Public
Edited
Apr 6, 2024
Insert cell
Insert cell
{
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const context = util.ctx(512, 512);
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format });
//

const module = device.createShaderModule({
code: `
struct Vertex {
@location(0) position: vec2f,
@location(1) color: vec4f,
@location(2) offset: vec2f,
@location(3) scale: vec2f,
};

struct VertexOut {
@builtin(position) position: vec4f,
@location(0) color: vec4f,
};

@vertex
fn vs(vertex: Vertex) -> VertexOut {
var vsOut: VertexOut;
vsOut.position = vec4f(vertex.position * vertex.scale + vertex.offset, 0.0, 1.0);
vsOut.color = vertex.color;
return vsOut;
}

@fragment
fn fs(vsOut: VertexOut) -> @location(0) vec4f {
return vsOut.color;
}
`
})
//

const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module,
entryPoint: 'vs',
buffers: [
{
arrayStride: 2 * 4, // 2 floats * 4 bytes each
attributes: [
{ shaderLocation: 0, offset: 0, format: 'float32x2' }, // position
],
},
// static
{
arrayStride: 6 * 4, // 6 floats * 4 bytes each
// attr advances one per instance (vs one per vert, starting over at instance)
stepMode: 'instance',
attributes: [
{ shaderLocation: 1, offset: 0, format: 'float32x4' }, // color (rgba -> 4x4)
{ shaderLocation: 2, offset: 0 + 4 * 4, format: 'float32x2' }, // offset (xy -> 2x4)
],
},
// dynamic
{
arrayStride: 2 * 4, // 2 floats * 4 bytes each
stepMode: 'instance',
attributes: [
{ shaderLocation: 3, offset: 0, format: 'float32x2' }, // scale (xy)
]
}
]
},
fragment: {
module,
entryPoint: 'fs',
targets: [{ format }]
}
})

// janky but we're not focused on perf rn...
const xExtent = [Math.min(...data.map(d => d.len)), Math.max(...data.map(d => d.len))];
const yExtent = [Math.min(...data.map(d => d.depth)), Math.max(...data.map(d => d.depth))];
const kNumObjects = data.length;
const dynamicData = [];
// create 2 storage buffers
const staticUnitSize =
4 * 4 + // color = 4x4 (4 32-bit-floats x 4 bytes)
2 * 4; // offset = 2x4 (2 32-bit-floats x 4 bytes)
const dynamicUnitSize =
2 * 4; // scale = 2x4 (2 32-bit-floats x 4 bytes)
const staticBufferSize = staticUnitSize * kNumObjects;
const dynamicBufferSize = dynamicUnitSize * kNumObjects;

const staticBuffer = device.createBuffer({
size: staticBufferSize,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});

const dynamicBuffer = device.createBuffer({
size: dynamicBufferSize,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
// offsets to the various uniform values in float32 indices
const kColorOffset = 0;
const kOffsetOffset = 4;
//
const kScaleOffset = 0;

const staticValues = new Float32Array(staticBufferSize / 4);
for (let i = 0; i < kNumObjects; i++) {
const d = data[i];
const c = species.indexOf(data[i].species);
const staticOffset = i * (staticUnitSize / 4);

// color
staticValues.set(
[+(c === 0), +(c === 1), +(c === 2), 1],
staticOffset + kColorOffset
);

// offset
staticValues.set(
// lerp to clip space
// in subsequent notebooks, we will do these calculations in shaders (maybe compute?)
[
-1 + ((d.len - xExtent[0]) / (xExtent[1] - xExtent[0])) * (1 - (-1)),
-1 + ((d.depth - yExtent[0]) / (yExtent[1] - yExtent[0])) * (1 - (-1))
],
staticOffset + kOffsetOffset
);
// scale
dynamicData.push({ scale: 1 });
}
// write to gpu; will write dynamic values during render
device.queue.writeBuffer(staticBuffer, 0, staticValues);

// used to update dynamicBuffer
const dynamicValues = new Float32Array(dynamicBufferSize / 4);
// position (`@location(0)`)
const { vertices, count: vertexCount } = util.geom.circle({ r: 0.01, innerR: 0 });
const vertexBuffer = device.createBuffer({
size: vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vertexBuffer, 0, vertices);

const renderPassDescriptor = {
colorAttachments: [
{
clearValue: [0, 0, 0, 1],
loadOp: 'clear',
storeOp: 'store',
view: undefined, // to be filled out when we render
},
],
};

function render() {
renderPassDescriptor.colorAttachments[0].view = context.getCurrentTexture().createView();

const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(pipeline);
pass.setVertexBuffer(0, vertexBuffer);
pass.setVertexBuffer(1, staticBuffer);
pass.setVertexBuffer(2, dynamicBuffer);
// can cache this w a flag, esp since getting canvas dims is expensive
const aspect = context.canvas.width / context.canvas.height;

// set scales for each object
dynamicData.forEach(({ scale }, i) => {
const offset = i * (dynamicUnitSize / 4);
dynamicValues.set([scale / aspect, scale], offset + kScaleOffset); // set scale
});
// upload all scales at once
device.queue.writeBuffer(dynamicBuffer, 0, dynamicValues);

pass.draw(vertexCount, kNumObjects);
pass.end();
device.queue.submit([encoder.finish()]);
}

render()
return htl.html`
<figure>
${context.canvas}
<figcaption>
x = penguin culmen length (mm); y = penguin culment depth (mm)
<br><br>
${legend}
<br>
</figcaption>
</figure>
`;
}
Insert cell
Insert cell
data = penguins.reduce((ps, p) =>
isNaN(p.culmen_length_mm) || isNaN(p.culmen_depth_mm)
? ps
: [...ps, { len: p.culmen_length_mm, depth: p.culmen_depth_mm, species: p.species }],
[]
)
Insert cell
species = [...new Set(data.map(p => p.species))]
Insert cell
Insert cell
util = ({
rand: (min = 0, max = 1) => min + Math.random() * (max - min),
arr: (size, callback) => {
const arr = Array(size).fill(null)
return callback ? arr.map(callback) : arr;
},
ctx: (width = 512, height = 512) => {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('webgpu');
return context;
},
geom: {
circle: ({
r = 1,
subdivisions = 16,
innerR = 0,
startAngle = 0,
endAngle = Math.PI * 2
}) => {
// 2 triangles per subdivision * 3 verts per tri
const numVerts = subdivisions * 2 * 3;
// ... * 2 values (xy) each
const vertices = new Float32Array(numVerts * 2);

// 2 vertices per subdivision
//
// outer
// 0--1 4
// | / /|
// |/ / |
// 2 3--5
// inner
let offset = 0;
const add = (x, y) => ((vertices[offset++] = x), (vertices[offset++] = y));
for (let i = 0; i < subdivisions; i++) {
// can do lots of perf improvements here
const angle1 = startAngle + (i + 0) * (endAngle - startAngle) / subdivisions;
const angle2 = startAngle + (i + 1) * (endAngle - startAngle) / subdivisions;
const c1 = Math.cos(angle1);
const s1 = Math.sin(angle1);
const c2 = Math.cos(angle2);
const s2 = Math.sin(angle2);

// first tri
add(c1 * r, s1 * r)
add(c2 * r, s2 * r)
add(c1 * innerR, s1 * innerR)
// second tri
add(c1 * innerR, s1 * innerR)
add(c2 * r, s2 * r)
add(c2 * innerR, s2 * innerR)
}
return { vertices, count: numVerts }
}
}
})
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more