Recursive structs?
Hello,
I can't find any info about nested struct, something like this:
struct MyData {
v1:vec4<f32>,
children: array<MyData>
}
Is it planned to deal with such a structure or is there a workaround to achieve this ?
Thank you in advance for your help.
Just to note, this is a request for recursive structs, nested structs are already available in WGSL.
Interesting, I wasn't able to find info about nested struct like this:
struct MyNestedData {
v2:vec4<f32>
}
struct MyData {
v1:vec4<f32>,
nested_datas: array<MyNestedData>
}
If it is possible to set an array of nested struct, why not recursive structs ?
See https://www.w3.org/TR/WGSL/#struct-types where it lists the types of a struct member. The last item: a structure type that has a creation-fixed footprint.
The recursive struct is an error because, currently, the spec says:
It is a shader-creation error if any module scope declaration is recursive. That is, no cycles can exist among the declarations:
Even if that were lifted, it would not be possible to create a recursive struct like the one in your example: members of a struct are inline in the struct so the size would be infinite: sizeof(MyData) = sizeof(vec4f) + sizeof(MyData)
A struct can only recurse if the recursive member puts the struct behind a pointer indirection (ptr<> in WGSL). However it is not possible to allocate memory inside a WGSL shader, so the pointer would need to be to either:
- host-shareable memory (uniform buffer or storage buffer) - not possible because
ptrtypes can't be stored in host-shareable memory. - or a local variable. So you could set up
var1and have it point tovar2and have it point tovar3but you would have to define all of them. - or, very similarly, an element of an array defined in a local variable (which must be fixed-size because allocation isn't possible).
+1 to be clear, this choice reflects constraints in the shader languages in underlying APIs: not every underlying shading language allows you to store a pointer in memory. In WGSL this is captured by the fact that ptr<...> types are not storable
WGSL 2024-06-25 Minutes
- (milestone?)
- DS: Nested structs is already in the spec. Recursive structs…. No.
- DN: Recursive structs is syntactic sugar for storing pointers.
- KG: Have a need for a struct self-reference, like
struct Foo { ptr<Foo> - DN: Order independence at module-scope means it’s already there in terms of identifier resolution.
- JB: Implies malloc?
- AB: No: can have a structure built on the CPU side, and represented in a buffer. (Vulkan buffer reference feature)
- JB: No plans for this.
- AB: This needs a full deliberate design, and it wouldn’t start from this language feature.
- Resolved to close as “no current plans”