evil-jrpg/atlas.lua

84 lines
2.2 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_path string The path to the source image for the atlas.
---@param sw integer The width of each sprite.
---@param sh integer The height of each sprite.
---@param ax integer? The anchor X coordinate of each sprite. Defaults to 0.
---@param ay integer? The anchor Y coordinate of each sprite. Defaults to 0.
function Atlas:new(image_path, sw, sh, ax, ay)
local image = love.graphics.newImage(image_path)
---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 anchor X coordinate of each sprite.
self.ax = ax or 0
---The anchor Y coordinate of each sprite.
self.ay = ay or 0
---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
---Draws a sprite at a given location.
---@param sprite integer The index of the sprite to draw.
---@param x integer The X coordinate to draw at.
---@param y integer The Y coordinate to draw at.
function Atlas:draw(sprite, x, y)
local mesh = self.meshes[sprite]
love.graphics.draw(mesh, x - self.ax, y - self.ay)
end
return Atlas