← shifting-lattices

Shifting Lattices

A lattice distorted across the plane: a live formula of position builds a smoothly varying lattice field from the flowed base lattice, drawn as dots at self-consistent centres.

Source

common.glsl

// Shifting Lattices — take a lattice and distort it across the plane.
// The shared JS driver (script.js -> 2dFlowJS) flows the base lattice and
// cone-reduces it every frame, so uLattice stays bounded however long the
// flow runs. The distortion formula below maps each plane position (and
// time) to a lattice built from that bounded base; image.glsl renders dots
// at self-consistent centres of the resulting field. Bounded base x bounded
// distortion means the picture stays numerically clean indefinitely, and
// the renderer's basis covariance makes the driver's renormalisation jumps
// invisible.
//
// The distortion body is spliced in live from the UI's box (script.js
// recompiles this file; on a compile error the engine keeps the old field).
//
// Common code is compiled before the uniform declarations, so the formula
// receives uniforms as parameters (image.glsl reads them directly).

#include "../shared/2d_utils.glsl"
#include "../shared/coord_utils.glsl"

// Dot radius is the uDotRad uniform (image.glsl).

vec4 dotCol  = vec4(.8, .05, .04, 1.);
vec4 backCol = vec4(1., 1., 1., 1.);

// Flow matrices matching the JS driver (mathjs is row-major, GLSL mat2 is
// column-major, so the shear entries land in the opposite corner).
mat2 gFlow(in float d)  { return mat2(exp(d),0.,0.,exp(-d)); } // geodesic: stretch x, shrink y
mat2 hFlow(in float d)  { return mat2(1.,d,0.,1.); }           // horocyclic vertical: shears y by x
mat2 hFlowH(in float d) { return mat2(1.,0.,d,1.); }           // horocyclic horizontal: shears x by y
mat2 rot(in float d)    { return mat2(cos(d),sin(d),-sin(d),cos(d)); } // elliptic: rotation

// CP^2's Fubini-Study lattice family over its moment triangle (equilateral,
// centred at the origin, circumradius r, vertex up). At barycentric (a,b,c)
// the flat metric on the fiber torus has Gram matrix
// [[b(1-b), -bc], [-bc, c(1-c)]]; the Cholesky basis of that Gram matrix is
// returned, so the lattice is hexagonal at the barycenter and collapses one
// subtorus direction at each edge. Coordinates are clamped just inside the
// triangle to keep the basis invertible for the renderer; outside the
// triangle the field freezes at the nearest clamped value, so the edge
// degeneration continues outward (crop the view to the triangle by scale).
mat2 cp2Lattice(in vec2 p, in float r)
{
    vec3 bc = vec3(1./3.) + (2./(3.*r)) *
        vec3(p.y, dot(p, vec2(-.8660254, -.5)), dot(p, vec2(.8660254, -.5)));
    bc = clamp(bc, .05, .94);
    float d = bc.y*(1. - bc.y);
    return mat2(sqrt(d), 0., -bc.y*bc.z/sqrt(d), sqrt(max(bc.x*bc.y*bc.z, 1e-6)/d));
}

// First-order area correction for drawing the angular monodromy field
// L*hFlowH(sigma*theta) as dots. The dot construction shows the lattice
// mixed with the field's first differential: drawn cell area is
// det(D)/det(I-K), where K is the field gradient contracted with the dot's
// integer label. For this field K is rank one and its trace
// h = sigma*(inverse(L)*u).y*dot(L[0], perp(u)) depends only on the
// direction u, so pre-scaling the field by sqrt(1-h) restores the field's
// own cell area. The traceless part of K (an area-preserving shape error)
// remains; removing it too would need the field to be integrable.
float areaFix(in vec2 p, in mat2 L, in float sigma)
{
    vec2 u = normalize(p);
    float h = sigma * (inverse(L)*u).y * dot(L[0], vec2(-u.y, u.x));
    return sqrt(max(1. - h, .25));
}

// Matrix upgrade of areaFix. The differential's correction (I-K) acts on the
// drawn cell as a full matrix: its trace changes area, its traceless part
// shears the shape, and a scalar fix can only touch the trace (its own
// angular gradient then feeds the shape error). This pre-multiplier combines
// the L2-balanced rank-one correction (I - c*b1 u^T), which halves the error
// energy, with an exact first-order area rescale. The remaining error is the
// rigid anholonomy residue of the family, which corrections can only
// redistribute, never remove.
mat2 latticeFix(in vec2 p, in mat2 L, in float sigma)
{
    vec2 u = normalize(p);
    vec2 v = vec2(-u.y, u.x);
    vec2 b1 = L[0];
    float g  = (inverse(L)*u).y;
    float gp = (inverse(L)*v).y;
    float f = -.5*sigma*gp;
    float c = f/(1. + f*dot(u, b1));
    float tr = -.5*sigma*(gp*dot(b1, u) + g*dot(b1, v));
    return inversesqrt(max(1. - tr, .25)) * (mat2(1.) - c*outerProduct(b1, u));
}

// Lagrange-Gauss reduction: shortest basis for the lattice spanned by lat.
// 8 steps is plenty for anything floats can represent; exits early once
// reduced.
mat2 gaussReduce(in mat2 lat)
{
    vec2 b1 = lat[0];
    vec2 b2 = lat[1];

    for (int i = 0; i < 8; i++)
    {
        if (dot(b1,b1) > dot(b2,b2)) { vec2 t = b1; b1 = b2; b2 = t; }
        float m = round(dot(b1,b2)/dot(b1,b1));
        if (m == 0.) { break; }
        b2 = b2 - m*b1;
    }

    return mat2(b1,b2);
}

// Nearest point of the lattice spanned by M to p, as an integer label in M's
// own columns. Rounding in a skew basis picks a point up to half its longest
// basis vector away, so the search happens in the Gauss-reduced basis; the
// label is then converted back to M's columns. This makes the renderer
// basis-covariant: two bases of the same lattice give the same dots, so the
// driver's cone reduction never causes a visual jump.
vec2 nearestN(in mat2 M, in vec2 p)
{
    mat2 R = gaussReduce(M);
    vec2 z = R*round(inverse(R)*p);
    return round(inverse(M)*z);
}

// === Distortion formula — edited live from the UI ===
// Maps plane position (and time) to a lattice built from the flowed base.
// Available: x, y  screen position ((0,0) at the centre, y from -0.5 to 0.5),
//            t     elapsed time in seconds (iTime),
//            L     the flowed, renormalised base lattice (uLattice),
//            M     a free matrix uniform for UI layers (uFieldMat),
//            a     the Strength slider (uFieldAmt),
// plus gFlow(d), hFlow(d), hFlowH(d), rot(d), cp2Lattice(p, r),
// areaFix(p, L, sigma), latticeFix(p, L, sigma) and all of GLSL.
// For monodromy fields (integer jumps that should render seamlessly), the
// jump matrix must preserve the lattice, which means multiplying it on the
// RIGHT of L so it acts on L's integer coordinates: L*hFlowH(s), not
// hFlowH(s)*L. A left-multiplied integer shear preserves only the square
// lattice, so it shows a seam for any other L. Note the driver's
// renormalisation is only invisible for left factors, so right-multiplied
// monodromy formulas want the flow speed at 0.
// Formulas return the target field itself: the renderer (image.glsl's
// latticeAt) draws the inverse of the ray-averaged coframe automatically,
// so fields varying along rays render first-order exactly with no change
// to the formula. Only the coframe's curl (the anholonomy) survives that
// correction, which is what areaFix/latticeFix compensate for the angular
// monodromy field. Full analysis in _notes/rendering-error-analysis.md.
// script.js splices the distortion box's expression into the tagged line.
mat2 distortMat(in float x, in float y, in float t, in mat2 L, in mat2 M, in float a)
{
    return hFlowH(a*x) * L; //<DISTORT>
}

image.glsl

// Renders the lattice field as round dots at self-consistent centres.
// latticeAt and drShiftGrid live here rather than in common.glsl so they can
// read the uniforms directly (common code is compiled before them).

// Plane position -> lattice: the distortion field applied to the flowed,
// renormalised base lattice.
mat2 fieldAt(in vec2 q)
{
    return distortMat(q.x, q.y, iTime, mat2(uLattice), mat2(uFieldMat), uFieldAmt);
}

// The Stamp slider zooms the image as it grows the stamps: the effective
// scale is the Scale slider divided by the stamp factor.
float effScale()
{
    return uScale / sqrt(uStamp);
}

