sonic-bluestreak/sonic-radiance.love/core/modules/assets/tileset.lua

90 lines
2.9 KiB
Lua
Raw Normal View History

2019-02-03 19:40:28 +01:00
-- assets/tileset :: tileset are automatic breakage of texture into quads. they
-- have the adventage of being automatized, reducing the ammount of code needed
-- to create quads.
-- They have two manners to be draw: with their quad id (in 1D) or by using their
-- place in the grid, in 2D.
--[[
Copyright © 2019 Kazhnuz
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local Tileset = Object:extend()
function Tileset:new(filepath)
self.texture = love.graphics.newImage(filepath .. ".png")
local data = require(filepath)
self.metadata = data.metadata
self:createQuads()
end
function Tileset:createGrid()
self.textureWidth, self.textureHeight = self.texture:getDimensions()
self.width, self.height = self.metadata.width, self.metadata.height
self.gridWidth, self.gridHeight = math.floor(self.textureWidth / self.width),
math.floor(self.textureHeight / self.height)
end
function Tileset:createQuads()
self.quads = {}
self:createGrid()
local quad, n
n = 1
for i=0, (self.gridHeight-1) do
for j=0, (self.gridWidth-1) do
quad = love.graphics.newQuad(j * self.width, i * self.height, self.width, self.height, self.textureWidth, self.textureHeight)
self.quads[n] = quad
n = n + 1
end
end
end
function Tileset:getTileID_Grid(x, y)
local n = (y - 1) * self.gridWidth + x
return n
end
function Tileset:getTile_Grid(x, y)
return self:getTile(self:getTileID_Grid(x, y))
end
function Tileset:getTile(n)
return self.quads[n]
end
function Tileset:drawTile_Grid(i, j, x, y, r, sx, sy, ox, oy, kx, ky)
local tileID = self:getTileID_Grid(i, j)
love.graphics.draw(self.texture, self.quads[tileID], x, y, r, sx, sy, ox, oy, kx, ky)
end
function Tileset:drawTile(id, x, y, r, sx, sy, ox, oy, kx, ky)
love.graphics.draw(self.texture, self.quads[id], x, y, r, sx, sy, ox, oy, kx, ky)
end
return Tileset