Arrange layout of a struct to automatically conform to GLSL std140

24 Views Asked by At

For a GPU to consume data from CPU memory, the layout assumed by the GPU must match the layout of how the data is stored in CPU memory. This assumption is encoded by the std140 rules.

I'd like the C# compiler to arrange the layout of my struct automatically according to std140. Some of these rules are:

  • The alignment of float is 4 (= sizeof(float)).
  • The alignment of a 2-element vector of floats vec2 is 8 (= 2 * sizeof(float)).
  • The alignment of a 4-element vector of floats vec4 is 16 (= 4 * sizeof(float)).

It is not relevant for this question to know all the rules, so let us assume that the above three cover all the rules.

I would like to be able to write something like:

[Std140Layout]
public struct Data 
{
    public float x;
    public vec2 y;
    public float z;
    public vec4 w;
}

And have it automatically generate the following code:

[StructLayout(LayoutKind.Explicit)]
public struct Data 
{
    [FieldOffset(0)] 
    public float x;
    
    [FieldOffset(8)] 
    public vec2 y;

    [FieldOffset(16)] 
    public float z;
    
    [FieldOffset(32)] 
    public vec4 w;
}

Is this possible to achieve by e.g. reflection, and if so, how?

0

There are 0 best solutions below