Skip to content

Instantly share code, notes, and snippets.

@greggman
Last active September 27, 2021 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggman/dd9bea6a850447dde59dc50eeb402c1c to your computer and use it in GitHub Desktop.
Save greggman/dd9bea6a850447dde59dc50eeb402c1c to your computer and use it in GitHub Desktop.
gl.POINTS
html, body { margin: 0; height: 100%; }
canvas { width: 100%; height: 100%; display: block; }
#info {
position: absolute;
left: 0;
top: 0;
background: rgba(0,0,0,0.8);
color: white;
padding: 0.5em;
font-family: monospace;
}
#info a {
color: orange;
}
<canvas></canvas>
<div id="info">See <a target="_blank" href="https://jsgist.org/?src=535da7687726e14dc26884e085de7629">here</a> for <i>better</i> emulated POINTS</div>
import * as twgl from 'https://twgljs.org/dist/4.x/twgl-full.module.js';
const gl = document.querySelector('canvas').getContext('webgl');
const pointsVS = `
attribute vec4 position;
void main() {
gl_PointSize = 64.0;
gl_Position = position;
}
`;
const pointsFS = `
precision mediump float;
void main() {
gl_FragColor = vec4(gl_PointCoord, 0, 1);
}
`;
const prg = twgl.createProgram(gl, [pointsVS, pointsFS]);
gl.useProgram(prg);
const posLoc = gl.getAttribLocation(prg, "position");
const rand = (min, max) => Math.random() * (max - min) + min;
const numPoints = 100;
const pointPositions = new Float32Array(numPoints * 2);
const pointVelocities = new Float32Array(numPoints * 2);
for (let i = 0; i < numPoints; ++i) {
const offset = i * 2;
pointPositions[offset ] = rand(-2, 2);
pointPositions[offset + 1] = rand(-2, 2);
pointVelocities[offset ] = rand(-1, 1);
pointVelocities[offset + 1] = rand(-1, 1);
}
const pointsBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, pointsBuffer);
gl.bufferData(gl.ARRAY_BUFFER, pointPositions.byteLength, gl.DYNAMIC_DRAW);
let then = 0;
function render(now) {
now *= 0.001; // convert to seconds
const elapsedTime = Math.min(now - then, 0.5);
then = now;
twgl.resizeCanvasToDisplaySize(gl.canvas);
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
// I'd update this positions on the GPU if I can but
// just for the sake of an example we're doing it on the CPU
for (let i = 0; i < numPoints * 2; ++i) {
pointPositions[i] = (pointPositions[i] + pointVelocities[i] * elapsedTime + 6) % 4 - 2;
}
gl.bindBuffer(gl.ARRAY_BUFFER, pointsBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, pointPositions);
gl.enableVertexAttribArray(posLoc);
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.POINTS, 0, numPoints);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
{"name":"gl.POINTS","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment