Wiki

Clone wiki

Core / BlendImagesShader

Back to Built-in Shader Packs


Blend Images Shader

Introduction

'Blend Images' is an example shader provided in Codea's 'Basic' Shaders Pack.

Vertex shader

The vertex shader is very simple indeed, passing colour and texture coordinates to the fragment shader:

void main()
{
    ...
    vColor = color;
    vTexCoord = texCoord;
    ...
    gl_Position = modelViewProjection * position;
}

gl_Position is a variable that is intended for outputting the vertex position in homogenous co-ordinates (that is, as a vec4 value). All vertex shaders must write a value into that variable. (See Section 7.1 'Vertex Shader Special Variables' of the GLSL ES specification.) Here, the modelViewProjection 4x4 matrix is applied to the vertex's position. modelViewProjection is a 'uniform' mat4 variable supplied automatically by Codea when the shader is used with a mesh. It is the current model matrix * view matrix * projection matrix. position is a vec4 'attribute' variable, also supplied automatically by Codea from the mesh.

Fragment shader

The fragment shader makes use of two 'uniform' variables in addition to the texture 'uniform' variable supplied automatically by Codea when the shader is used with a mesh:

uniform lowp sampler2D texture;  // First texture
uniform lowp sampler2D texture2; // Second texture
uniform float mixAmount;         // Used to set in what proportions the colours will be mixed

The main() function samples a colour from each of the textures supplied, using the built-in texture lookup function of GLSL ES (texture2D(). It then uses the built-in mix() function (see Section 8.3 'Common Functions' of the GLSL ES specification) to mix the two colours in the proportions established by mixAmount. gl_FragColor, which outputs the colour of the fragment, is set to the result of the mixing:

void main()
{
    ...
    lowp vec4 col1 = texture2D(texture, vTexCoord);
    lowp vec4 col2 = texture2D(texture2, vTexCoord);
    ...
    gl_FragColor = mix(col1, col2, mixAmount);
}

Example of use

The code below is a simple example of the use of the shader:

function setup()
    local dim = math.min(WIDTH, HEIGHT)
    parameter.number("mixAmount", 0, 1, 0.5)
    myMesh = mesh()
    myMesh:addRect(WIDTH / 2, HEIGHT / 2, dim, dim)
    myMesh.texture = readImage("Cargo Bot:Codea Icon")
    local texture2 = readImage("Planet Cute:Heart")
    myMesh.shader = shader("Basic:Blend Images")
    myMesh.shader.texture2 = texture2
end

function draw()
    background(0)
    myMesh.shader.mixAmount = mixAmount
    myMesh:draw()
end

Updated