evil-jrpg/atlas.lua

65 lines
1.5 KiB
Lua

local Math = require "math"
local Object = require "lib/classic"
---@class Atlas
---A spriteset laid out on a regular grid.
local Atlas = Object:extend()
---Creates a new atlas.
---@param image love.Image The source image for the atlas.
---@param sw integer The width of each sprite.
---@param sh integer The height of each sprite.
function Atlas:new(image, sw, sh)
---The source image of the atlas.
self.image = image
---The width of each atlas's sprite.
self.sw = sw
---The height of each atlas's sprite.
self.sh = sh
---The width of the atlas in texels.
self.iw = image:getPixelWidth()
---The height of the atlas in texels.
self.ih = image:getPixelHeight()
---The width of the atlas in sprites.
self.w = Math.floor(self.iw / sw)
---The height of the atlas in sprites.
self.h = Math.floor(self.ih / sh)
---The total number of sprites.
self.num = self.w * self.h
---A drawable mesh for each sprite.
self.meshes = {}
for row = 1, self.h do
for col = 1, self.w do
--UV texture coordinates
local l = (col - 1) * sw / self.iw
local t = (row - 1) * sh / self.ih
local r = col * sw / self.iw
local b = row * sh / self.ih
--Vertex data
local vertices = {
{ 0, 0, l, t },
{ sw, 0, r, t },
{ 0, sh, l, b },
{ sw, sh, r, b }
}
--Create and push the mesh
local mesh = love.graphics.newMesh(vertices, "strip", "static")
mesh:setTexture(self.image)
self.meshes[#self.meshes + 1] = mesh
end
end
end
return Atlas