Framebuffers
Draw into a texture instead of the canvas, for post-processing, blurs and effects that build up over time.
A framebuffer is somewhere to draw other than the canvas. createFrameBuffer makes one with a texture to draw into, so the next pass can read what this one drew. Bind it, draw, and pass its target to the next renderer as a texture.
import { createContext, createFrameBuffer, createRenderer } from 'wtc-simplegl'
// Draws a spinning shape into a small framebuffer, then draws that
// framebuffer onto the canvas with NEAREST filtering, so it's pixelated.
const vert = /* glsl */ `#version 300 es
in vec2 a_position;
out vec2 v_uv;
void main() {
v_uv = a_position * 0.5 + 0.5;
gl_Position = vec4(a_position, 0.0, 1.0);
}`
const shape = /* glsl */ `#version 300 es
precision highp float;
uniform float u_time;
uniform float u_aspect;
in vec2 v_uv;
out vec4 colour;
void main() {
vec2 p = (v_uv - 0.5) * vec2(u_aspect, 1.0) * 2.0;
float a = u_time * 0.6;
p = mat2(cos(a), sin(a), -sin(a), cos(a)) * p;
// A rounded square outline
float d = length(max(abs(p) - 0.45, 0.0)) - 0.1;
float alpha = smoothstep(0.05, 0.0, abs(d) - 0.06);
vec3 rgb = mix(vec3(0.29, 0.62, 1.0), vec3(1.0, 0.45, 0.7), v_uv.x);
colour = vec4(rgb * alpha, alpha);
}`
const show = /* glsl */ `#version 300 es
precision highp float;
uniform sampler2D u_image;
in vec2 v_uv;
out vec4 colour;
void main() {
colour = texture(u_image, v_uv);
}`
const SCALE = 1 / 8
export default function (container) {
const ac = new AbortController()
const canvas = document.createElement('canvas')
container.appendChild(canvas)
const gl = createContext({
canvas,
signal: ac.signal,
attributes: { alpha: true, premultipliedAlpha: true }
})
const attributes = {
a_position: { data: new Float32Array([-1, -1, 3, -1, -1, 3]), size: 2 }
}
const draw = createRenderer(gl, { vert, frag: shape, attributes, count: 3 })
const present = createRenderer(gl, { vert, frag: show, attributes, count: 3 })
// One target, kept at an eighth of the canvas's size
const target = createFrameBuffer(gl, {
width: 1,
height: 1,
singular: true,
minFilter: gl.NEAREST
})
const fit = () => {
const width = Math.max(1, Math.round(gl.canvas.width * SCALE))
const height = Math.max(1, Math.round(gl.canvas.height * SCALE))
if (width !== target.width || height !== target.height) target.resize(width, height)
}
return {
frame(time) {
fit()
// Into the framebuffer, at its own size
gl.bindFramebuffer(gl.FRAMEBUFFER, target.read.fb)
gl.clearColor(0, 0, 0, 0)
gl.clear(gl.COLOR_BUFFER_BIT)
draw.bindVAOs()
draw.setUniforms({ u_time: time, u_aspect: target.width / target.height })
draw.render({ width: target.width, height: target.height })
// Then onto the canvas
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
present.bindVAOs()
present.setUniforms({ u_image: target.read })
present.render()
},
dispose() {
ac.abort()
draw.delete()
present.delete()
target.delete()
gl.getExtension('WEBGL_lose_context')?.loseContext()
canvas.remove()
}
}
}Drawing into one
import { createFrameBuffer } from 'wtc-simplegl'
const target = createFrameBuffer(gl, { width: 256, height: 256, singular: true })
// Into the target, at its size
gl.bindFramebuffer(gl.FRAMEBUFFER, target.read.fb)
scene.bindVAOs()
scene.render({ width: target.width, height: target.height })
// Back to the canvas, reading the target
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
show.bindVAOs()
show.setUniforms({ u_image: target.read })
show.render()Each target is a RenderTarget: fb, the framebuffer to bind, and targetTexture, the texture it draws into. Pass the whole target to setUniforms and its texture is used.
Pass the target's size to render(): it sets the viewport, which otherwise covers the canvas.
Ping-pong
A shader can't read a texture while drawing into it. For an effect that reads its own last frame, such as a trail or a simulation, you need two: read from one, draw into the other, then swap. Leave out singular and you get both, as read and write:
const feedback = createFrameBuffer(gl, { width, height, type: gl.HALF_FLOAT })
// Each frame
gl.bindFramebuffer(gl.FRAMEBUFFER, feedback.write.fb)
step.bindVAOs()
step.setUniforms({ u_previous: feedback.read })
step.render({ width: feedback.width, height: feedback.height })
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
feedback.swap()
// feedback.read now holds the frame just drawnSet the texture uniforms every frame: read and write trade places with each swap. Feedback with ping-pong buffers builds a whole effect this way.
Options
| Option | Default | |
|---|---|---|
width, height | Size in pixels. | |
type | gl.UNSIGNED_BYTE | gl.HALF_FLOAT or gl.FLOAT for float targets. |
format | gl.RGBA | gl.RG or gl.RED for fewer channels with float types. |
singular | false | Make read only. |
depth | false | A depth buffer, for depth testing while drawing into the target. |
minFilter, magFilter | gl.LINEAR | gl.NEAREST for exact texels or pixelated scaling. |
tiling | gl.CLAMP_TO_EDGE | The wrap mode when the texture is read. |
data | null | Initial contents. |
Float targets
8-bit targets store 256 levels from 0 to 1. Effects that accumulate, fade slowly, or store positions and velocities need more: type: gl.HALF_FLOAT stores 16-bit floats, and gl.FLOAT 32-bit. The internal format and the extension needed to draw into them (EXT_color_buffer_float) are handled; if the device can't, createFrameBuffer throws.
gl.HALF_FLOAT is filterable everywhere and half the memory, so prefer it unless you need the precision. gl.FLOAT targets default to gl.NEAREST where they can't be filtered linearly.
Resizing
resize(width, height) replaces the targets with new, empty ones. Call it from createContext's onResize, or check the size before drawing:
if (target.width !== gl.canvas.width / 2) target.resize(gl.canvas.width / 2, gl.canvas.height / 2)The textures are new objects afterwards, which is another reason to pass target.read to setUniforms every frame rather than keeping its texture.
Errors
If the combination of format, internalFormat and type can't be drawn into, createFrameBuffer throws, naming the reason, such as FRAMEBUFFER_INCOMPLETE_ATTACHMENT. Without the check, drawing into it would silently do nothing.
Freeing them
delete() frees the framebuffers, their textures and depth buffers.