17.0 KiB · text History 3208487
// The neiam moire wallpaper, in the browser: neiam-org's
// assets/js/shader_field.js, with Vigil's themes. The fragment shader is
// neiam-device's moire/shaders/field.frag, copied unchanged into
// assets/shaders/ (copy it again when it changes there); `toGles`
// rewrites only its Qt header for WebGL2, as droid/Shader.kt does.
// `Motion` is a port of droid/Motion.kt (itself Field.qml's): everything
// that moves is advanced here in double precision and handed to the
// shader as positions and wrapped phases.
//
// The "prism", "oil", "bubbles", "spheres" and "eyes" patterns are the
// site's own (assets/shaders/*.frag), in the same header style; each
// gets its own program, picked per frame. Bubbles' and spheres' discs
// are moved in shader_balls.js, the eyes' lives run in shader_eyes.js.
//
// Not ported: following the sun through night/sunrise/day/sunset, and
// the wordmark.

import FIELD from "../shaders/field.frag"
import PRISM from "../shaders/prism.frag"
import OIL from "../shaders/oil.frag"
import BUBBLES from "../shaders/bubbles.frag"
import SPHERES from "../shaders/spheres.frag"
import EYES from "../shaders/eyes.frag"
import { Bubbles, Absorbers } from "./shader_balls"
import { Eyes } from "./shader_eyes"

const VERTEX = `#version 300 es
in vec2 position;
out vec2 qt_TexCoord0;
void main()
{
    qt_TexCoord0 = vec2(position.x * 0.5 + 0.5, 0.5 - position.y * 0.5);
    gl_Position = vec4(position, 0.0, 1.0);
}
`

function toGles(qt) {
  const out = ["#version 300 es", "precision highp float;"]
  let inBlock = false
  for (const line of qt.split("\n")) {
    const t = line.trim()
    if (t.startsWith("#version")) continue
    else if (t.startsWith("layout(location")) out.push(t.slice(t.indexOf(")") + 1).trim())
    else if (t.startsWith("layout(std140")) inBlock = true
    else if (inBlock && t.startsWith("};")) inBlock = false
    else if (inBlock) {
      const m = line.match(/^\s*(\w+)\s+(\w+(?:\[\d+\])?)\s*;/)
      if (m) out.push(`uniform ${m[1]} ${m[2]};`)
    } else out.push(line)
  }
  return out.join("\n")
}

// neiam-device's themes (droid/Themes.kt, generated from waxx): ground,
// ground at the edges, moire, halftone. Vigil's themes (Vigil.Themes,
// assets/css/app.css) are the same catalog by name. A theme not listed
// here takes its colours from its daisyUI variables instead.
const hex = h => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16) / 255)
const THEMES = {
  dark: ["#292f37", "#13171c", "#d16671", "#b6797a"],
  light: ["#fef6f6", "#f3dfdd", "#000000", "#b6797a"],
  her: ["#661e1e", "#470005", "#fdf2c6", "#b6797a"],
  afterdark: ["#201e66", "#0e0048", "#fdf2c6", "#7b78b4"],
  forest: ["#062f17", "#001603", "#fdf2c6", "#48de81"],
  sky: ["#072e48", "#00152d", "#fdf2c6", "#37bcf7"],
  clays: ["#451a03", "#290200", "#fdf2c6", "#da780e"],
  stones: ["#292524", "#120f0e", "#fdf2c6", "#6b727f"],
  blueprint: ["#002661", "#001241", "#fdf2c6", "#0e9dff"],
}

// The fallback: base-100, base-300, primary and secondary as the theme
// defines them (oklch strings), turned into RGB by painting each into a
// pixel. Read once per theme name.
const fromCss = {}
function cssColours(name) {
  if (fromCss[name]) return fromCss[name]
  const probe = document.createElement("div")
  probe.setAttribute("data-theme", name)
  probe.style.display = "none"
  document.body.appendChild(probe)
  const style = getComputedStyle(probe)
  const ctx = document.createElement("canvas").getContext("2d", { willReadFrequently: true })
  const rgb = v => {
    ctx.clearRect(0, 0, 1, 1)
    ctx.fillStyle = "#000"
    ctx.fillStyle = v.trim() || "#000"
    ctx.fillRect(0, 0, 1, 1)
    const d = ctx.getImageData(0, 0, 1, 1).data
    return [d[0] / 255, d[1] / 255, d[2] / 255]
  }
  const out = ["--color-base-100", "--color-base-300", "--color-primary", "--color-secondary"].map(v =>
    rgb(style.getPropertyValue(v)),
  )
  probe.remove()
  return (fromCss[name] = out)
}
export const themeColours = name => (THEMES[name] ? THEMES[name].map(hex) : cssColours(name))
// The root layout's script sets data-theme before first paint, "System"
// resolved to light or dark.
export const siteTheme = () => document.documentElement.getAttribute("data-theme") || "light"

// Same names and defaults as the Plasma wallpaper's settings.
export const DEFAULTS = {
  pattern: "both",
  fadeFrom: "moire",
  fadeTo: "halftone",
  lights: 14,
  speed: 1,
  glints: false,
  breathing: false,
  foreground: false,
  grain: false,
  dither: true,
  prismAngle: 20,
  prismSides: 3,
  prismRays: 7,
  prismSlow: false,
  // Animate even when the system asks for reduced motion.
  alwaysMove: false,
  bubbleCount: 12,
  sphereCount: 32,
  oilCoverage: 50,
  eyeCount: 5,
  // The largest eye's size over the smallest's.
  eyeRatio: 3,
}

const LAYERS = ["moire", "halftone", "bokeh", "stars"]
const layerOf = (name, layer) =>
  layer === name || (name === "both" && (layer === "moire" || layer === "halftone")) ? 1 : 0

class Motion {
  constructor() {
    // A random start, so two fields on one page never mirror each other.
    this.clock = Math.random() * 10000
    this.frame = 0
    this.eased = {}
    this.colours = null
    this.from = null
    this.to = null
    this.t = 1
    this.spin = Math.random() * 2 * Math.PI
    this.rayTurn = Math.random() * 2 * Math.PI
    this.stepClock = 0
    this.extent = [16 / 9, 1]
    this.bubbles = new Bubbles()
    this.absorbers = new Absorbers()
    this.eyes = new Eyes()
  }

  sweep(period, phase) {
    return Math.sin(2 * Math.PI * (this.clock / period + phase))
  }

  amount(layer, s) {
    if (s.pattern === "alternate") {
      const t = 0.5 + 0.5 * this.sweep(360, 0)
      return layerOf(s.fadeFrom, layer) * (1 - t) + layerOf(s.fadeTo, layer) * t
    }
    return layerOf(s.pattern, layer)
  }

  ease(key, target, dt, seconds = 1.5) {
    const now = this.eased[key] ?? target
    const step = dt / seconds
    const next = Math.abs(target - now) <= step ? target : now + Math.sign(target - now) * step
    this.eased[key] = next
  }

  // `still`: one settled frame for reduced motion. `pointer`: where
  // the pointer is, in shader units, for the eyes ({ x, y, active }).
  advance(dt, s, colours, still = false, pointer = null) {
    const step = s.speed * Math.min(dt, 0.25)
    this.clock += step
    // Prism's turns are accumulated rather than taken from the clock, so
    // switching between the two motions carries on from where they are.
    // Slow spin: a steady turn, the shape every 2 min and the rays every
    // 160 s. Otherwise both hold still, then every 15 s turn one step
    // (a side of the shape, one ray's spacing) over 2 s, eased.
    const wrap = a => a % (2 * Math.PI)
    if (s.prismSlow) {
      this.spin = wrap(this.spin + (2 * Math.PI * step) / 120)
      this.rayTurn = wrap(this.rayTurn + (2 * Math.PI * step) / 160)
    } else {
      const steps = t => {
        const f = Math.min(1, (t % 15) / 2)
        return Math.floor(t / 15) + f * f * (3 - 2 * f)
      }
      const before = steps(this.stepClock)
      this.stepClock += step
      const moved = steps(this.stepClock) - before
      this.spin = wrap(this.spin + (moved * 2 * Math.PI) / (s.prismSides >= 3 ? s.prismSides : 6))
      this.rayTurn = wrap(this.rayTurn + (moved * 2 * Math.PI) / Math.max(1, s.prismRays))
    }
    if (s.pattern === "bubbles") this.bubbles.step(step, this.extent, s.bubbleCount)
    if (s.pattern === "spheres") this.absorbers.step(step, this.extent, s.sphereCount)
    if (s.pattern === "eyes") {
      // Held still: open, looking ahead.
      if (still) this.eyes.settle(this.extent, s.eyeCount, s.eyeRatio)
      else this.eyes.step(step, this.extent, s.eyeCount, s.eyeRatio, pointer)
    }
    this.frame = (this.frame + 1) % 100000

    const key = JSON.stringify(colours)
    if (!this.colours) {
      this.colours = colours
      this.to = key
    } else if (key !== this.to) {
      this.from = this.colours
      this.target = colours
      this.to = key
      this.t = 0
    }
    if (this.t < 1) {
      this.t = Math.min(1, this.t + dt / 4)
      this.colours = this.from.map((c, i) => c.map((v, j) => v + (this.target[i][j] - v) * this.t))
    }

    const direct = s.pattern === "alternate"
    for (const layer of LAYERS) {
      const a = this.amount(layer, s)
      if (direct) this.eased[layer] = a
      else this.ease(layer, a, dt)
    }
    this.ease("flare", s.foreground ? 1 : 0, dt)
    this.ease("glints", s.glints ? 1 : 0, dt)
    this.ease("grain", s.grain ? 1 : 0, dt)
    this.ease("breathe", s.breathing ? 1 : 0, dt)
  }

  uniforms(width, height, s) {
    const shorter = Math.max(1, Math.min(width, height))
    // The rings and dots are sized for a full screen (~1000 px on the
    // short side); on anything much smaller they fall below a pixel
    // apart and blur into a glow, so scale them up to keep their look.
    const zoom = Math.min(6, Math.max(1, 1000 / shorter))
    const ex = width / shorter
    const ey = height / shorter
    this.extent = [ex, ey]
    const hub = [0.62 * ex + 0.05 * this.sweep(97, 0), 0.46 * ey + 0.04 * this.sweep(131, 0.3)]
    const spread = 0.03 * (1 + 0.35 * this.sweep(71, 0.1))
    const turn = (2 * Math.PI * this.clock) / 53
    const e = this.eased
    const breathe = e.breathe || 0
    const c = this.colours
    const rgba = x => [x[0], x[1], x[2], 1]

    return {
      qt_Opacity: [1],
      size: [width, height],
      hub,
      ringA: [hub[0] - (spread * Math.cos(turn)) / 2, hub[1] - (spread * Math.sin(turn)) / 2],
      ringB: [hub[0] + (spread * Math.cos(turn)) / 2, hub[1] + (spread * Math.sin(turn)) / 2],
      reach: [0.95 + 0.06 * this.sweep(43, 0.7) + 0.08 * breathe * this.sweep(16, 0)],
      period: [zoom / 110],
      moire: [e.moire || 0],
      halftone: [e.halftone || 0],
      cell: [zoom / 70],
      angle: [0.26 + 0.03 * this.sweep(211, 0.2)],
      wave: [((2 * Math.PI * this.clock) / 16) % (2 * Math.PI)],
      bokeh: [e.bokeh || 0],
      lights: [s.lights],
      flare: [e.flare || 0],
      drift: [(this.clock / 600) % 1],
      stars: [e.stars || 0],
      twinkle: [(this.clock / 12) % 1],
      glints: [e.glints || 0],
      glintPhase: [(this.clock / 90) % 1],
      breath: [1 - 0.2 * breathe * (0.5 - 0.5 * this.sweep(16, 0))],
      grain: [e.grain || 0],
      dither: [s.dither ? 1 : 0],
      seed: [(this.frame * 0.618034) % 1],
      base: rgba(c[0]),
      deep: rgba(c[1]),
      ink: rgba(c[2]),
      tone: rgba(c[3]),
      // Prism
      centre: [0.5 * ex + 0.03 * this.sweep(97, 0), 0.5 * ey + 0.03 * this.sweep(131, 0.3)],
      radius: [0.15],
      sides: [s.prismSides],
      spin: [this.spin],
      beamAngle: [(s.prismAngle * Math.PI) / 180],
      rays: [s.prismRays],
      rayTurn: [this.rayTurn],
      cycle: [(this.clock / 900) % 1],
      // Oil on glass
      oilCycle: [(this.clock / 240) % 1],
      coverage: [s.oilCoverage / 100],
      // Bubbles, Absorbing spheres
      ...(s.pattern === "bubbles" ? this.bubbles.pack() : {}),
      ...(s.pattern === "spheres" ? this.absorbers.pack() : {}),
      // Eyes
      ...(s.pattern === "eyes" ? this.eyes.pack() : {}),
    }
  }
}

const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

