From 0ff979c42fe06cda49932f5f39c16c3e9b18badc Mon Sep 17 00:00:00 2001 From: mars Date: Sun, 16 Apr 2023 16:30:39 -0400 Subject: [PATCH] Add atlas.lua --- atlas.lua | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ main.lua | 9 ++++++++ 2 files changed, 72 insertions(+) create mode 100644 atlas.lua diff --git a/atlas.lua b/atlas.lua new file mode 100644 index 0000000..09d1713 --- /dev/null +++ b/atlas.lua @@ -0,0 +1,63 @@ +local Math = require "math" +local Object = require "classic" + +---A spriteset laid out on a regular grid. +local Atlas = Object:extend() + +---Creates a new atlas. +---@param image love.Image +---@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 diff --git a/main.lua b/main.lua index d52455a..ba9622e 100644 --- a/main.lua +++ b/main.lua @@ -1,3 +1,5 @@ +local Atlas = require "atlas" + MultiMenu = {} MultiMenu.__index = MultiMenu @@ -65,10 +67,17 @@ end function love.load() Menu = MultiMenu({ "Fight", "Use", "Pkmn", "Flee" }) + + local font = love.graphics.newImage("assets/small-blocky-font.png") + Font = Atlas(font, 8, 8) end function love.draw() Menu:draw() + + for sprite = 1,#Font.meshes do + love.graphics.draw(Font.meshes[sprite], sprite * 10 + 100, 100) + end end function love.keypressed(key)