Compute Shader (WGS) and Web CANVAS (NOT Graphics Pipeline)
Compute to Canvas (Screen) using Textures. Loads and maps texture onto the circle surface (more than just a flat color).
The purpose of this example is to use the compute shader to generate graphics and redirect the output to the CANVAS texture (not via the render pipeline).
For this example, you'll do a simple ray-tracing example - well sort of.... it's a signed distance calculation for a circle.
The meat of the code is actually creating textures with the appropriate flags (e.g., the CANVAS texture needs to allow GPU binding/copying).
To make the example extra juicy - instead of just rendering a color circle to the output - we also load in a texture and bind it to the compute pipeline (texture_2d) which we use to color the circle (in this example it's a rainbow zebra pattern).
The steps for the code:
• 1. Load the texture (basic Javascript load code)
• 2. Initialize WebGPU
• 3. Get WebGPU Canvas (and the texture handle for it) - important the correct flags are set in the context configuration
• 4. Setup the texture buffers (for the pipeline to render to)
• 5. Compute pipeline layout/group (so the shader/pipeline both knows what goes in/out)
• 6. Create pipeline
• 7. WGSL compute shader code (compile this and pass it to the pipeline)
• 8. After the compute shader has finished we do a 'texture-to-texture' copy to put the output on the Canvas.
The demo only does a single shot pass - however, you can modify the final lines of code so they loop (update compute shader, copy to canvas...repeat).
/* Create a `compute' pipeline which will do all the work - compute -> texture -> canvas (screen) */
let div = document.createElement('div'); document.body.appendChild( div ); div.style['font-size'] = '20pt'; function log( s ) { console.log( s ); let args = [...arguments].join(' '); div.innerHTML += args + '<br><br>'; }