// The dot chart Phi(s) = latticeAt(s)^-1 * s should be the line integral of
// the field's coframe along the ray from the origin; using the field's
// endpoint value instead makes the drawn lattice first-order wrong wherever
// the coframe varies along rays (see _notes/rendering-error-analysis.md).
// So return the inverse of the ray-averaged coframe. The integral is done
// by composite two-point Gauss quadrature with a fixed step in formula
// units, so accuracy does not degrade with distance and no symmetry or
// polynomial form is assumed of the field: any smooth field is integrated
// to O(step^4), ray-constant fields (like the monodromy formulas) are
// exact with any step, and the nodes never sample the origin. Only the
// coframe's curl survives this correction (it is path-dependent; the ray
// family is one choice, and no choice removes it).
mat2 latticeAt(in vec2 p)
{
    vec2 q = p / effScale();
    const float SEG = 0.1;   // segment length in formula units
    const int MAXSEG = 16;
    int n = int(clamp(ceil(length(q) / SEG), 1.0, float(MAXSEG)));
    float h = 1.0 / float(n);
    mat2 A = mat2(0.);
    for (int i = 0; i < MAXSEG; i++) {
        if (i >= n) { break; }
        float t0 = float(i) * h;
        A += 0.5 * h * inverse(fieldAt((t0 + 0.2113249*h) * q));
        A += 0.5 * h * inverse(fieldAt((t0 + 0.7886751*h) * q));
    }
    return inverse(A);
}

// Local drawing distortion for the dot shape: the drawn basis against the
// field basis, M = B * dPhi, measured by central differences of the chart
// Phi(s) = latticeAt(s)^-1 * s at quarter-cell scale. M = I exactly where
// the family is integrable; its deviation is the curl residue E in the
// form E*B^-1 (see _notes/rendering-error-analysis.md). Across a monodromy
// branch cut the chart jumps by an integer relabeling, which would swamp
// the stencil; such jumps are detected by their size and the display falls
// back to a round dot in the thin band the stencil straddles.
// Chart value at a point (integer values of this are the dots).
vec2 chartAt(in vec2 p)
{
    return inverse(latticeAt(p)) * p;
}

// One robust chart derivative along direction e: forward and one-sided
// backward differences are compared, and if they disagree badly (the
// stencil straddles a monodromy cut, where the chart jumps by an integer
// relabeling and a straddling difference measures the jump, not the
// derivative) the clean side is used alone. No smoothing or capping is
// applied to the value itself: extreme fields report extreme derivatives.
vec2 chartDeriv(in vec2 phi0, in vec2 s, in vec2 e, in float d)
{
    vec2 f = chartAt(s + d*e) - phi0;
    vec2 b = phi0 - chartAt(s - d*e);
    if (length(f - b) > 0.5 * max(length(f), length(b))) {
        return (length(f) < length(b) ? f : b) / d;
    }
    return (f + b) / (2.*d);
}

mat2 shapeAt(in vec2 s, in mat2 B)
{
    mat2 Rb = gaussReduce(B);
    float d = 0.25 * min(length(Rb[0]), length(Rb[1]));
    vec2 phi0 = chartAt(s);
    return B * mat2(chartDeriv(phi0, s, vec2(1.,0.), d),
                    chartDeriv(phi0, s, vec2(0.,1.), d));
}

// Round dot at each lattice point of the field. A dot's centre is the
// self-consistent position s = latticeAt(s)*n: the point sits where the
// field at its own position puts it. Solved by fixed-point iteration seeded
// from the pixel's own lattice. The label n is re-selected in the current
// basis after every step: the label is only meaningful in the basis it was
// selected in, and monodromy fields have branch cuts where the basis jumps
// while the lattice does not, so a label carried across the cut lands on
// the wrong point and fades a line of dots along the cut.
vec4 drShiftGrid(in vec4 pC, in vec2 p, in float r, in vec4 col, in float exp)
{
    vec2 n = nearestN(latticeAt(p), p);

    vec2 s = p;
    for (int i = 0; i < 4; i++) {
        s = latticeAt(s)*n;
        n = nearestN(latticeAt(s), p);
    }

    // Convergence check: apply the map once more and measure how far the
    // centre still moves. Where the field's spatial gradient is too steep
    // (e.g. a shear field amplified along the unstable direction of the
    // geodesic flow) the fixed point stops existing; fade the dot out there
    // instead of drawing flickering garbage.
    vec2 s2 = latticeAt(s)*n;
    float ok = clamp(1. - 4.*length(s2 - s)/r, 0., 1.);
    s = s2;

    // The Stamp slider morphs each dot into a circular stamp of its local
    // lattice: the circle radius grows as r*uStamp while the lattice
    // inside is drawn at relative scale 1/uStamp with faithfully scaled
    // dots. At uStamp = 1 the only lattice point inside the circle is the
    // centre itself, so the stamp degenerates to the plain dot. Each
    // lattice point fades in and out as a whole dot: transparency 0 when
    // its centre sits on the circle's boundary, 1 once the whole dot lies
    // inside, so dots never pop or get cut by the circle's edge.
    // With uShowE each dot displays the nature of E: it is drawn as the
    // image of a round dot under the local drawing distortion, so dots
    // are circles exactly where the family is integrable and shear into
    // ellipses where the curl residue acts.
    if (ok > 0.) {
        mat2 B = fieldAt(s / effScale());
        mat2 M = mat2(1.);
        if (uShowE) { M = shapeAt(s, B); }
        float c = 1. / uStamp;
        // The circle grows with the slider but stays inside the centre's
        // cell of the arrangement, so included lattice points are always
        // drawn whole rather than cut by a neighbouring stamp; the
        // on-screen growth beyond that comes from the zoom.
        mat2 Ra = gaussReduce(latticeAt(s));
        float win = min(r * uStamp, 0.45 * min(length(Ra[0]), length(Ra[1])));
        vec2 o = p - s;
        vec2 om = c * (B * nearestN(B, o / c));
        float edgeA = clamp((win - length(om)) / (c * r), 0., 1.);
        if (edgeA > 0.) {
            float l = length(M * (o - om)) / c;
            if (l < r) { pC = mix(pC, col, pow((r - l)/r, exp)*col.a*ok*edgeA); }
        }
    }
    return pC;
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 p = coords(fragCoord, iResolution, effScale(), iResolution.xy * 0.5);

    vec4 col = backCol;

    col = drShiftGrid(col, p, uDotRad, dotCol, 0.15);

    fragColor = col;
}

script.js

// Shifting Lattices UI: the live distortion formula box on top of the shared
// lattice driver. The driver flows uLattice and cone-reduces it every frame
// (so it stays bounded forever) and handles the CF inputs; applying a formula
// splices the distortion box into the pristine common.glsl held by the engine
// and hot-recompiles via the script API. On a compile error the engine keeps
// the old distortion and the error is shown as an overlay.
import { createLatticeDriver } from '../shared/lattice_driver.js';

const driver = createLatticeDriver();

export const setup = driver.setup;
export const onSetLattice = driver.onSetLattice;

let status = null;   // overlay text
let statusTtl = 0;   // frames left to show it; Infinity keeps errors up

export function onFrame(engine, time, deltaTime, frame) {
  driver.onFrame(engine, time, deltaTime, frame);

  if (status !== null) {
    engine.setOverlay('bottom-left', status);
    statusTtl -= 1;
    if (statusTtl <= 0) {
      engine.setOverlay('bottom-left', null);
      status = null;
    }
  }
}

// Single-line match only ([^;\n]) — a multi-line match can start at the word
// "return" inside a doc comment and swallow the function signature.
const DISTORT_MARKER = /return[^;\n]*;[ \t]*\/\/<DISTORT>/;

export function onApplyFormula(inputs, engine) {
  const expr = (inputs.distortFormula ?? '').trim();
  if (expr === '') { return; }

  // The engine hands the transform the pristine common.glsl (as first
  // mounted), so a broken formula can't wedge later ones and reapplying
  // after a remount reproduces the same state.
  let markerFound = false;
  const result = engine.recompilePass('common', (source) => {
    markerFound = DISTORT_MARKER.test(source);
    if (!markerFound) { return source; }
    return source.replace(DISTORT_MARKER, `return (${expr}); //<DISTORT>`);
  });

  if (!markerFound) {
    status = 'Distortion: //<DISTORT> marker missing from common.glsl';
    statusTtl = 300;
  } else if (result.success) {
    status = `distortion = ${expr}`;
    statusTtl = 240;
  } else {
    const first = result.errors[0];
    const message = first ? first.error : 'unknown error';
    status = `GLSL error — ${message.slice(0, 300)}`;
    statusTtl = Infinity;
  }
}