Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const regl = require('regl')({
extensions: 'OES_texture_float'
})
const fillScreen = require('./fill-screen')(regl)
const RESOLUTION = 256
const initialData = new Float32Array(RESOLUTION * RESOLUTION * 4)
for (var i = 0; i < initialData.length; ++i) {
initialData[i] = Math.random()
}
const stateBuffers = (new Array(2)).fill().map(() =>
regl.framebuffer({
depthStencil: false,
color: regl.texture({
shape: [RESOLUTION, RESOLUTION, 4],
type: 'float',
data: initialData
})
}))
const update = regl({
framebuffer: ({tick}) =>
stateBuffers[tick % stateBuffers.length],
uniforms: {
state: ({tick}) =>
stateBuffers[
(tick + stateBuffers.length - 1) % stateBuffers.length ],
resolution: ({viewportWidth, viewportHeight}) =>
[viewportWidth, viewportHeight],
mouse: regl.prop('mouse')
},
frag: `
precision highp float;
varying vec2 uv;
uniform sampler2D state;
uniform vec2 resolution, mouse;
vec4 fetch (vec2 offset) {
return texture2D(state, uv + offset / resolution);
}
vec4 laplacian () {
return fetch(vec2(0, 0)) -
0.25 * (
fetch(vec2(1, 0)) +
fetch(vec2(-1, 0)) +
fetch(vec2(0, 1)) +
fetch(vec2(0, -1)));
}
void main () {
float d = length(uv - mouse);
gl_FragColor =
0.95 * fetch(vec2(0)) - 0.015 * laplacian() +
0.05 * fetch(vec2(0, 2)) +
step(d, 0.01);
}
`
})
const drawTexture = regl({
frag: `
precision highp float;
varying vec2 uv;
uniform sampler2D tex;
void main () {
gl_FragColor = vec4(texture2D(tex, uv).rgb, 1.);
}
`,
uniforms: {
tex: regl.prop('texture')
}
})
var mouse = [0, 0]
window.addEventListener('mousemove', ({clientX, clientY}) => {
mouse[0] = clientX / window.innerWidth
mouse[1] = 1 - clientY / window.innerHeight
})
regl.frame(() => {
regl.clear({
color: [0, 0, 0, 1],
depth: 1
})
fillScreen(({tick}) => {
update({ mouse })
drawTexture({
texture: stateBuffers[tick % stateBuffers.length]
})
})
})
module.exports = function (regl) {
return regl({
vert: `
precision highp float;
attribute vec2 position;
varying vec2 uv;
void main () {
uv = 0.5 * (position + 1.0);
gl_Position = vec4(position, 0, 1);
}
`,
frag: `
precision highp float;
varying vec2 uv;
void main () {
gl_FragColor = vec4(uv, 0, 1);
}
`,
attributes: {
position: [
-4, 0,
4, 4,
4, -4
]
},
count: 3
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment