summaryrefslogtreecommitdiff
path: root/honey/image.lua
blob: f0742726889b6ab6cba7b3cb3e29b397ca121ed4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
local gl = honey.gl

local module = {}
setmetatable(module, {__index=_G})
setfenv(1, module)

function Image(filename, params)
	local params = params or {}
	local data, width, height = honey.image.load(filename, 4)
	local self = {}
	self.width = width
	self.height = height

	self.texture = gl.GenTextures()
	gl.BindTexture(gl.TEXTURE_2D, self.texture)
	for param, value in pairs(params) do
		gl.TexParameteri(gl.TEXTURE_2D, gl[param], value)
	end
	gl.TexImage2D(
		gl.TEXTURE_2D, 0,
		gl.RGBA, width, height,
		gl.RGBA, gl.UNSIGNED_BYTE, data
	)
	gl.GenerateMipmap(gl.TEXTURE_2D)
	honey.image.destroy(data)

	self.__gc = honey.util.gc_canary(function()
		gl.DeleteTextures(self.texture)
	end)

	return self
end


local cache = {}
function loadImage(filename, params)
	if not cache[filename] then
		local img = Image(filename, params)
		cache[filename] = img
		return img
	end

	return cache[filename]
end

function clearImageCache()
	cache = {}
end

return module