// The neiam moire wallpaper, in the browser. From party-slut's
// assets/f/js/shader_field.js (itself neiam-org's), with recourse's extra
// themes and a pause while the tab is hidden. The fragment shader is neiam-device's
// moire/shaders/field.frag, copied unchanged into ./shaders/ (copy it
// again when it changes there; esbuild inlines it as text); `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" and "spheres" patterns are neiam-org's
// own, copied into ./shaders/ (and shader_balls.js with them), in the
// same header style; each gets its own program, picked per frame. Bubbles' and spheres' discs are moved
// in shader_balls.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 { Bubbles, Absorbers } from "./shader_balls"
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. recourse builds all but blueprint,
// plus daisyUI's lofi and black (greys of their own, last two below);
// blueprint rides along so the theme already has its colours here.
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"],
lofi: ["#ffffff", "#ebebeb", "#000000", "#808080"],
black: ["#141414", "#000000", "#d4d4d4", "#737373"],
}
export const themeColours = name => (THEMES[name] || THEMES.dark).map(hex)
// root.html sets data-theme before first paint, system theme included.
export const siteTheme = () => document.documentElement.getAttribute("data-theme") || "dark"
// 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,
}
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()
}
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
}
advance(dt, s, colours) {
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)
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() : {}),
}
}
}
// Fired on window whenever the settings change (shader_background.js).
export const SETTINGS_EVENT = "app:shader-settings"
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 }
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
}
}
const draw = dt => {
resize()
const s = { ...DEFAULTS, ...settings() }
motion.advance(dt, s, themeColours(s.theme || siteTheme()))
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 || document.hidden) return
if (reducedMotion() && !settings().alwaysMove) {
// One settled frame, redrawn on demand (resize, theme, settings).
draw(10)
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(SETTINGS_EVENT, kick)
// A hidden tab draws nothing (browsers mostly stop rAF there anyway);
// back in view, carry on without a jump.
const shown = () => {
last = 0
if (!document.hidden) kick()
}
document.addEventListener("visibilitychange", shown)
kick()
return {
redraw: kick,
destroy() {
cancelAnimationFrame(raf)
seen.disconnect()
sized.disconnect()
themed.disconnect()
window.removeEventListener(SETTINGS_EVENT, kick)
document.removeEventListener("visibilitychange", shown)
gl.getExtension("WEBGL_lose_context")?.loseContext()
},
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
14.2 KiB · text
History
0297141