WGSL初探
WGSL初探
WGSL 通过 @vertex、@fragment、@compute 三个着色器阶段(Shader State)进行编写代码
@location(0)和@location(1)
struct VertexInput {
@location(0) position: vec3f,
@location(1) color: vec3f,
};
struct VertexOutput {
@builtin(position) clip_position: vec4f,
@location(0) color: vec3f,
};
@vertex
fn vs_main(
model: VertexInput,
) -> VertexOutput {
var out: VertexOutput;
out.color = model.color;
out.clip_position = vec4f(model.position, 1.0);
return out;
}
@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4f {
return vec4f(in.color, 1.0);
}
上述代码来自wgpu教程( https://jinleili.github.io/learn-wgpu-zh/beginner/tutorial1-window )
我尝试对代码进行分析,@vertex和@frgment属于渲染管线。在另一个文件中,render_pipeline()等函数,提前设置好数据,然后二者接收并进行渲染。
@location(0)和@location(1)可以理解为一种属性标记,表示一个存放槽点存储点数据,一个颜色数据。
wgpu::VertexBufferLayout{
//...
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 0,
format: wgpu::VertexFormat::Float32x3,
},
wgpu::VertexAttribute {
offset: core::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
shader_location: 1,
format: wgpu::VertexFormat::Float32x3,
},
],
}
shader_location 告诉着色器什么位置存储这个属性,而在.wgsl中对应的就是@location(0)和@location(1)
vec4f
vec4f表示由 4 个 32 位浮点数组成的向量,需要注意的是@builtin(position) 类型为 vec4f。
@builtin(position) 是内置变量,无法对外使用。其标记了此字段将作为顶点在裁剪坐标系中的位置,vec4f中前三个向量表示坐标(x,y,z)而最后一个是齐次权重,w取1表示坐标不变,而w不等于1就代表点数据被透视投影了。
return vec4f(in.color, 1.0);中的1.0表示的alph值,就是透明度,另外VertexOput中的@location(0),与VertexInput中的@location(0)是WGSL的一种特殊写法,WGSL 不再需要像 GLSL 一样,在顶点着色器中定义完输出字段后,再到片元着色器中定义相应的输入字段。

浙公网安备 33010602011771号