0
votes

My goal is to slap a texture on a Cube. I'm using webGL 1 on Chrome. My UV coordinates varying doesn't appear to be working properly. It appears as if the values aren't passed to the fragment shader.

Vertex Shader code:

attribute vec3 a_position;
attribute vec2 a_vertexUV;

uniform mat4 u_mvp;

varying vec2 v_uv;

void main() {
    v_uv = a_vertexUV;
    gl_Position = u_mvp * vec4(a_position, 1);
}

Fragment Shader code:

precision mediump float; 

varying vec2 v_uv;

uniform sampler2D u_texSampler;

void main() {
    gl_FragColor = texture2D(u_texSampler, v_uv).bgra;
}

Running my program produces the following:

canvas printscreen

I see my cube, it sources color from the texture, but only uses the color of the first texel for the whole shape. Which suggests my UV vector is empty.

I can confirm this by trying to use the data from my uv vector as a color:

gl_FragColor = vec4(v_uv,0,1);

Which gives me the following:

canvas printscreen #2

A black cube. No values in my UV vector...

The weird thing is that if I use the uv vector in the vertex shader like so:

gl_Position = u_mvp * vec4(v_uv, 0, 1);

Suddenly I get values in my uv vector in the fragment shader, which using as color values produces this:

canvas printscreen #3

Or as Uv coordinates in my texture like so:

gl_FragColor = texture2D(u_texSampler, v_uv).bgra;

Produces the following:

canvas printscreen #4

Which correctly sources color from my texture...

Why does my varying not pass the values to the fragment shader unless it is used in gl_Position?

1
You need to post the code setting up the buffers and attributes for your positions and texcoordsgman

1 Answers

0
votes

I found my mistake.

I'm storing my gl object locations in different arrays such:

webGlBuffers = [];
webGlShaders = [];
webGlPrograms = [];
webGlAttribLocations = [];
webGlUniformLocations = [];
webGlTextures = [];

In my gl.EnableVertexAttribArray calls I was referencing the wrong array. ie: I was calling

gl.EnableVertexAttribArray(webGlShaders[0]);

When I should be calling

gl.EnableVertexAttribArray(webGlAttribLocations[0]);