Search code examples
javaopengl-esglsllwjgl

How to pass an array of float to Shader in LWJGL


I have been following the tutorial on LWJGL's website (http://wiki.lwjgl.org/wiki/GLSL_Tutorial:_Communicating_with_Shaders.html) to try to send an array of random floats to my fragment shader, but every value in the shader was 0. I tried copy-pasting the "arrayOfInts" example to try and isolate the problem, changing everything to be ints, but I still only get zeros shader-side. According to the documentation ( https://javadoc.lwjgl.org/org/lwjgl/opengl/GL20.html#glUniform1iv(int,int%5B%5D) ), the function glUniform1iv exists and does what I need, but when I try it Eclipse tells me it doesn't exist in the class GL20, both when using an int[] or an IntBuffer, same for glUniform1fv. The location of the uniform variable is 0, therefore it is correctly loaded. The values stored in the java arrays generated are correct.

Vertex Shader:

#version 400 core

in vec3 position;
out vec2 uvPosition;

void main(void){
    gl_Position = vec4(position, 1.0);
    uvPosition = (position.xy+vec2(1.0, 1.0))/2;
}

Fragment shader

#version 400 core

in vec2 uvPosition;
out vec4 outColor;

uniform int random[50];

int randomIterator = 0;

float randf(){
    return random[randomIterator++];
}

void main(void){
    outColor = vec4(random[0]/10, 1.0, 1.0, 1.0);
}

Java code where I load the uniform:

    final int RAND_AMOUNT = 50;
    IntBuffer buffer = BufferUtils.createIntBuffer(RAND_AMOUNT);
    int[] array = new int[RAND_AMOUNT];
    for(int i = 0; i < RAND_AMOUNT; i++) {
        buffer.put((int)(Math.random()*9.999f));
        array[i] = (int)(Math.random()*9.999f);
    }
    buffer.rewind();
    System.out.println(buffer.get(0));
    GL20.glUniform1(glGetUniformLocation(programID, "random"), buffer); //In this line, using GL20.glUniform1iv tells me it doesn't exist. Same with

Nothing throws errors and the display is cyan, meaning the Red component is 0. Any help in making the random ints or directly sending random floats would help. Feel free to ask any question.


Solution

  • glUniform* sets a value of a uniform in the default uniform block of the currently installed program. Thus the program has to be installed by glUseProgram before.

    int random_loc = GL20.glGetUniformLocation(programID, "random")
    
    GL20.glUseProgram(programID);
    GL20.glUniform1(random_loc, buffer);