Initialize array in glsl

I want initialize an array from uniform, but the problem I cannot because the array must be init from const.
For this reason I must write a same method ntwice, that’s make a lot of code to write the same thing.

is it possible ?

my problem :

const int p_2 = 2;
const int p_3 = 3;
const int p_4 = 4;
const int p_5 = 5;
const int p_6 = 6;
const int p_7 = 7;
const int p_8 = 8;
const int p_9 = 9;

vec3 palette_2() {
	vec3 palette [p_2]; 
        // rest of code
} 

vec3 palette_3() {
	vec3 palette [p_3]; 
        // rest of code
} 
vec3 palette_4() {
	vec3 palette [p_4]; 
        // rest of code
}

.../...

I want write something like

uniform int num;
vec3 palette(int num) {
     vec3 palette [num]; 
}
1 Like

Hi! Your last example looks a bit odd, as the palette is duplicated as function name and variable and there’s no return in:

vec3 palette(int num) {
     vec3 palette [num]; 
}

Maybe you want to have something like

const vec3 palette[3] = vec3[3](
  vec3(0.0, 0.1, 0.2),
  vec3(0.3, 0.1, 0.2),
  vec3(0.5, 0.1, 0.2)
);

and then access

palette[index]

to get a color? Is that the goal?

But consider possible issues and these too (in case it doesn’t work, or if you want to distribute your program).

3 Likes

Sure, I write where is my problem, the reason why there is no return :slight_smile:
to see the full code is here https://github.com/StanLepunK/Filter/blob/master/filters/shader/pixel.glsl

I need if it’s possible only one method, here i can init the array palette with a uniform, or may be change the array size at each frame. Because in my architectory if I want change the size of the palette I need to copy the method for each size of palette, because I need a const in the method. I hope my problem is better understandable ?

Why not make an array of the maximum size you will ever need, and then only use the number of elements needed on the current case?

For example, if you never need more than 32 items, then vec3 palette[32] = vec3[32]; and if on the current frame you only need 5 items, then iterate over 5 items and assign values to them. Would that work?

To me it sounds not ideal to make an array of different size on every frame, better to keep the array of fixed size and then only use as much of it as you need.

Looking at the palette_4 example, I think it could be written even without using an array and with only one for loop, as if you find the right color a break is triggered, which means it was not necessary to calculate the remaining colors. But maybe other palette_X cases do need an array?

4 Likes

“Elementary, my dear Watson”… why I don’t think about that soon. Thx a lot for your simple and GREAAATTTT idea. Best for X-mass my dear Hamoid !

1 Like