代碼見:https://github.com/onsummer/my-dev-notes/tree/master/webgpu-Notes/02-buffer%26color

創建buffer
與 WebGL 的 gl.createBuffer() 幾乎一樣,
const vbodata = https://www.cnblogs.com/onsummer/archive/2021/03/31/new Float32Array([
-0.5, 0.0, 1.0, 0.0, 0.0, 1.0,
0.0, 0.5, 0.0, 1.0, 0.0, 1.0,
0.5, 0.0, 0.0, 0.0, 1.0, 1.0
])
const vbo = device.createBuffer({
size: vbodata.byteLength,
usage: GPUBufferUsage.VERTEX,
mappedAtCreation: true
})
與 Float32Array 的系結,跟 WebGL 就完全不同了:
new Float32Array(buffer.getMappedRange()).set(vbodata)
vbo.unmap()
創建一個坐標快取,一個顏色快取,
頂點著色器
[[builtin(position)]] var<out> out_position: vec4<f32>;
[[location(0)]] var<out> out_color: vec4<f32>;
[[location(0)]] var<in> in_position_2d: vec2<f32>;
[[location(1)]] var<in> in_color_rgba: vec4<f32>;
[[stage(vertex)]]
fn main() -> void {
out_position = vec4<f32>(in_position_2d, 0.0, 1.0);
out_color = in_color_rgba;
return;
}
與 glsl 有幾分相似,但是多了一個出口,
片元著色器
頂點著色器的輸出,在片元著色器里就要輸入,
[[location(0)]] var<out> fragColor: vec4<f32>;
[[location(0)]] var<in> in_color: vec4<f32>;
[[stage(fragment)]]
fn main() -> void {
fragColor = in_color;
return;
}
管線組裝
兩端都準備完成后,就要在管線里拼接他們了,
const pipeline = device.createRenderPipeline({
vertex: {
... // 其他引數同 01 的
buffers: [{
arrayStride: 6 * vbodata.BYTES_PER_ELEMENT,
attributes: [{
shaderLocation: 0,
offset: 0,
format: 'float32x2'
}, {
shaderLocation: 1,
offset: 2 * vbodata.BYTES_PER_ELEMENT,
format: 'float32x4'
}]
}]
},
fragment: , // 略
primitive: , // 略
})
最后,在通道編碼器指定坐標快取、顏色快取,
passEncoder.setVertexBuffer(0, vbo)
資料交錯
將兩個快取合并成一個,vertexState 中的 vertexBuffer 下的 arrayStride 要改動,若為二維坐標+rgba顏色,那么就要改為 6x4 了;offset 屬性也要改動,即從 buffer 的第幾個位元組開始是它自己第一個資料,
或者合并 vertexBuffer 物件下的 attributes 屬性,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/270803.html
標籤:其他
下一篇:SQL注入靶場實戰-小白入門
