Skip to content

Instantly share code, notes, and snippets.

@littleark
Created October 1, 2019 08:13
Show Gist options
  • Save littleark/1a3d599c0c5cb2dec4995bddb6f95fc6 to your computer and use it in GitHub Desktop.
Save littleark/1a3d599c0c5cb2dec4995bddb6f95fc6 to your computer and use it in GitHub Desktop.
Experiments with regl 0.0.2
const regl = require('regl')();
const d3Random = require('d3-random');
const d3Array = require('d3-array');
const rng = d3Random.randomNormal(0, 0.1);
const { range } = d3Array;
const numPoints = 100000;
// the size of the points we draw on screen
const pointWidth = 2;
// dimensions of the viewport we are drawing in
const width = window.innerWidth;
const height = window.innerHeight;
// generaate some random points
const points = range(numPoints).map(i => ({
x1: (rng() * width) + (width / 2),
y1: (rng() * height) + (height / 2),
x: rng(),
y: rng(),
size: Math.random() * 5 + pointWidth,
color: [0, Math.random(), 0],
delta: [rng(), rng()],
}));
// draw points
const drawStuff = regl({
frag: `
precision mediump float;
varying vec3 fragColor;
void main() {
float r = 0.0;
float delta = 0.0;
float alpha = 1.0;
vec2 cxy = 2.0 * gl_PointCoord - 1.0;
r = dot(cxy, cxy);
if (r > 1.0) {
discard;
}
gl_FragColor = vec4(fragColor, 0.5) * alpha;
}
`,
vert: `
precision mediump float;
attribute vec2 position;
attribute vec2 delta;
attribute vec3 color;
attribute float size;
varying vec3 fragColor;
uniform float pointWidth;
uniform float stageWidth;
uniform float stageHeight;
uniform float time;
void main() {
gl_PointSize = size;
fragColor = color;
gl_Position = vec4(position.x + sin(time * delta.x), position.y + cos(time * delta.y), 0.0, 1.0);
}
`,
attributes: {
position: points.map(d => [d.x, d.y]),
delta: points.map(d => d.delta),
color: points.map(d => [1.0,1.0,0.0]),
size: points.map(d => d.size),
},
uniforms: {
pointWidth: regl.prop('pointWidth'),
stageWidth: regl.prop('width'),
stageHeight: regl.prop('height'),
time: regl.context('time'),
},
blend: {
enable: true,
func: {
srcRGB: 'src alpha',
srcAlpha: 'src alpha',
dstRGB: 'one minus src alpha',
dstAlpha: 'one minus src alpha',
},
},
depth: { enable: false },
count: points.length,
primitive: 'points',
})
// loop
regl.frame(({time}) => {
regl.clear({
color: [0,0,0,1],
depth: 1,
});
drawStuff({
pointWidth: pointWidth,
width,
height,
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment