实现顶点和颜色缓冲区,创建两个三角形

This commit is contained in:
SpecialX
2025-11-18 18:57:47 +08:00
parent 186fb4515e
commit 4648ca10ad
2 changed files with 94 additions and 39 deletions

View File

@@ -4,7 +4,8 @@ class Renderer{
private device! : GPUDevice;
private context! : GPUCanvasContext;
private pipeline! : GPURenderPipeline;
private postitionBuffer! : GPUBuffer;
private colorBuffer! : GPUBuffer;
public async initialize()
{
@@ -37,42 +38,76 @@ class Renderer{
})
this.prepareModel();
this.postitionBuffer = this.CreateBuffer(new Float32Array([
-0.5, -0.5,
0.5, -0.5,
-0.5, 0.5,
-0.5, 0.5,
0.5, 0.5,
0.5, -0.5
]));
this.colorBuffer = this.CreateBuffer(new Float32Array([
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0
]));
}
public draw()
private CreateBuffer(data: Float32Array)
{
const commandEncoder = this.device.createCommandEncoder();
const textureView = this.context.getCurrentTexture().createView();
const buffer = this.device.createBuffer({
size: data.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true
});
const renderPassDescriptor:GPURenderPassDescriptor = {
colorAttachments:[{
view: textureView,
clearValue: {r: 0, g: 0, b: 0, a: 1},
loadOp: 'clear',
storeOp:'store'
}]
}
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
new Float32Array(buffer.getMappedRange()).set(data);
buffer.unmap();
//Draw here
passEncoder.setPipeline(this.pipeline );
passEncoder.draw(3);
passEncoder.end();
this.device.queue.submit([commandEncoder.finish()]);
return buffer;
}
private prepareModel() {
const shaderModule = this.device.createShaderModule({code: shaderSource});
const postitionBufferLayout : GPUVertexBufferLayout =
{
arrayStride: 2 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: 'float32x2'
}
],
stepMode: 'vertex'
}
const colorBufferLayout : GPUVertexBufferLayout =
{
arrayStride: 3 * Float32Array.BYTES_PER_ELEMENT,
attributes: [
{
shaderLocation: 1,
offset: 0,
format: 'float32x3'
}]
}
const vertexState: GPUVertexState = {
module : shaderModule,
entryPoint: "VertexMain",
buffers: []
buffers:
[postitionBufferLayout,
colorBufferLayout]
}
const fragmentState: GPUFragmentState = {
@@ -98,6 +133,37 @@ class Renderer{
}
public draw()
{
const commandEncoder = this.device.createCommandEncoder();
const textureView = this.context.getCurrentTexture().createView();
const renderPassDescriptor:GPURenderPassDescriptor = {
colorAttachments:[{
view: textureView,
clearValue: {r: 0, g: 0, b: 0, a: 1},
loadOp: 'clear',
storeOp:'store'
}]
}
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
//Draw here
passEncoder.setPipeline(this.pipeline );
passEncoder.setVertexBuffer(0, this.postitionBuffer);
passEncoder.setVertexBuffer(1, this.colorBuffer);
passEncoder.draw(6);
passEncoder.end();
this.device.queue.submit([commandEncoder.finish()]);
}
}