Hey guys, I started on fragment shaders today and I’ve come up with an efficient solution to something was trying to achieve using image:set(), its a spray can, as you guessed by the title!
Have a look:
--# Main
--Spray demo
function setup()
m = {}
txtre = image(30,30)
setContext(txtre)
pushStyle()
for i=1,15 do
fill(255,255/10)
ellipse(15,15,i*2)
end
popStyle()
setContext()
msh = mesh()
msh.texture = txtre
rsh = msh:addRect(1,1,1,1)
msh.shader = shader(shadr.vS,shadr.fS)
msh.shader.depth = 0.2
img = image(WIDTH,HEIGHT)
parameter.color("colour",color(255,255,255))
parameter.integer("width",10,150,30)
end
function touched(t)
setContext(img)
msh:setRect(rsh,t.x,t.y,width,width)
msh.shader.random = math.random(100,400)/100
msh:setColors(colour)
msh:draw()
setContext()
end
function draw()
background(255, 255, 255, 255)
sprite(img,WIDTH/2,HEIGHT/2,WIDTH,HEIGHT)
end
--# SprayShader
shadr = {
vS = [[
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;
}
]],
fS = [[
precision highp float;
uniform lowp sampler2D texture;
varying lowp vec4 vColor;
uniform highp float random;
uniform highp float depth;
varying highp vec2 vTexCoord;
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(13.0,79.0))) * 40000.0);
}
void main()
{
//Sample the texture at the interpolated coordinate
highp vec2 tc = vTexCoord.xy;
vec2 dir = 0.5 - tc;
float dist = sqrt(dir.x*dir.x + dir.y*dir.y);
dist = (0.5-dist);
lowp vec4 col = texture2D( texture, tc ) * vColor;
if (rand(tc*random) > depth) discard;
col = vec4(col.rgb,dist);
//Set the output color to the texture color
gl_FragColor = col;
}
]]}