|
|
 |
WebGPU Shader Language...
Even web-pages can use the power of the GPU... |
|
|
|
 | Function Pointers in WGSL |  |
WGSL does not support traditional function pointers like in C or GLSL. Instead, it uses pointer-to-function-variable arguments (`ptr`) to pass mutable function-scoped variables by reference. This allows functions to modify their arguments directly, similar to `inout` parameters in other languages.
Example of what the syntax looks like:
fn pcount(p: ptr<function, vec2<f32>>, num f32) -> f32 {
...
}
 | Why Use Function Pointers? |  |
Passing a `ptr` is useful when:
1. You need to modify a variable inside a function and retain changes after the call (avoiding copies).
2. Working with large structs where passing by value would be inefficient.
3. Implementing SDF operations (like `pModPolar`) that transform coordinates in-place.
 | Syntax & Common Errors |  |
The syntax `fn foo(p: ptr>)` declares a function that takes a mutable reference to a vec2<f32> . Key pitfalls:
❌ Only works in 'function' address space (not private /workgroup ).
❌ Must dereference with `*p` to read/write (e.g., (*p).x = 1.0 ).
❌ The original variable must be marked as var not let ).
 | Minimal WGSL Example |  |
// Function that modifies a vec2 via pointer
fn add_one(p: ptr<function, vec2<f32>>) {
(*p).x += 1.0; // Dereference to modify
(*p).y += 1.0;
}
@fragment
fn main() -> @location(0) vec4<f32> {
var coord = vec2<f32>(0.5, 0.5); // Must be 'var'!
add_one(&coord); // Pass as pointer
// coord is now (1.5, 1.5)
return vec4<f32>(coord, 0.0, 1.0);
}
Output:
• coord becomes (1.5, 1.5) after add_one .
• Without ptr<function> , changes would be local to the function.
Compare to Incorrect Usage:
<?php
let coord = vec2<f32>(0.5); // ❌ Fails: 'let' is immutable!
add_one(&coord); // ❌ Can't take pointer to const.
Use ptr<function> sparingly—it’s best for performance-critical in-place updates.
 | Resources & Links |  |
• WebGPU Shader Language Information/Tutorials
• WGSL API
|
|