love.graphics.stencil

Available since LÖVE 0.10.0
This function is not supported in earlier versions.

Draws geometry to the stencil buffer.

The passed function draws to the (invisible) stencil buffer instead of the regular screen. The stencil buffer acts like a mask or stencil – the geometry of everything drawn to the stencil buffer determines whether pixels in the buffer are 'enabled' or not. When the Stencil Test is enabled after love.graphics.stencil is used, everything drawn after that point will be affected by the contents of the stencil buffer.

Note that each Canvas has its own stencil buffer.

Function

Synopsis

love.graphics.stencil( stencilfunction, keepbuffer )

Arguments

function stencilfunction
Function which draws the stencil geometry to the stencil buffer.
boolean keepbuffer (false)
Whether to preserve the previous contents of the stencil buffer. Note that love.graphics.clear will also clear the stencil buffer.

Returns

Nothing.

Examples

Drawing circles masked by a rectangle

local function myStencilFunction()
   love.graphics.rectangle("fill", 225, 200, 350, 300)
end

function love.draw()
    -- draw a rectangle to the stencil buffer
    love.graphics.stencil(myStencilFunction)

    -- enable testing against the contents of the stencil buffer
    love.graphics.setStencilTest(true)

    love.graphics.setColor(255, 0, 0, 120)
    love.graphics.circle("fill", 300, 300, 150, 50)

    love.graphics.setColor(0, 255, 0, 120)
    love.graphics.circle("fill", 500, 300, 150, 50)

    love.graphics.setColor(0, 0, 255, 120)
    love.graphics.circle("fill", 400, 400, 150, 50)

    love.graphics.setStencilTest(false)
end

Using an Image as a stencil mask

-- a black/white mask image: black pixels will mask, white pixels will pass.
local mask = love.graphics.newImage("mymask.png")

local mask_shader = love.graphics.newShader[[
   vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords) {
      if (Texel(texture, texture_coords).rgb == vec3(0.0)) {
         // a discarded pixel wont be applied as the stencil.
         discard;
      }
      return vec4(1.0);
   }
]]

local function myStencilFunction()
   love.graphics.setShader(mask_shader)
   love.graphics.draw(mask, 0, 0)
   love.graphics.setShader()
end

function love.draw()
    love.graphics.stencil(myStencilFunction)
    love.graphics.setStencilTest(true)
    love.graphics.rectangle("fill", 0, 0, 256, 256)
    love.graphics.setStencilTest(false)
end

The love.graphics.setStencilTest wiki page includes more examples.

See Also


Other Languages