 | Mutable Global Variable |  |
In WGSL, var<private> declares a mutable global variable that is only accessible within the same shader module (unlike uniform or storage buffers, which can be shared across pipelines). Unlike const (which is immutable and must be initialized at declaration), a private variable can be modified at runtime.
For example:
• const variable:f32 = 2.0; → Fixed value, cannot change.
• var<private> gTime: f32 = 0.0; → Can be updated (e.g., gTime = 1.0; ).
 | Why Use var<private> ? Pros and Cons |  |
Use cases:
• Track state across multiple functions in a shader (e.g., animation time).
• Store intermediate results reused in later calculations.
Pros:
✔️ Retains value across function calls.
✔️ Avoids passing values through parameters repeatedly.
Cons:
❌ Not shared between shader invocations (unlike workgroup or storage vars).
❌ Overuse can make code harder to debug (global state).
 | Simple WGSL Example |  |
// A private variable (mutable, module-scoped) var<private> counter: f32 = 0.0;
// A constant (immutable) const MAX_COUNT: f32 = 5.0;
@fragment fn main() -> @location(0) vec4<f32> { // Update the private variable counter = counter + 1.0; // Use it to compute color (resets after MAX_COUNT) let progress = counter / MAX_COUNT; return vec4<f32>(progress, 0.0, 1.0 - progress, 1.0); }
Key Notes:
• counter persists across shader invocations (but only for the current GPU thread).
• Unlike const MAX_COUNT , counter can be modified.
• Try replacing var<private> with const —it will fail because const can’t be reassigned!
 | When to Avoid private |  |
Use workgroup for compute shaders (shared across threads) or uniform for CPU-GPU data. Reserve private for shader-internal state.
 | Where To Learn More |  |
• WebGPU Tutorials/Books [LINK]
• WebGPU Lab (100s of WebGPU Examples) [LINK]
• Official WGSL Documentation [LINK]
|