Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
395 lines (328 loc) · 11.3 KB
/
Copy pathindex.js
File metadata and controls
395 lines (328 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// -----------------------------------------------------------------------------
const createCanvas = target => {
if (target.tagName === 'CANVAS') return target
for (const canvas of document.querySelectorAll('#gradient-gl')) canvas.remove()
return target.appendChild(
Object.assign(document.createElement('canvas'), {
id: 'gradient-gl',
style: 'position:fixed;inset:0;width:100vw;height:100vh;z-index:-1;pointer-events:none;'.replace(/:([^;]+);/g, ':$1!important;'),
}),
)
}
// -----------------------------------------------------------------------------
// Pure utility functions
const normalize = v => {
const value = Number.parseInt(v, 16)
return Math.round(value * (255 / 15)) // Map 0-15 to 0-255
}
const nonLinearMap = (val, minOut, maxOut, power = 2) => {
const v = Math.max(0, Math.min(val, 15))
return v === 0 ? minOut : minOut + ((v - 1) / 14) ** power * (maxOut - minOut)
}
const parseSeed = s => [
s.split('.').shift(),
new Uint8Array(s.split('.').pop().split('').map(normalize)),
]
// -----------------------------------------------------------------------------
const vertex = /* glsl */ `#version 300 es
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}`
class GradientGL {
#gl
#canvas
#ownsCanvas
#program
#uniforms
#timeScale
#isActive
#externalUniforms
#currentSeed
#currentUniformValues
#fragment
#vertex
#lastTime
#elapsedTime
// Time interpolation constants
static #MAX_DELTA = 50 // Maximum frame delta in ms (~20fps minimum)
constructor(canvas, fragment, seed, ownsCanvas) {
this.#canvas = canvas
this.#ownsCanvas = ownsCanvas
this.#fragment = fragment
this.#vertex = vertex
this.#timeScale = 0.4
this.#isActive = false
this.#currentSeed = seed
this.#externalUniforms = seed[1]
this.#currentUniformValues = { speed: 0, hueShift: 0, saturation: 0, lightness: 0 }
this.#lastTime = null
this.#elapsedTime = 0
this.#setupEventHandlers()
}
#setupEventHandlers() {
this.#canvas.addEventListener('webglcontextlost', e => {
if (!this.#isActive) return
e.preventDefault()
this.#isActive = false
this.#gl = null
this.#program = null
this.#uniforms = null
if (this.#canvas) this.#canvas.width = 0
})
this.#canvas.addEventListener('webglcontextrestored', () => {
if (this.#canvas) this.init()
})
// INFO: to consider
// document.addEventListener('visibilitychange', () => {
// if (!document.hidden && !this.#isActive) this.init()
// })
}
init() {
if (!this.#canvas) return
this.#gl = this.#createGLContext(this.#canvas)
this.#program = this.#createProgram(this.#vertex, this.#fragment)
this.#uniforms = this.#getUniformLocations()
this.#isActive = true
this.#setupBuffers()
this.#setupAttributes()
this.#updateExternalUniforms(true)
this.#render()
}
#createGLContext(canvas) {
const gl = canvas.getContext('webgl2', {
antialias: true,
})
if (!gl) throw new Error('WebGL2 not supported')
return gl
}
#createShader(type, source) {
const shader = this.#gl.createShader(type)
this.#gl.shaderSource(shader, source)
this.#gl.compileShader(shader)
const log = this.#gl.getShaderInfoLog(shader)
if (log)
throw new Error(
`${type === this.#gl.VERTEX_SHADER ? 'Vertex' : 'Fragment'} shader compilation error: ${log}`,
)
return shader
}
#createProgram(vertexSource, fragmentSource) {
const program = this.#gl.createProgram()
const vertexShader = this.#createShader(this.#gl.VERTEX_SHADER, vertexSource)
const fragmentShader = this.#createShader(this.#gl.FRAGMENT_SHADER, fragmentSource)
this.#gl.attachShader(program, vertexShader)
this.#gl.attachShader(program, fragmentShader)
this.#gl.linkProgram(program)
const log = this.#gl.getProgramInfoLog(program)
if (log) console.error('Program linking error:', log)
this.#gl.detachShader(program, vertexShader)
this.#gl.detachShader(program, fragmentShader)
this.#gl.deleteShader(vertexShader)
this.#gl.deleteShader(fragmentShader)
this.#gl.useProgram(program)
return program
}
#setupBuffers() {
const positionBuffer = this.#gl.createBuffer()
this.#gl.bindBuffer(this.#gl.ARRAY_BUFFER, positionBuffer)
this.#gl.bufferData(
this.#gl.ARRAY_BUFFER,
new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]),
this.#gl.STATIC_DRAW,
)
}
#setupAttributes() {
const positionLocation = this.#gl.getAttribLocation(this.#program, 'position')
this.#gl.enableVertexAttribArray(positionLocation)
this.#gl.vertexAttribPointer(positionLocation, 2, this.#gl.FLOAT, false, 0, 0)
}
#getUniformLocations() {
return [
'iResolution',
'iTime',
'iFrame',
'options',
'timeScale',
'hueShift',
'saturation',
'lightness',
].reduce(
(acc, cur) => ({
...acc,
[cur]: this.#gl.getUniformLocation(this.#program, cur),
}),
{},
)
}
#updateExternalUniforms(forceUpdate = false) {
if (!this.#externalUniforms) return
this.#gl.useProgram(this.#program)
this.#gl.uniform1iv(this.#uniforms.options, this.#externalUniforms)
const [speedVal, hueVal, satVal, lightVal] = this.#externalUniforms.map(v =>
Math.round((v * 15) / 255),
)
const [speed, hueShift, satFactor, lightFactor] = [
nonLinearMap(speedVal, 0.1, 3.0, 1.5),
hueVal / 15,
nonLinearMap(satVal, 0.3, 3.0, 1.5),
lightVal / 15, // Simple linear mapping from 0 to 1
]
const valuesChanged =
forceUpdate ||
speed !== this.#currentUniformValues.speed ||
hueShift !== this.#currentUniformValues.hueShift ||
satFactor !== this.#currentUniformValues.saturation ||
lightFactor !== this.#currentUniformValues.lightness
if (valuesChanged) {
this.#gl.uniform1f(this.#uniforms.timeScale, speed)
this.#gl.uniform1f(this.#uniforms.hueShift, hueShift)
this.#gl.uniform1f(this.#uniforms.saturation, satFactor)
this.#gl.uniform1f(this.#uniforms.lightness, lightFactor)
this.#currentUniformValues = {
speed,
hueShift,
saturation: satFactor,
lightness: lightFactor,
}
}
}
isMounted(target) {
if (!this.#isActive || !this.#gl || !this.#program) return false
if (!this.#canvas?.isConnected) return false
return target.tagName === 'CANVAS'
? this.#canvas === target
: this.#canvas.parentElement === target
}
updateSeed(seed) {
if (seed[0] === this.#currentSeed[0] && seed[1].every((v, i) => v === this.#currentSeed[1][i]))
return false
this.#currentSeed = seed
this.#externalUniforms = seed[1]
this.#updateExternalUniforms(true)
return true
}
#updateInternalUniforms(time) {
if (!this.#isActive || !this.#canvas || !this.#gl) return
const { iResolution, iTime, iFrame } = this.#uniforms
this.#gl.useProgram(this.#program)
const displayWidth = this.#canvas.clientWidth
const displayHeight = this.#canvas.clientHeight
if (this.#canvas.width !== displayWidth || this.#canvas.height !== displayHeight) {
this.#canvas.width = displayWidth
this.#canvas.height = displayHeight
this.#gl.uniform3f(iResolution, this.#canvas.width, this.#canvas.height, 1.0)
this.#gl.viewport(0, 0, this.#canvas.width, this.#canvas.height)
}
// Use elapsed time for smooth animation
const continuousTime = time / 1000
this.#gl.uniform1f(iTime, continuousTime)
this.#gl.uniform1f(iFrame, Math.floor(continuousTime * 60))
}
#updateTime(currentTime) {
if (this.#lastTime !== null) {
const delta = Math.min(currentTime - this.#lastTime, GradientGL.#MAX_DELTA)
this.#elapsedTime += delta
}
this.#lastTime = currentTime
}
#render() {
const frame = () => {
if (!this.#isActive || !this.#canvas || !this.#gl) {
return
}
if (!this.#canvas.isConnected) {
this.destroy()
return
}
const currentTime = performance.now()
this.#updateTime(currentTime)
this.#updateInternalUniforms(this.#elapsedTime)
this.#gl.drawArrays(this.#gl.TRIANGLE_STRIP, 0, 4)
requestAnimationFrame(frame)
}
requestAnimationFrame(frame)
}
destroy(preserveCanvas) {
this.#isActive = false
if (this.#program && this.#gl) this.#gl.deleteProgram(this.#program)
const reuse = this.#canvas === preserveCanvas
if (this.#ownsCanvas && !reuse) {
this.#gl?.getExtension('WEBGL_lose_context')?.loseContext()
this.#canvas?.remove()
}
this.#program = null
this.#canvas = null
this.#gl = null
if (activeProgram === this) activeProgram = null
}
}
// -----------------------------------------------------------------------------
import common from './shaders/common.glsl.js'
const fetchCommon = () => Promise.resolve(common)
// Static-analyser friendly map; no dynamic import paths; tree-shake + per-shader split
const shaderLoaders = {
b1: () => import('./shaders/b1.glsl.js'),
b2: () => import('./shaders/b2.glsl.js'),
b3: () => import('./shaders/b3.glsl.js'),
b4: () => import('./shaders/b4.glsl.js'),
c1: () => import('./shaders/c1.glsl.js'),
c4: () => import('./shaders/c4.glsl.js'),
f1: () => import('./shaders/f1.glsl.js'),
f3: () => import('./shaders/f3.glsl.js'),
l1: () => import('./shaders/l1.glsl.js'),
l3: () => import('./shaders/l3.glsl.js'),
l5: () => import('./shaders/l5.glsl.js'),
n1: () => import('./shaders/n1.glsl.js'),
n2: () => import('./shaders/n2.glsl.js'),
n3: () => import('./shaders/n3.glsl.js'),
n4: () => import('./shaders/n4.glsl.js'),
s1: () => import('./shaders/s1.glsl.js'),
s3: () => import('./shaders/s3.glsl.js'),
}
export const shaderIds = Object.keys(shaderLoaders).sort()
const fetchShader = async id => {
const loader = shaderLoaders[id]
if (!loader) throw new Error('Unknown shader')
const mod = await loader()
return mod.default
}
const main = /* glsl */ `
void main() {
fragColor = shader(gl_FragCoord.xy);
}
`
let activeProgram = null
let bootLock = Promise.resolve()
export default function boot(seed, selector = 'body') {
const task = bootLock.then(async () => {
if (!seed) throw new Error('Seed is required')
const parsedSeed = parseSeed(seed)
const [shaderId] = parsedSeed
const target = document.querySelector(selector) ?? document.body
if (activeProgram?.shaderId === shaderId && activeProgram.isMounted(target)) {
activeProgram.updateSeed(parsedSeed)
return activeProgram
}
if (activeProgram) {
activeProgram.destroy(target)
activeProgram = null
}
const [common, shader] = await Promise.all([fetchCommon(), fetchShader(shaderId)])
const fragment = common + shader + main
const canvas = createCanvas(target)
const program = new GradientGL(canvas, fragment, parsedSeed, canvas !== target)
program.shaderId = shaderId
program.init()
activeProgram = program
return program
})
bootLock = task.catch(() => {})
return task
}
// -----------------------------------------------------------------------------
const url = new URL(import.meta.url)
const seed = url.searchParams.get('seed')
const selector = url.searchParams.get('selector') || 'body'
if (seed) boot(seed, selector)
window.gradient = boot;