Hasty Briefsbeta

Bilingual

Testing WebGPU data layouts with Facet

a day ago
  • GPU compute shaders often require alignment between host (Rust) and shader (WGSL) struct layouts, which can have subtle differences like padding.
  • A common issue is that Rust's `[[f32; 3]; 3]` is tightly packed (36 bytes), while WGSL's `mat3x3f` has per-row padding, resulting in 48 bytes, causing offset mismatches.
  • Manual field-by-field checking is error-prone and lacks diagnostic clarity; a generic solution using runtime reflection (via the `facet` library) automates the comparison.
  • The `facet` library provides `#[derive(facet::Facet)]` for structs, enabling automated checks of field offsets and sizes against WGSL structs parsed with `naga`.
  • The generic checker function verifies overall struct size (handling runtime-sized arrays), field offsets, field sizes, and ensures all WGSL members exist in Rust.
  • The approach is conditionally compiled for tests (`#[cfg_attr(test, derive(facet::Facet))]`), allowing easy integration without overhead in production builds.
  • These tests help catch layout mismatches proactively when adding new compute shaders, improving confidence in data loading correctness.