Wiki
Clone wikiCore / InvertShader
Invert Shader
Introduction
'Invert' is an example shader provided in Codea's 'Basic' Shaders Pack.
Vertex shader
The vertex shader is very simple indeed, passing the per-vertex colour and texture coordinates on 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 the texture
'uniform' variable supplied automatically by Codea when the shader is used with a mesh:
uniform lowp sampler2D texture;
The main()
function samples a colour from the texture supplied, using the built-in texture lookup function of GLSL ES (texture2D()
), and tints it by multiplying it by vColor
. vColor
is the 'varying' variable passed on from the accompanying vertex shader.
The result is stored in variable col
(declared as a vec4
within the scope of the main()
function).
The code then inverts the red, green and blue channels (1.0 - col.rgb
) and multiplies the result by the alpha (opacity) channel (col.a
). The second step is done so that the result is a colour in a premultiplied format. gl_FragColor
, which outputs the colour of the fragment, is set to the result:
void main()
{
...
lowp vec4 col1 = texture2D(texture, vTexCoord) * vColor;
...
gl_FragColor = vec4((1.0 - col.rgb) * col.a, col.a);
}
In the final line above, the vec4()
constructor has two parameters: the first is of type vec3
and the second is of type float
(see Section 5.4.2 'Vector and Matrix Constructors' of the GLSL ES specification). col.rgb
is of type vec3
and is made up of the r
, g
and b
components of the variable col
(which is of type vec4
). col.a
is of type float
and is the a
component of col
. (See Section 5.5 'Vector Components' of the GLSL ES specification.)
Example of use
The code below is a simple example of the use of the shader:
function setup()
local dim = math.min(WIDTH, HEIGHT)
myMesh = mesh()
myMesh:addRect(WIDTH / 2, HEIGHT / 2, dim, dim)
myMesh.texture = readImage("Cargo Bot:Codea Icon")
myMesh.shader = shader("Basic:Invert")
end
function draw()
background(0)
myMesh:draw()
end
Updated