Skip to content

四角形に画像を貼り付け

import { createSquareBuffer } from "./square"
import { createWebGPUTextureFromImageUrl } from "./image"
import shaderCode from "./shader.wgsl?raw"
import imageUrl from "../assets/twinkle.png?url"
const adapter = await navigator.gpu.requestAdapter()
if (!adapter) {
throw new Error("WebGPU cannot be initialized - Adapter not found")
}
const device = await adapter.requestDevice()
device.lost.then(() => {
throw new Error("WebGPU cannot be initialized - Device has been lost")
})
const canvas = document.querySelector("canvas")
const context = canvas!.getContext("webgpu")
if (!context) {
throw new Error("WebGPU cannot be initialized - Canvas does not support WebGPU")
}
const canvasFormat = navigator.gpu.getPreferredCanvasFormat()
context.configure({ device, format: canvasFormat })
const { vertexBuffer, indexBuffer, indexCount } = createSquareBuffer(device, 1.0)
const texture = await createWebGPUTextureFromImageUrl(device, imageUrl)
const sampler = device.createSampler({
magFilter: "linear",
minFilter: "linear"
})
const shaderModule = device.createShaderModule({ code: shaderCode })
const renderPipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module: shaderModule,
entryPoint: "vs_main",
buffers: [
{
arrayStride: 4 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: "float32x2"
},
{
shaderLocation: 1,
offset: 2 * Float32Array.BYTES_PER_ELEMENT,
format: "float32x2"
}
]
}
]
},
fragment: {
module: shaderModule,
entryPoint: "fs_main",
targets: [
{
format: canvasFormat
}
]
}
})
const uniformBindGroup = device.createBindGroup({
layout: renderPipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: texture.createView()
},
{
binding: 1,
resource: sampler
}
]
})
const commandEncoder = device.createCommandEncoder()
const renderPass = commandEncoder.beginRenderPass({
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
loadOp: "clear",
clearValue: { r: 0.824, g: 0.878, b: 0.984, a: 1 },
storeOp: "store"
}
]
})
renderPass.setPipeline(renderPipeline)
renderPass.setBindGroup(0, uniformBindGroup)
renderPass.setVertexBuffer(0, vertexBuffer)
renderPass.setIndexBuffer(indexBuffer, "uint16")
renderPass.drawIndexed(indexCount)
renderPass.end()
device.queue.submit([commandEncoder.finish()])