Webgpu草案
内容纲要
WebGPU是针对万维网的新开放源代码图形API标准的草案提案。苹果的WebKit团队于2017年2月7日宣布了该项目。目前为止,苹果正在向W3C提出这个新标准,试图在浏览器中开发下一代图形技术。
相关Api都是实验性的,随时会改,与WebGL的区别、文档等详见官网。
目前,着色器有两种:GLSL 和 WGSL。
个人推荐WGSL,未来技术应该也会是这个。
以下是测试代码,用于绘制一个多边形:
<canvas id="c" width="512" height="512"></canvas>
<script id="vs" type="x-shader/x-vertex">
[[location(0)]] var<in> position : vec3<f32>;
[[builtin(position)]] var<out> Position : vec4<f32>;
[[stage(vertex)]]
fn main() -> void {
Position = vec4<f32>(position, 1.0);
return;
}
</script>
<script id="fs" type="x-shader/x-fragment">
[[location(0)]] var<out> outColor : vec4<f32>;
[[stage(fragment)]]
fn main() -> void {
outColor = vec4<f32>(0.0, 0.0, 1.0, 1.0);
return;
}
</script>
const vs = document.getElementById("vs").textContent;
const fs = document.getElementById("fs").textContent;
init();
async function init() {
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const c = document.getElementById('c');
const ctx = c.getContext('gpupresent');
const swapChainFormat = "bgra8unorm";
const swapChain = ctx.configureSwapChain({device, format: swapChainFormat});
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({bindGroupLayouts: []}),
vertexStage: {
module: device.createShaderModule({
code: vs
}),
entryPoint: 'main'
},
fragmentStage: {
module: device.createShaderModule({
code: fs
}),
entryPoint: 'main'
},
vertexState: {
vertexBuffers: [{
arrayStride: 12, // 3 * 4bytes
attributes: [{
shaderLocation: 0,
offset: 0,
format: "float3"
}]
}]
},
colorStates: [{
format: swapChainFormat,
alphaBlend: {
srcFactor: "src-alpha",
dstFactor: "one-minus-src-alpha",
operation: "add"
}
}],
primitiveTopology: 'triangle-list',
});
const positions = [
0.0, 0.5, 0.0, // v0
-0.5,-0.5, 0.0, // v1
0.5,-0.5, 0.0 // v2
];
const data = new Float32Array(positions);
const vertexBuffer = device.createBuffer({
size: data.byteLength,
usage: GPUBufferUsage.VERTEX,
mappedAtCreation: true,
});
new Float32Array(vertexBuffer.getMappedRange()).set(data);
vertexBuffer.unmap();
const render = function () {
const commandEncoder = device.createCommandEncoder();
const textureView = swapChain.getCurrentTexture().createView();
const renderPassDescriptor = {
colorAttachments: [{
attachment: textureView,
loadValue: {r: 1.0, g: 1.0, b: 1.0, a: 1.0},
}]
};
const passEncoder = commandEncoder.beginRenderPass(renderPassDescriptor);
passEncoder.setVertexBuffer(0, vertexBuffer);
passEncoder.setPipeline(pipeline);
passEncoder.draw(3, 1, 0, 0);
passEncoder.endPass();
device.defaultQueue.submit([commandEncoder.finish()]);
}
requestAnimationFrame(render);
}
草案2017年就已经有了,一直在推进。
Api变化较快,且浏览器支持不一,详见执行状态
相信很快就能发布正式版。
code enjoy! 🐾🐾🐾🐾🐾🐾🐾🐾🐌🐝
作者:indeex
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。