epervier-old/birb/modules/gui/elements/canvas.lua
2022-07-27 21:57:34 +02:00

96 lines
No EOL
2.5 KiB
Lua

local Parent = require "birb.modules.gui.elements.parent"
local CanvasElement = Parent:extend()
function CanvasElement:new(name, x, y, w, h, r,sx,sy,ox,oy, opacity)
self:initCanvas()
CanvasElement.super.new(self, name, x, y, w, h)
self.r = r or 0
self.sx, self.sy = sx or 1, sy or 1
self.ox, self.oy = self:parseOrigin(ox, w), self:parseOrigin(oy, h)
self.opacity = opacity or 1
end
function CanvasElement:initCanvas()
self.canvas = {}
self.canvas.needRedraw = true
self.canvas.texture = nil
self.canvas.isAnimated = false
self.canvas.padding = 8
self.canvas.final = nil
self.canvas.dual = false
end
function CanvasElement:updateElement(dt)
CanvasElement.super.updateElement(self, dt)
end
function CanvasElement:getCanvasDimensions()
return self:getDimensions()
end
function CanvasElement:redraw()
if (self.canvas.needRedraw or self.canvas.isAnimated) then
self:generateTexture()
end
if (self.canvas.dual) then
local w, h = self:getDimensions()
local canvas = love.graphics.newCanvas(w + (self.canvas.padding*2), h + (self.canvas.padding*2))
love.graphics.setCanvas(canvas)
love.graphics.draw(self.canvas.texture, 0, 0)
self:drawFinalTexture()
self.canvas.final = canvas
love.graphics.setCanvas()
end
end
function CanvasElement:generateTexture()
local w, h = self:getDimensions()
local canvas = love.graphics.newCanvas(w + (self.canvas.padding*2), h + (self.canvas.padding*2))
love.graphics.setCanvas(canvas)
self:drawTexture()
self.canvas.needRedraw = false
love.graphics.setCanvas()
if (self.canvas.isAnimated) then
self.canvas.texture = canvas
else
local imageData = canvas:newImageData()
self.canvas.texture = love.graphics.newImage(imageData)
canvas:release()
imageData:release()
end
end
function CanvasElement:drawTexture()
end
function CanvasElement:drawFinalTexture()
end
function CanvasElement:parseOrigin(origin, size)
if (origin == "center") then
return size/2
elseif (origin == "end") then
return size
else
return origin or 0
end
end
function CanvasElement:draw()
love.graphics.setColor(1, 1, 1, self.opacity)
local texture = self.canvas.texture
if (self.canvas.dual) then
texture = self.canvas.final
end
love.graphics.draw(texture, self.x - self.canvas.padding,self.y - self.canvas.padding,self.r,self.sx,self.sy,self.ox,self.oy)
love.graphics.setColor(1, 1, 1, 1)
end
return CanvasElement