import type { PageScope } from './page-scope'; import type { RenderSurface, DisplayClock, ArtEffects } from './render-surface'; import { inViewport } from './render-surface'; import { motionPaused } from './motion'; import { pixelSize, glyphGrid, alignToPixelGrid, snapPixel } from './pixel-grid'; import { artworkTexture } from './art-textures'; import { asciiAtlas, asciiFont } from './ascii-atlas'; import fragment from './dither.frag.glsl?raw'; import { between, ease } from '../lib/math'; import { webgl } from './webgl'; const chroma = { initial: [4000, 14000], interval: [11000, 29000], duration: [45, 110], strength: [1, 3], speed: [0.43, 0.31], amplitude: [0.8, 0.65], phase: 1.7, velocityScale: 36, velocityStrength: 1.3, } as const; const movement = { ease: 0.14, deltaLimit: 0.1, deltaFloor: 0.016, x: 32, y: 24, scroll: -40, phaseRange: 600, pointerLife: 800, pointerDecay: 150, offscreen: -10, }; const vertex = `attribute vec2 position; varying vec2 uv; void main() { uv = position * .5 + .5; gl_Position = vec4(position, 0., 1.); }`; export function createArtSurface( element: HTMLElement, scope: PageScope, clock: DisplayClock, effects: ArtEffects, ): RenderSurface | undefined { const canvas = element.querySelector('canvas')!; const image = element.querySelector('.dither-source')!; const gpu = webgl(canvas, scope, vertex, fragment); if (!gpu) return; const { gl, set } = gpu; gl.bufferData( gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]), gl.STATIC_DRAW, ); gpu.attribute('position', 2); const imageTexture = gpu.texture('image', 0, gl.LINEAR); const toneTexture = gpu.texture('toneMap', 2, gl.LINEAR); const glyphTexture = gpu.texture('glyphs', 1); set({ breathing: 1, stationSymbol: element.hasAttribute('data-moon-sway') ? 1 : 0, glyphCell: [glyphGrid.width, glyphGrid.height], pointer: [movement.offscreen, movement.offscreen], }); let bounds = element.getBoundingClientRect(); let rasterWidth = 1, rasterHeight = 1, sized = false; let nextChroma = between(...chroma.initial), chromaUntil = 0, chromaStrength = 0; const phase = between(0, movement.phaseRange); alignToPixelGrid(canvas); const target = [0, 0], parallax = [0, 0], cursor = [movement.offscreen, movement.offscreen]; let scrollDrift = 0, previousTime = 0, pointerAt = -Infinity, lastX = -Infinity, lastY = -Infinity, revealed = false; const surface: RenderSurface = { dirty: true, visible: inViewport(bounds), ready: false, draw(time) { // A backing-store resize clears WebGL. Resize and paint in this same frame. if (!sized || canvas.width !== rasterWidth || canvas.height !== rasterHeight) { sized = true; canvas.width = rasterWidth; canvas.height = rasterHeight; canvas.style.width = `${rasterWidth * pixelSize}px`; canvas.style.height = `${rasterHeight * pixelSize}px`; gl.viewport(0, 0, rasterWidth, rasterHeight); set({ resolution: [rasterWidth, rasterHeight] }); } const moving = !motionPaused(); if (moving && time >= nextChroma) { chromaUntil = time + between(...chroma.duration); chromaStrength = between(...chroma.strength); nextChroma = chromaUntil + between(...chroma.interval); } const delta = Math.min(movement.deltaLimit, (time - previousTime) / 1000); const fraction = ease(delta, movement.ease); previousTime = time; const dx = (target[0] - parallax[0]) * fraction; const dy = (target[1] + scrollDrift - parallax[1]) * fraction; parallax[0] += dx; parallax[1] += dy; const drift = (distance: number) => Math.tanh(distance / Math.max(movement.deltaFloor, delta) / chroma.velocityScale) * chroma.velocityStrength; const chromaTime = time / 1000 + phase; set({ moonSway: moving && element.hasAttribute('data-moon-sway') ? 1 : 0, chroma: moving && time < chromaUntil ? chromaStrength : 0, chromaDrift: [ moving ? Math.sin(chromaTime * chroma.speed[0]) * chroma.amplitude[0] + drift(dx) : 0, moving ? Math.sin(chromaTime * chroma.speed[1] + chroma.phase) * chroma.amplitude[1] + drift(dy) : 0, ], parallax: parallax.map((value) => value / pixelSize), pointer: cursor, pointerEnergy: moving && time - pointerAt < movement.pointerLife ? Math.exp(-(time - pointerAt) / movement.pointerDecay) : 0, time: time / 1000 + phase, ...effects, }); gl.drawArrays(gl.TRIANGLES, 0, 6); if (!revealed) { element.classList.add('ready'); revealed = true; } }, }; function resize() { bounds = element.getBoundingClientRect(); rasterWidth = Math.max(1, Math.ceil(bounds.width / pixelSize)); rasterHeight = Math.max(1, Math.ceil(bounds.height / pixelSize)); surface.dirty = true; clock.schedule(); } async function upload() { if (!image.naturalWidth) return; const source = image.src; surface.ready = false; revealed = false; element.classList.remove('ready'); let prepared; try { prepared = await artworkTexture(image); } catch (error) { if (!scope.signal.aborted) console.warn('Could not prepare artwork.', error); return; } // Navigation can finish before this source's worker does. if (scope.signal.aborted || image.src !== source || gl.isContextLost()) return; const focus = (element.dataset.focus || '.5,.5').split(',').map(Number); set({ focus: [focus[0], 1 - focus[1]], exposure: Number(element.dataset.exposure || 0) }); imageTexture(prepared.image); toneTexture(prepared.tone); set({ sourceSize: [image.naturalWidth, image.naturalHeight] }); surface.ready = true; resize(); } function uploadGlyphs(atlas: HTMLCanvasElement) { if (scope.signal.aborted) return; glyphTexture(atlas, { flip: true }); surface.dirty = true; clock.schedule(); } const atlas = asciiAtlas(); uploadGlyphs(atlas.canvas); if (!atlas.ready) document.fonts.load(asciiFont).then(() => uploadGlyphs(asciiAtlas().canvas)); if (image.complete) upload(); scope.on(image, 'load', upload); scope.observe(new ResizeObserver(resize)).observe(element); scope.intersect([element], (entry) => { surface.visible = entry.intersectionRatio > 0; if (surface.visible) clock.schedule(); }); const pointerSurface = element.closest('[data-reactive-art]') || element; scope.on(pointerSurface, 'pointerenter', () => { bounds = element.getBoundingClientRect(); }); scope.on( pointerSurface, 'pointermove', (event) => { if (motionPaused() || !surface.visible) return; const x = snapPixel(event.clientX), y = snapPixel(event.clientY); if (x === lastX && y === lastY) return; lastX = x; lastY = y; cursor[0] = (x - bounds.left) / bounds.width; cursor[1] = 1 - (y - bounds.top) / bounds.height; pointerAt = cursor.every((value) => value >= 0 && value <= 1) ? clock.time : -Infinity; target[0] = (x / innerWidth - 0.5) * movement.x; target[1] = (0.5 - y / innerHeight) * movement.y; surface.dirty = true; clock.schedule(); }, { passive: true }, ); scope.on(pointerSurface, 'pointerleave', () => { target.fill(0); cursor.fill(movement.offscreen); pointerAt = lastX = lastY = -Infinity; clock.schedule(); }); scope.on( window, 'scroll', () => { bounds = element.getBoundingClientRect(); if (motionPaused()) return; scrollDrift = (movement.scroll * scrollY) / Math.max(1, document.documentElement.scrollHeight - innerHeight); surface.dirty = true; clock.schedule(); }, { passive: true, capture: true }, ); scope.on(document, 'motion:change', () => { pointerAt = -Infinity; chromaUntil = 0; target.fill(0); parallax.fill(0); scrollDrift = 0; }); scope.on(canvas, 'webglcontextlost', (event) => { event.preventDefault(); surface.ready = false; revealed = false; element.classList.remove('ready'); }); return surface; }