五、WebGPU——动态改变颜色

163 阅读1分钟

前面项目中,颜色是在着色器中定义的。这次,我们把颜色作为uniform变量传入着色器,实现颜色的动态控制。实现rgb三个分量的动态控制,透明值动态设置。

着色器

@group(0) @binding(0) var<uniform> color : vec4<f32>;
@fragment
fn fragmentMain() -> @location(0) vec4f {
    return color;
}

创建颜色缓存,创建颜色组

// 创建颜色缓存
const colorBuffer = device.createBuffer({
    label: 'GPUBuffer store rgba color',
    size: 4 * 4,
    usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
})
device.queue.writeBuffer(colorBuffer, 0, new Float32Array([1, 1, 0, 1]))

// 创建颜色组
const uniformGroup = device.createBindGroup({
    label: 'Uniform Group with colorBuffer',
    layout: pipeline.getBindGroupLayout(0),
    entries: [
        {
            binding: 0,
            resource: {
                buffer: colorBuffer
            }
        }
    ]
})

渲染管道绑定颜色组

passEncoder.setBindGroup(0, pipelineObj.uniformGroup)

动态改变颜色

//动态改变颜色
setTimeout(() => {
    device.queue.writeBuffer(pipelineObj.colorBuffer, 0, new Float32Array([1, 0, 1, 1]))
    draw(device, context, pipelineObj, vertices)
}, 2000)