I want to write one vertex shader to work with colors and textures I used this code
precision mediump float;
varying vec4 v_Color;
uniform sampler2D u_TextureUnit;
varying vec2 v_TextureCoordinates;
void main() {
gl_FragColor= (v_Color*texture2D(u_TextureUnit, v_TextureCoordinates));
}
it works when the model has a texture map but if the model has only color it loads black, I want to check the sampler2D u_TextureUnit
before putting gl_FragColor
You have written a shader that reads from a texture unit; you should generally avoid conditionality in shaders as it potentially splits the execution path. Usually a compiler can figure it out if the thing you're acting conditionally upon is a uniform but you may end up paying for a recompile every time you set the uniform. ES 2 has no means of introspecting the current properties of a sampling unit so the prima facie solution might be something like:
uniform bool u_ApplyTexture;
...
if(u_ApplyTexture)
gl_FragColor = {what you already have};
else
gl_FragColor = v_Color;
A non-conditional alternative possibly to profile as an alternative might be:
uniform float u_TextureWeight;
...
gl_FragColor = v_Color*
mix(vec4(1.0),
texture2D(u_TextureUnit, v_TextureCoordinates),
u_TextureWeight);
As that would evaluate to v_Color*vec4(1.0)
when u_TextureWeight
is 0.0
and v_Color*texture2D(u_TextureUnit, v_TextureCoordinates)
when u_TextureWeight
is 1.0
.
If you were really looking to be hacky, you might just upload your textures as negative images and negative them again in the shader:
gl_FragColor = v_Color*(vec4(1.0) - texture2D(u_TextureUnit, v_TextureCoordinates));
As then obviously if you're getting vec4(0.0)
from the sampling unit because no texture is attached, that ends up multiplying v_Color
by 1.0
.