Pixelize Shader

Here is a shader to pixelize an image (see attached screenshot). At the suggestion of @dave1707, the shader is embedded in code which allows you to change the pixel size (‘resolution’) and view the image with or without the shader applied. The code is free to use as you like. Enjoy!

-- Pixelize Shader

function setup()
    
    parameter.integer("Resolution", 16, 64, 32)
    parameter.boolean("Original", false)
    
    myMesh = mesh()
    local rIdx = myMesh:addRect(0, 0, 0, 0)

    myMesh.texture = "Cargo Bot:Codea Icon"
    meshWidth, meshHeight = spriteSize(myMesh.texture)
    myMesh:setRect(rIdx, 0, 0, meshWidth, meshHeight)

    myMesh.shader = shader(pixelizeShader.vert, pixelizeShader.frag)
    myMesh.shader.resolution = 32.0
    myMesh.shader.size = 1.0
    
end

function draw()
    
    background(0)
    
    if Original then
        pushMatrix()
            translate(WIDTH/2, HEIGHT/2)
            sprite(myMesh.texture)
        popMatrix()
    else
        myMesh.shader.resolution = Resolution
        pushMatrix()
            translate(WIDTH/2, HEIGHT/2)
            myMesh:draw()
        popMatrix()
    end
    
end

pixelizeShader = {
vert = [[
    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;
    }
    ]],

frag = [[    
    precision highp float;
    
    uniform lowp sampler2D texture;
    
    varying lowp vec4 vColor;
    varying highp vec2 vTexCoord;
    
    uniform highp float resolution;
    uniform highp float size;
    
    void main()
    {
     float dx = size*(1.0/resolution);
     float dy = size*(1.0/resolution);
     vec2 coord = vec2(dx*floor(vTexCoord.x/dx), dy*floor(vTexCoord.y/dy));

     gl_FragColor = texture2D(texture, coord);
    }
    ]]
}

Nice job. Another shader for all to study. It’s also nice to have all the code to execute.

Add to example shaders pls

I love it!

Question: Why doesn’t it work with CAMERA?

@TokOut Replace the draw function with the code below and it will work with camera.

function draw()
    background(0)
    if Original then
        pushMatrix()
        translate(WIDTH/2, HEIGHT/2)
        sprite(myMesh.texture)
        popMatrix()
    else
        myMesh.texture = image(CAMERA)
        collectgarbage()
        myMesh.shader.resolution = Resolution
        pushMatrix()
        translate(WIDTH/2, HEIGHT/2)
        myMesh:draw()
        popMatrix()
    end
end

Thanks @dave1707! @TokOut I was thinking of adding a parameter so the user could cycle through different images, and I could also include the camera as an option for future shader examples. @UberGoober glad you like it! I’m learning about shaders by translating different Shadertoy.com examples into Codea, so there may be more coming.