简体   繁体   中英

Passing one float from the vertex shader to the fragment shader

Currently I'm passing one float from the vertex shader :

varying float fog_factor;
...
fog_factor = clamp(gl_Position.z, 0.0, 1.0);
...

To the fragment shader :

varying float fog_factor;
...
gl_FragColor = texture2D(sampler_texture_4, ...) * fog_factor;
...

My question, is there something I need to add in the java code ? When passing an array of float I need to add something like this :

vertex_position_handle = GLES20.glGetAttribLocation(program, "vertex_position");
GLES20.glEnableVertexAttribArray(vertex_position_handle);
GLES20.glVertexAttribPointer(vertex_position_handle, 3, GLES20.GL_FLOAT, false, 3 * 4, vertex_buffer);

For now I'm only doing this in my java code for my float :

fog_handle = GLES20.glGetAttribLocation(program, "fog_factor");

I'm asking this because this code is working on my device, but crash on others...

Well, the issue is that fog_factor is a varying. While this will pass information from the vertex to the fragment shader, you don't have access to it from client (java) code. If you want to send information into the shader you need either an attribute or a uniform variable.

attributes can change per vertex, while uniforms stay the same for each set of vertices (glDrawElements call)

What I frequently do in the vertex shader is this:

  attribute vec2 clientTexCoord;
  varying vec2 texCoord;  

  main(){
        ... // other code
        texCoord = clientTexCoord;
        ... // other code
  }

and in the client/java code get the attribute location for clientTexCoord as you are doing correctly. It's incredible this works correctly right now but i've seen some GLSL compilers be a little less picky than others.

Try modifying your vertex shader to allow for an attribute to be passed in to set the value for the varying fog_factor you have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM