knucklebones/utils/rendering.lua

98 lines
2.7 KiB
Lua
Raw Permalink Normal View History

2023-08-12 11:36:14 +02:00
function draw9box(corner, edge, x, y, width, height)
-- edges
for i = 8, width - 9, 8 do
spr(edge, x + i, y, 0) -- top
spr(edge, x + i, y + height - 8, 0, 1, 0, 2) -- bottom
end
for i = 8, height - 8,8 do
spr(edge, x, y + i, 0, 1, 0, 3) -- left
spr(edge, x + width - 8, y + i, 0, 1, 0, 1) -- right
end
-- corners
spr(corner, x, y, 0) -- top left
spr(corner, x + width - 8, y, 0, 1, 0, 1) -- top right
spr(corner, x, y + height - 8, 0, 1, 0, 3) -- bottom left
spr(corner, x + width - 8, y + height - 8, 0, 1, 0, 2) -- bottom right
end
local function rot(x, y, rad)
local sa = math.sin(rad)
local ca = math.cos(rad)
return x * ca - y * sa, x * sa + y * ca
end
--- Draw a sprite using two textured triangles.
--- Apply affine transformations: scale, shear, rotate, flip
--- https://cxong.github.io/tic-80-examples/affine-sprites
---comment
---@param id number
---@param x number
---@param y number
---@param colorkey? number
---@param sx? number scale x
---@param sy? number scale y
---@param flip? number
---@param rotate? number
---@param w? number
---@param h? number
---@param ox? number
---@param oy? number
---@param shx1? number
---@param shy1? number
---@param shx2? number
---@param shy2? number
function aspr(
id, x, y, colorkey, sx, sy, flip, rotate, w, h,
ox, oy, shx1, shy1, shx2, shy2
)
colorkey = colorkey or -1
sx = sx or 1
sy = sy or 1
flip = flip or 0
rotate = math.rad(rotate or 0)
w = w or 1
h = h or 1
ox = ox or w * 8 // 2
oy = oy or h * 8 // 2
shx1 = shx1 or 0
shy1 = shy1 or 0
shx2 = shx2 or 0
shy2 = shy2 or 0
-- scale / flip
if flip % 2 == 1 then
sx = -sx
end
if flip >= 2 then
sy = -sy
end
ox = ox * -sx
oy = oy * -sy
-- shear / rotate
shx1 = shx1 * -sx
shy1 = shy1 * -sy
shx2 = shx2 * -sx
shy2 = shy2 * -sy
local rx1, ry1 = rot(ox + shx1, oy + shy1, rotate)
local rx2, ry2 = rot(((w * 8) * sx) + ox + shx1, oy + shy2, rotate)
local rx3, ry3 = rot(ox + shx2, ((h * 8) * sy) + oy + shy1, rotate)
local rx4, ry4 = rot(((w * 8) * sx) + ox + shx2, ((h * 8) * sy) + oy + shy2, rotate)
local x1 = x + rx1
local y1 = y + ry1
local x2 = x + rx2
local y2 = y + ry2
local x3 = x + rx3
local y3 = y + ry3
local x4 = x + rx4
local y4 = y + ry4
-- UV coords
local u1 = (id % 16) * 8
local v1 = id // 16 * 8
local u2 = u1 + w * 8
local v2 = v1 + h * 8
ttri(x1, y1, x2, y2, x3, y3, u1, v1, u2, v1, u1, v2, 0, colorkey)
ttri(x3, y3, x4, y4, x2, y2, u1, v2, u2, v2, u2, v1, 0, colorkey)
end