WebGPU uniforms and alignment (?)
I'm using the webgpu cube example and added a few more uniforms to test stuff out (sorry, I couldn't get this to work on Codesandbox):
struct Uniforms {
projectionMatrix: mat4x4f,
modelViewMatrix: mat4x4f,
normalMatrix: mat4x4f,
color: vec3f,
time: f32,
darkness: f32,
};
@group(0) @binding(0) var<uniform> uniforms: Uniforms;
struct VertexIn {
@builtin(vertex_index) vertexIndex: u32,
@location(0) position: vec3<f32>,
@location(1) normal: vec3<f32>,
};
struct VertexOut {
@builtin(position) position: vec4<f32>,
@location(0) color: vec3<f32>,
@location(1) normal: vec3<f32>,
};
@vertex
fn main(input: VertexIn) -> VertexOut {
var out: VertexOut;
var transformed = input.position + vec3f(0, sin(uniforms.time * 2), 0);
out.position = uniforms.projectionMatrix * uniforms.modelViewMatrix * vec4(transformed, 1.0);
out.color = uniforms.color * uniforms.darkness;
out.normal = (uniforms.normalMatrix * vec4f(input.normal, 0.0)).xyz;
return out;
}
const material = new Material({
uniforms: {
color: [.2, .4, .4],
time: .5,
darkness: .5,
},
vertex,
fragment,
})
When I do that the time uniform does not update, and darkness seems to pick out the data from time instead. also: the order of the struct Uniform members change the behaviour as this order does work:
struct Uniforms {
projectionMatrix: mat4x4f,
modelViewMatrix: mat4x4f,
normalMatrix: mat4x4f,
time: f32,
darkness: f32,
color: vec3f,
};
or even do color: vec4f it works as expected again. I'm am very new to WebGPU, so I might be missing something obvious here, but from what I can tell there is no need to do manual layout/padding (?) for the struct definition? Also four seems to be handling things on its own with the std140 helper?
I'm not able to observe this issue. This is the expected memory layout for the shader (offset calculator):