First, add target color
Above, we mainly used GLSL to fill the texture on one pixel. Here we further add a texture blend for the pixel.
A necessary condition for texture blending is that the source color must be transparent, otherwise the target color will be overwritten directly. So we first add a color for the pixel itself, and then adjust the opacity of the texture color to mix it.
First add vertex color to vertex data:
GLfloat attrArr[] = {// vertex vertex color texture coordinates -0.5f, 0.5f, 0.0f, 1,0,0, 0.0f, 1.0f,// upper left 0 0.5f, 0.5f, 0.0f, 0,1,0, 1.0f, 1.0 f, 1-0.5 f / / right, 0.5 f, f 0.0, 0, 1, 0.0 f, f, 0.0 0.5 f / / lower left 2, 0.5 f, f 0.0, 1, 1, 1.0 f, 1.0 f, / / lower 3 0.0 f, f 0.0, 1.0, f 0,1,1, 1.0f, 0.0f// vertex 4};Copy the code
Add an additional attribute to the vertex shader to receive the vertex color, and add a VARYING attribute to pass the vertex color to the slice shader:
attribute vec4 position; // Attribute vec4 positionColor; // Vertex color attribute vec2 textCoordinate; // Texture coordinates varying lowp VEC2 varyTextCoord; // The texture coordinates are passed to the element varying LOWP VEC4 varyColor; Uniform mat4 projectionMatrix; // Uniform mat4 modelViewMatrix; Void main() {varyTextCoord = textCoordinate; varyColor = positionColor; gl_Position = projectionMatrix * modelViewMatrix * position; //m v p }Copy the code
Next we need to turn on the vertex color channel in our drawing:
- (void)renderLayer { //... // GLuint pisitionColor = glGetAttribLocation(self.myame, "positionColor"); glEnableVertexAttribArray(pisitionColor); glVertexAttribPointer(pisitionColor, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 8, (GLfloat *)NULL+3); / /... Omit}Copy the code
Note that because of the new vertex colors in the vertex data, the step size should be 8 instead of 6, and the step size of the vertex data channel and texture data channel should be 8.
Two, start the color mix
Next, we need to do a transparent treatment for the source color, the texture color:
precision highp float; varying lowp vec2 varyTextCoord; // The passed texture coordinates varying lowp VEC4 varyColor; Uniform sampler2D colorMap; Vec4 weakMask = texture2D(colorMap, varyTextCoord); Vec4 mask = varyColor; // Vertex color float alpha = 0.3; // Opacity vec4 tempColor = mask * (1.0-alpha) + weakMask * alpha; Cf = (Cs * S) + (Cd * D) gl_FragColor = tempColor; // The blended color is submitted to the vertex shader}Copy the code
The final effect is as follows: