-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
396 lines (329 loc) · 11.9 KB
/
index.html
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
396
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Visualizer</title>
<style>
body,
html {
margin: 0;
overflow: hidden;
background-color: black;
width: 100%;
height: 100%;
}
#glcanvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
}
</style>
</head>
<body>
<canvas id="glcanvas"></canvas>
<script>
;(function () {
// Get the canvas element and set up WebGL2 context
const canvas = document.getElementById("glcanvas")
const gl = canvas.getContext("webgl2")
// If WebGL2 is not supported, alert the user
if (!gl) {
alert("WebGL 2 is not supported by your browser.")
return
}
let buffers = [] // To hold the framebuffers used for rendering effects
let bufferIndex = 0 // Track which framebuffer is currently being rendered
// Function to create a framebuffer with attached texture
function createFramebuffer() {
const framebuffer = gl.createFramebuffer()
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer)
const texture = gl.createTexture()
gl.bindTexture(gl.TEXTURE_2D, texture)
// Allocate space for texture
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA8,
canvas.width,
canvas.height,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
null
)
// Set texture parameters
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
// Attach the texture to the framebuffer
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
texture,
0
)
return { framebuffer, texture }
}
// Create two framebuffers used for ping-pong rendering
function createFramebuffers() {
if (buffers.length > 0) {
// Delete existing buffers to avoid memory leaks
buffers.forEach((buf) => {
gl.deleteFramebuffer(buf.framebuffer)
gl.deleteTexture(buf.texture)
})
}
buffers = [createFramebuffer(), createFramebuffer()]
bufferIndex = 0
}
// Resize canvas and update WebGL viewport
function resizeCanvas() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
gl.viewport(0, 0, canvas.width, canvas.height)
createFramebuffers() // Recreate framebuffers to match new size
}
window.addEventListener("resize", resizeCanvas)
resizeCanvas() // Initial canvas setup
// Vertex shader program: Defines position of vertices and calculates texture coordinates
const vertexShaderSource = `#version 300 es
in vec4 a_position;
out vec2 v_texCoord;
uniform float iAudioLevel;
uniform float iTime;
void main() {
gl_Position = a_position;
// Calculate the dynamic values based on audio level
float minVal = 0.5;
float maxVal = 0.5;
// Threshold volume above which the values start changing
if (iAudioLevel > 0.1) {
float volumeFactor = smoothstep(0.001, 0.01, iAudioLevel);
float cycleOffset = sin(iTime * 1.0 * 3.14159 / (60.0 / 128.0 / 2.0)); // Cycle every 8th beat at 128 BPM
minVal = 0.49 - 0.000001 * volumeFactor * cycleOffset;
maxVal = 0.501 - 0.001 * volumeFactor * cycleOffset;
}
v_texCoord = a_position.xy * minVal + maxVal;
}`
// Fragment shader program: Defines color for each fragment based on noise and audio level
const fragmentShaderSource = `#version 300 es
uniform highp float seed;
precision highp float;
uniform vec2 iResolution;
uniform float iTime;
uniform float iAudioLevel;
uniform sampler2D iChannel0;
out vec4 fragColor;
in vec2 v_texCoord;
float noise3( vec3 x ) {
vec3 p = floor(x), f = fract(x);
f = f*f*(3.0-2.0*f);
#define hash3(p) fract(sin(1e3*dot(p,vec3(1,57,-13.7)) + seed) * 4375.5453)
return mix( mix(mix( hash3(p+vec3(0,0,0)), hash3(p+vec3(1,0,0)), f.x),
mix( hash3(p+vec3(0,1,0)), hash3(p+vec3(1,1,0)), f.x), f.y),
mix(mix( hash3(p+vec3(0,0,1)), hash3(p+vec3(1,0,1)), f.x),
mix( hash3(p+vec3(0,1,1)), hash3(p+vec3(1,1,1)), f.x), f.y), f.z);
}
#define noise(x) (noise3(x) + noise3(x + 11.5)) / 2.0
void main() {
vec2 U = gl_FragCoord.xy;
vec2 R = iResolution.xy;
float t = iTime * (1.0 + iAudioLevel * 0.8 * (1.0 - smoothstep(0.5, 1.0, iAudioLevel)));
// Enhance the effect of the audio level on the noise
float n = noise(vec3(U * 3.0 / R.y, 0.1 * t + iAudioLevel * 2.0));
float v = sin(6.28 * 8.0 * n * (1.0 + iAudioLevel * 0.5));
v = smoothstep(1.0, 0.0, 0.5 * abs(v) / fwidth(v));
vec4 prevColor = texture(iChannel0, v_texCoord);
vec4 baseColor = vec4(0.5 - 0.5 * sin(10.0 * n + vec4(35.0 * iAudioLevel + sin(iTime * 0.05), 45.0 * iAudioLevel + cos(iTime * 0.05), 50.0 * iAudioLevel + sin(iTime * 0.05), 0))); // Removed time-based color influence
vec4 color = mix(vec4(1.0, 1.0, 1.0, 1.0), baseColor, smoothstep(0.01, 0.1, iAudioLevel * 2.0));
float decayFactor = 0.8 - iAudioLevel * 0.3; // Increase glow intensity with audio level
fragColor = mix(prevColor * decayFactor, color, v);
}`
// Helper function to compile shader source code
function compileShader(gl, source, type) {
const shader = gl.createShader(type)
gl.shaderSource(shader, source)
gl.compileShader(shader)
const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
if (!success) {
console.error(
"Shader compilation failed:",
gl.getShaderInfoLog(shader)
)
gl.deleteShader(shader)
return null
}
return shader
}
// Compile vertex and fragment shaders
const vertexShader = compileShader(
gl,
vertexShaderSource,
gl.VERTEX_SHADER
)
const fragmentShader = compileShader(
gl,
fragmentShaderSource,
gl.FRAGMENT_SHADER
)
// Create and link shader program
const program = gl.createProgram()
gl.attachShader(program, vertexShader)
gl.attachShader(program, fragmentShader)
gl.linkProgram(program)
// Check if program linked successfully
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.error(
"Program failed to link:",
gl.getProgramInfoLog(program)
)
return
}
gl.useProgram(program)
// Set up position attribute for drawing a rectangle (fullscreen)
const positionAttributeLocation = gl.getAttribLocation(
program,
"a_position"
)
const positionBuffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
// Fullscreen rectangle vertices
const positions = new Float32Array([
-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1,
])
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW)
gl.enableVertexAttribArray(positionAttributeLocation)
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)
gl.vertexAttribPointer(
positionAttributeLocation,
2,
gl.FLOAT,
false,
0,
0
)
// Uniform locations for resolution, time, and audio level
const iResolutionLocation = gl.getUniformLocation(
program,
"iResolution"
)
const iTimeLocation = gl.getUniformLocation(program, "iTime")
const iAudioLevelLocation = gl.getUniformLocation(
program,
"iAudioLevel"
)
const iChannel0Location = gl.getUniformLocation(program, "iChannel0")
function setResolution() {
// Set the resolution uniform
gl.uniform2f(iResolutionLocation, canvas.width, canvas.height)
}
setResolution()
let audioDataArray // Array to store frequency data from audio
let analyserNode // Web Audio API analyser node
let audioLevel = 0.0 // Current audio level
let smoothedAudioLevel = 0.0 // Smoothed version of audio level
// Function to set up microphone input for audio analysis
async function setupAudio() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
audio: true,
})
const audioContext = new (window.AudioContext ||
window.webkitAudioContext)()
const source = audioContext.createMediaStreamSource(stream)
analyserNode = audioContext.createAnalyser()
analyserNode.fftSize = 1024
const bufferLength = analyserNode.frequencyBinCount
audioDataArray = new Uint8Array(bufferLength)
source.connect(analyserNode)
} catch (err) {
console.error("Error accessing microphone:", err)
}
}
setupAudio()
// Update the current audio level from the analyser node
function updateAudioLevel() {
if (analyserNode && audioDataArray) {
analyserNode.getByteFrequencyData(audioDataArray)
// Compute average volume
let sum = 0
for (let i = 0; i < audioDataArray.length; i++) {
// Weighted average for different frequency bands
let frequencyWeight =
i < audioDataArray.length * 0.2
? 1.0
: i < audioDataArray.length * 0.8
? 0.5
: 0.1
sum += audioDataArray[i] * frequencyWeight
}
audioLevel = sum / audioDataArray.length / 255.0 // Normalize between 0 and 1
// Apply smoothing to avoid sudden changes in audio level
const smoothingFactor = 0.1
smoothedAudioLevel =
smoothedAudioLevel * smoothingFactor +
audioLevel * (1 - smoothingFactor)
}
}
let startTime = null
let currentSeed = Math.random() * 1000 // Random initial seed for noise
let seed = currentSeed
let seedTransitionFactor = 0.0
let bpm = 128 // Beats per minute
let interval = (60 / bpm) * 1000 * 8 // Change seed every eight beats
setInterval(() => {
if (smoothedAudioLevel > 0.1) {
// Change shape dynamics only if volume is above a threshold
currentSeed += (Math.random() - 0.5) * 100 // Gradual adjustment to the current seed for smooth transition
seedTransitionFactor = 0.0
}
}, interval)
// Render function for drawing the visuals on each animation frame
function render(time) {
// Smoothly interpolate the seed value
seedTransitionFactor = Math.min(
seedTransitionFactor + 0.02 * smoothedAudioLevel,
1.0
)
seed = currentSeed
// Set shader uniform values for seed, time, and audio level
gl.uniform1f(gl.getUniformLocation(program, "seed"), seed)
if (!startTime) startTime = time
const deltaTime = (time - startTime) / 1000.0
updateAudioLevel()
gl.uniform1f(iTimeLocation, deltaTime)
gl.uniform1f(iAudioLevelLocation, smoothedAudioLevel)
setResolution()
// Use framebuffers for ping-pong rendering
const currentBuffer = buffers[bufferIndex]
const prevBuffer = buffers[1 - bufferIndex]
gl.bindFramebuffer(gl.FRAMEBUFFER, currentBuffer.framebuffer)
gl.viewport(0, 0, canvas.width, canvas.height)
gl.activeTexture(gl.TEXTURE0)
gl.bindTexture(gl.TEXTURE_2D, prevBuffer.texture)
gl.uniform1i(iChannel0Location, 0)
gl.clear(gl.COLOR_BUFFER_BIT)
// Draw to the current framebuffer
gl.drawArrays(gl.TRIANGLES, 0, 6)
// Draw to the main canvas
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
gl.viewport(0, 0, canvas.width, canvas.height)
gl.bindTexture(gl.TEXTURE_2D, currentBuffer.texture)
gl.drawArrays(gl.TRIANGLES, 0, 6)
// Swap the buffers for the next frame
bufferIndex = 1 - bufferIndex
requestAnimationFrame(render)
}
requestAnimationFrame(render) // Start the rendering loop
window.addEventListener("resize", () => {
resizeCanvas()
})
})()
</script>
</body>
</html>