 | Mixing Data Types in Same Buffer - floats, integers, shorts, ... |  |
When you create buffers or arrays of buffers - there are occasions when you want to mix types. For example, floats, unsigned integers or ascii characters.
Like sweeties! Data very rarely comes along in a single format - it's usually mixed! You never know what you're going to have! So you need to be able to pack different data types together into structures.
First, let's start with the WGSL compute shader - what the data will look like and how it'll be packed together:
struct MyData { value_f32: f32, value_u32: u32, value_i32: i32 };
@group(0) @binding(0) var<storage, read_write> mixedData: MyData;
@compute @workgroup_size(1) fn main() { // Use the uniform values here let f: f32 = mixedData.value_f32; let u: u32 = mixedData.value_u32; let i: i32 = mixedData.value_i32; // ... // Modify the values (for testing purposes) mixedData.value_f32 = f + 1.0; mixedData.value_u32 = u + 1; mixedData.value_i32 = i + 1; }
We've got a structure called MyData which contains a mixture of floating point, signed, unsigned integers. So how do we go about creating this structure on the CPU side in JavaScript?
Let's create a JavaScript object that matches the structure defined in the shader. You also need to create a GPUBuffer to store this data and bind it to the shader.
Very very very important that the structure and alignment of the data in the JavaScript side matches the shader definition (including any hidden alignment padding). Otherwise, it'll be bad! Really really bad!
The solution is to use a ArrayBuffer and DataView so you can manually set each element in the buffer (including the type and any offset).
|