Sprite sheet shader

A shader that displays one section of a uniformly spaced grid sprite sheet.


--# Main
-- Animation Shader

-- Use this function to perform your initial setup
function setup()
    m=mesh()
    m.shader=shader(spritesheetshader.vertex,spritesheetshader.fragment)
    m:addRect(WIDTH/2,HEIGHT/2,400,600,0)
    img=http.request(
    "http://www.sjamediaarts.com/uploads/3/5/0/5/3505548/7927282_orig.jpg",
    function(data,status,headers)img=data end,
    function(e) print("error:"..e) end)
end

-- This function gets called once every frame
function draw()
    background(0)
    if img then
        m.shader.texture=img
        m.shader.columns=10
        m.shader.rows=1
        m.shader.x=math.fmod(math.floor(ElapsedTime*10),10)
        m.shader.y=1
        m:draw()
    end
end



--# Shader
spritesheetshader={
vertex=[[
uniform mat4 modelViewProjection;
attribute vec4 position;
attribute vec4 color;
attribute vec2 texCoord;
varying lowp vec4 vColor;
varying highp vec2 vTexCoord;
void main()
{
    vColor = color;
    vTexCoord = texCoord;
    gl_Position = modelViewProjection * position;
}
]]
,
fragment=[[

precision highp float;

uniform lowp sampler2D texture;
uniform lowp float columns;
uniform lowp float rows;
uniform lowp float x;
uniform lowp float y;

varying lowp vec4 vColor;

varying highp vec2 vTexCoord;

void main()
{
    vec2 pos=vec2(x,y);
    
    // the position of the bottom left corner of the current frame
vec2 framePos=vec2(1./columns*(pos.x-1.),1./rows*(pos.y-1.));
    
    // the width and height of the current frame
vec2 frameSize=vec2(1./columns,1./rows);
    
vec2 tCoord=vec2(framePos.x+frameSize.x*vTexCoord.x,
                framePos.y+frameSize.y*vTexCoord.y);
    
    //Sample the texture at the interpolated coordinate
    lowp vec4 col = texture2D( texture, tCoord ) * vColor;

    gl_FragColor = col;
}
]]
}