// Draws the field into `canvas` until destroyed. `settings()` is read
// every frame, so callers change it by changing what it returns.
// Options: fps (frame cap), scale (device pixels per CSS pixel, capped).
// Returns { destroy }, or null where WebGL2 is unavailable.
export function createField(canvas, settings, { fps = 30, maxScale = 1.5 } = {}) {
  const gl = canvas.getContext("webgl2", { antialias: false, alpha: false, preserveDrawingBuffer: false })
  if (!gl) return null

  const compile = (type, src) => {
    const sh = gl.createShader(type)
    gl.shaderSource(sh, src)
    gl.compileShader(sh)
    if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(sh))
    return sh
  }
  // Each program is built the first time its pattern is drawn, with
  // the position attribute at 0 in both so one buffer setup serves.
  const sources = { field: FIELD, prism: PRISM, oil: OIL, bubbles: BUBBLES, spheres: SPHERES, eyes: EYES }
  const programs = {}
  const programFor = pattern => {
    const name = pattern in sources ? pattern : "field"
    if (!programs[name]) {
      const program = gl.createProgram()
      gl.attachShader(program, compile(gl.VERTEX_SHADER, VERTEX))
      gl.attachShader(program, compile(gl.FRAGMENT_SHADER, toGles(sources[name])))
      gl.bindAttribLocation(program, 0, "position")
      gl.linkProgram(program)
      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(program))
      programs[name] = { program, locations: {} }
    }
    return programs[name]
  }
  programFor("field")

  const buffer = gl.createBuffer()
  gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW)
  gl.enableVertexAttribArray(0)
  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)

  const motion = new Motion()
  let raf = 0
  let last = 0
  let visible = true

  const resize = () => {
    const scale = Math.min(window.devicePixelRatio || 1, maxScale)
    const w = Math.max(1, Math.round(canvas.clientWidth * scale))
    const h = Math.max(1, Math.round(canvas.clientHeight * scale))
    if (canvas.width !== w || canvas.height !== h) {
      canvas.width = w
      canvas.height = h
    }
  }

  // Where the pointer is, for the eyes: mouse, pen or touch, heard on
  // the window (a background canvas sits behind the page and gets no
  // events of its own), and only while the pattern is eyes. It goes
  // idle a few seconds after it last moved, or soon after a touch ends.
  const IDLE = 5000
  let pointer = null
  let listening = false
  const track = (x, y, idleIn = IDLE) => {
    pointer = { x, y, until: performance.now() + idleIn }
  }
  const onPointer = e => track(e.clientX, e.clientY, e.type === "pointerup" && e.pointerType !== "mouse" ? 1500 : IDLE)
  const onTouch = e => {
    const t = e.touches[0]
    if (t) track(t.clientX, t.clientY)
  }
  const onOut = e => {
    if (!e.relatedTarget) pointer = null
  }
  const pointerEvents = [
    ["pointermove", onPointer],
    ["pointerdown", onPointer],
    ["pointerup", onPointer],
    ["touchstart", onTouch],
    ["touchmove", onTouch],
    ["pointerout", onOut],
  ]
  const listen = on => {
    if (on === listening) return
    listening = on
    for (const [name, fn] of pointerEvents) {
      if (on) window.addEventListener(name, fn, { passive: true })
      else window.removeEventListener(name, fn)
    }
    if (!on) pointer = null
  }
  // In shader units: the canvas's shorter side is 1, y down.
  const pointerAt = () => {
    if (!pointer) return null
    const rect = canvas.getBoundingClientRect()
    const shorter = Math.max(1, Math.min(rect.width, rect.height))
    return {
      x: (pointer.x - rect.left) / shorter,
      y: (pointer.y - rect.top) / shorter,
      active: performance.now() < pointer.until,
    }
  }

  const draw = (dt, still = false) => {
    resize()
    const s = { ...DEFAULTS, ...settings() }
    listen(s.pattern === "eyes" && !still)
    motion.advance(dt, s, themeColours(s.theme || siteTheme()), still, s.pattern === "eyes" ? pointerAt() : null)
    const { program, locations } = programFor(s.pattern)
    gl.useProgram(program)
    gl.viewport(0, 0, canvas.width, canvas.height)
    for (const [name, v] of Object.entries(motion.uniforms(canvas.width, canvas.height, s))) {
      if (!(name in locations)) locations[name] = gl.getUniformLocation(program, name)
      const loc = locations[name]
      if (!loc) continue
      if (typeof v === "number") gl.uniform1f(loc, v)
      else if (v.length > 4) gl.uniform4fv(loc, v)
      else if (v.length === 1) gl.uniform1f(loc, v[0])
      else if (v.length === 2) gl.uniform2f(loc, v[0], v[1])
      else gl.uniform4f(loc, v[0], v[1], v[2], v[3])
    }
    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
  }

  const tick = now => {
    raf = 0
    if (!visible) return
    if (reducedMotion() && !settings().alwaysMove) {
      // One settled frame, redrawn on demand (resize, theme, settings).
      draw(10, true)
      return
    }
    if (!last || now - last >= 1000 / fps - 2) {
      draw(last ? (now - last) / 1000 : 0)
      last = now
    }
    raf = requestAnimationFrame(tick)
  }
  const kick = () => {
    if (!raf) raf = requestAnimationFrame(tick)
  }

  // Off screen (a preview scrolled away), stop drawing.
  const seen = new IntersectionObserver(([entry]) => {
    visible = entry.isIntersecting
    last = 0
    if (visible) kick()
  })
  seen.observe(canvas)
  const sized = new ResizeObserver(kick)
  sized.observe(canvas)
  const themed = new MutationObserver(kick)
  themed.observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] })
  window.addEventListener("vigil:shader-settings", kick)
  kick()

  return {
    redraw: kick,
    destroy() {
      cancelAnimationFrame(raf)
      seen.disconnect()
      sized.disconnect()
      themed.disconnect()
      window.removeEventListener("vigil:shader-settings", kick)
      listen(false)
      gl.getExtension("WEBGL_lose_context")?.loseContext()
    },
  }
}