Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebGPU Compute Shader</title>
</head>
<body>
<canvas id="canvas" width="640" height="480"></canvas>
</body>
</html>
              
            
!

CSS

              
                
              
            
!

JS

              
                async function main() {
    const inputArr = getInput();
    const initAt = Date.now();

    if (!navigator.gpu) {
        throw Error("WebGPU not supported.");
    }

    const adapter = await navigator.gpu.requestAdapter();
    if (!adapter) {
        throw Error("Couldn’t request WebGPU adapter.");
    }

    const device = await adapter.requestDevice();
    if (!device) {
        throw Error('need a browser that supports WebGPU');
    }

    const canvas = document.querySelector('canvas');
    const context = canvas.getContext('webgpu');
    const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
    context.configure({
        device,
        format: presentationFormat,
    });

    // Shader module
    const module = device.createShaderModule({
        label: 'sinus compute module',
        code: `
      @group(0) @binding(0) var<storage, read_write> data: array<f32>;
 
      @compute @workgroup_size(4, 4, 4) fn computeSinus(
        @builtin(global_invocation_id) id: vec3u
      ) {
        //  workgroup_id * workgroup_size + local_invocation_id
        let i = id.x;
        data[1] = 
        sin(data[1] * 1.0) + 
        sin(data[1] * 2.0) + 
        sin(data[1] * 3.0) + 
        sin(data[1] * 4.0) +
        sin(data[1] * 5.0) +
        sin(data[1] * 6.0) +
        sin(data[1] * 7.0) +
        sin(data[1] * 8.0) +
        sin(data[1] * 9.0) +
        sin(data[1] * 10.0)
        ;
      }
    `,
    });

    // Pipeline
    const pipeline = device.createComputePipeline({
        label: 'do compute pipeline',
        layout: 'auto',
        compute: {
            module,
            entryPoint: 'computeSinus',
        },
    });

    // Buffer
    const input = new Float32Array(inputArr);

    const gpuBuffer  = device.createBuffer({
        label: 'input buffer',
        size: input.byteLength,
        usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
    });

    const resultBuffer = device.createBuffer({
        label: 'result buffer',
        size: input.byteLength,
        usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
    });
    device.queue.writeBuffer(gpuBuffer, 0, input);

    const bindGroup = device.createBindGroup({
        label: 'bindGroup for input buffer',
        layout: pipeline.getBindGroupLayout(0),
        entries: [
            { binding: 0, resource: { buffer: gpuBuffer } },
        ],
    });


    const startCalcAt = Date.now();
    const timeToInit = startCalcAt - initAt;
    console.log("Time to init: " + timeToInit + " milliseconds");

    // Commands
    const encoder = device.createCommandEncoder({
        label: 'sinus encoder',
    });
    const pass = encoder.beginComputePass({
        label: 'sinus compute pass',
    });
    pass.setPipeline(pipeline);
    pass.setBindGroup(0, bindGroup);
    pass.dispatchWorkgroups(128, 128, 32); // 512 × 512 × 128
    pass.end();

    encoder.copyBufferToBuffer(gpuBuffer, 0, resultBuffer, 0, resultBuffer.size);

    const commandBuffer = encoder.finish();
    device.queue.submit([commandBuffer]);

    // Read the results
    await resultBuffer.mapAsync(GPUMapMode.READ);
    const result = new Float32Array(resultBuffer.getMappedRange());

    let timeTaken = Date.now() - startCalcAt;
    console.log("Time to compute: " + timeTaken + " milliseconds");

    resultBuffer.unmap();
}

function getInput() {
    const input = [];
    // 512 × 512 × 128
    for (let i = 0; i < 33_554_432; i++) {
        input[i] = i;
    }

    return input;
}

main();
              
            
!
999px

Console