|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +let Example = { |
| 4 | + initialize: async function (canvas) { |
| 5 | + async function render(shaders) { |
| 6 | + if (!navigator.gpu) { |
| 7 | + throw new Error("WebGPU not supported on this browser."); |
| 8 | + } |
| 9 | + const adapter = await navigator.gpu.requestAdapter(); |
| 10 | + if (!adapter) { |
| 11 | + throw new Error("No appropriate GPUAdapter found."); |
| 12 | + } |
| 13 | + const device = await adapter.requestDevice(); |
| 14 | + const context = canvas.getContext("webgpu"); |
| 15 | + const canvasFormat = navigator.gpu.getPreferredCanvasFormat(); |
| 16 | + context.configure({ |
| 17 | + device: device, |
| 18 | + format: canvasFormat, |
| 19 | + }); |
| 20 | + |
| 21 | + const vertexBufferLayout = { |
| 22 | + arrayStride: 8, |
| 23 | + attributes: [{ |
| 24 | + format: "float32x2", |
| 25 | + offset: 0, |
| 26 | + shaderLocation: 0, |
| 27 | + }], |
| 28 | + }; |
| 29 | + |
| 30 | + const pipeline = device.createRenderPipeline({ |
| 31 | + label: "Pipeline", |
| 32 | + layout: "auto", |
| 33 | + vertex: { |
| 34 | + module: device.createShaderModule({ |
| 35 | + label: "Vertex shader module", |
| 36 | + code: shaders.vertex |
| 37 | + }), |
| 38 | + entryPoint: "vertexMain", |
| 39 | + buffers: [vertexBufferLayout] |
| 40 | + }, |
| 41 | + fragment: { |
| 42 | + module: device.createShaderModule({ |
| 43 | + label: "Fragment shader module", |
| 44 | + code: shaders.fragment |
| 45 | + }), |
| 46 | + entryPoint: "fragmentMain", |
| 47 | + targets: [{ |
| 48 | + format: canvasFormat |
| 49 | + }] |
| 50 | + } |
| 51 | + }); |
| 52 | + |
| 53 | + const vertices = new Float32Array([ |
| 54 | + 0.0, -0.8, |
| 55 | + +0.8, +0.8, |
| 56 | + -0.8, +0.8, |
| 57 | + ]); |
| 58 | + const vertexBuffer = device.createBuffer({ |
| 59 | + label: "Triangle vertices", |
| 60 | + size: vertices.byteLength, |
| 61 | + usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST, |
| 62 | + }); |
| 63 | + const bufferOffset = 0; |
| 64 | + device.queue.writeBuffer(vertexBuffer, bufferOffset, vertices); |
| 65 | + |
| 66 | + const encoder = device.createCommandEncoder(); |
| 67 | + const pass = encoder.beginRenderPass({ |
| 68 | + colorAttachments: [{ |
| 69 | + view: context.getCurrentTexture().createView(), |
| 70 | + loadOp: "clear", |
| 71 | + clearValue: { r: 0, g: 0, b: 0, a: 1 }, |
| 72 | + storeOp: "store", |
| 73 | + }] |
| 74 | + }); |
| 75 | + pass.setPipeline(pipeline); |
| 76 | + const vertexBufferSlot = 0; |
| 77 | + pass.setVertexBuffer(vertexBufferSlot, vertexBuffer); |
| 78 | + pass.draw(vertices.length / 2); |
| 79 | + pass.end(); |
| 80 | + const commandBuffer = encoder.finish(); |
| 81 | + device.queue.submit([commandBuffer]); |
| 82 | + } |
| 83 | + |
| 84 | + render({ |
| 85 | + vertex: await fetch("shader.vertex.wgsl").then(r => r.text()), |
| 86 | + fragment: await fetch("shader.fragment.wgsl").then(r => r.text()), |
| 87 | + }); |
| 88 | + } |
| 89 | +} |
0 commit comments