home/ atoms/ wgsl-struct-shader-io

WGSL structs bundle multiple @location and @builtin annotated fields into a single typed input or output for shader functions

WGSL structs are named object types declared outside functions. In shaders, they group multiple annotated fields — @builtin or @location(n) — into a single typed value used as a function parameter or return type. Structs make it easy to pass many values between pipeline stages and to reuse the vertex output struct as the fragment input type. The declaration syntax is struct Name { field: type, ... } and instances are declared as var output: Name; with fields set individually before return.

Examples

struct VertexInput { @location(0) pos: vec2f, @builtin(instance_index) instance: u32 };
struct VertexOutput { @builtin(position) pos: vec4f, @location(0) cell: vec2f };
@vertex fn vertexMain(input: VertexInput) -> VertexOutput { ... }

Assessment

Without structs, how many individual arguments would a vertex function need for position + instance_index + UV + normal? Why does reusing VertexOutput as the fragment input type reduce errors?

“Structs in WGSL are named object types that contain one or more named”
corpus · your-first-webgpu-app-google-codelab · chunk 12