Search code examples
glslshader

How to initialize an array inside a struct GLSL


I'm try to initialize an array inside a struct, as follow:

struct myStruct {

  vec3 data[20] = vec3[20] (vec3(1, 1,  1), vec3( 1, -1,  1), vec3(-1, -1,  1), vec3(-1, 1,  1),
                            vec3(1, 1, -1), vec3( 1, -1, -1), vec3(-1, -1, -1), vec3(-1, 1, -1),
                            vec3(1, 1,  0), vec3( 1, -1,  0), vec3(-1, -1,  0), vec3(-1, 1,  0),
                            vec3(1, 0,  1), vec3(-1,  0,  1), vec3( 1,  0, -1), vec3(-1, 0, -1),
                            vec3(0, 1,  1), vec3( 0, -1,  1), vec3( 0, -1, -1), vec3( 0, 1, -1));

};

But I get this error:

ERROR: 0:84: '=' : syntax error: syntax error

It is possible to do that?


Solution

  • struct starts a type specification and not a variable declaration. You have to declare a variable and to use a struct constructor (See Data Type (GLSL) - Struct constructors):

    struct myStruct {
        vec3 data[20];
    };
    
    myStruct myVar = myStruct( vec3[20]( vec3(1, 1,  1), ..... ) );
    


    See GLSL Specification - 4.1.8 Structures

    User-defined types can be created by aggregating other already defined types into a structure using the struct keyword. For example,

    struct keyword. For example,
        struct light {
        float intensity;
        vec3 position;
    } lightVar;
    

    Structures can be initialized at declaration time using constructors, as discussed in section 5.4.3 “Structure Constructors”


    See GLSL Specification - 5.4.3 Structure Constructors

    Once a structure is defined, and its type is given a name, a constructor is available with the same name to construct instances of that structure. For example:

    struct light {
        float intensity;
        vec3 position;
    };
    light lightVar = light(3.0, vec3(1.0, 2.0, 3.0));