This commit is contained in:
Andras Schmelczer 2023-04-15 21:57:33 +01:00
parent 9cf8f73e18
commit 5cc94805f1
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
17 changed files with 670 additions and 237 deletions

View file

@ -0,0 +1,80 @@
import shader from './render.wgsl';
export class RenderPipeline {
private readonly pipeline: GPURenderPipeline;
private bindGroup?: GPUBindGroup;
private previousColorTexture?: GPUTexture;
public constructor(
private readonly context: GPUCanvasContext,
private readonly device: GPUDevice,
preferredCanvasFormat: GPUTextureFormat
) {
this.pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: device.createShaderModule({
code: shader,
}),
entryPoint: 'vertex',
},
fragment: {
module: device.createShaderModule({
code: shader,
}),
entryPoint: 'fragment',
targets: [
{
format: preferredCanvasFormat,
},
],
},
primitive: {
topology: 'triangle-strip',
},
});
}
public execute(commandEncoder: GPUCommandEncoder, colorTexture: GPUTexture) {
this.ensureBindGroupExists(colorTexture);
const renderPassDescriptor: GPURenderPassDescriptor = {
colorAttachments: [
{
view: this.context.getCurrentTexture().createView(),
clearValue: { r: 0.0, g: 0.0, b: 0.0, a: 1.0 },
loadOp: 'clear',
storeOp: 'store',
},
],
};
const renderPassEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
renderPassEncoder.setBindGroup(0, this.bindGroup);
renderPassEncoder.setPipeline(this.pipeline);
renderPassEncoder.draw(4, 1);
renderPassEncoder.end();
}
private ensureBindGroupExists(colorTexture: GPUTexture) {
if (this.previousColorTexture !== colorTexture) {
this.bindGroup = this.device.createBindGroup({
layout: this.pipeline.getBindGroupLayout(0),
entries: [
{
binding: 0,
resource: this.device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
}),
},
{
binding: 1,
resource: colorTexture.createView(),
},
],
});
this.previousColorTexture = colorTexture;
}
}
}

View file

@ -0,0 +1,30 @@
struct VertexOutput {
@builtin(position) Position : vec4<f32>,
@location(0) fragUV : vec2<f32>,
}
@vertex
fn vertex(@builtin(vertex_index) i : u32) -> VertexOutput {
var pos = array<vec2<f32>, 4>(
vec2(-1.0, 1.0),
vec2(-1.0, -1.0),
vec2(1.0, 1.0),
vec2(1.0, -1.0),
);
var output : VertexOutput;
output.Position = vec4<f32>(pos[i], 0.0, 1.0);
output.fragUV = output.Position.xy * 0.5 + 0.5;
return output;
}
@group(0) @binding(0) var mySampler: sampler;
@group(0) @binding(1) var TargetTexture : texture_2d<f32>;
@fragment
fn fragment(@location(0) fragUV: vec2<f32>) -> @location(0) vec4<f32> {
// return vec4(1.0, 0.0, 0.0, 1.0);
return textureSample(TargetTexture, mySampler, fragUV);
}