99 lines
2.3 KiB
Lua
99 lines
2.3 KiB
Lua
lzr_util = {}
|
|
|
|
local max_value = 255
|
|
|
|
-- Convert a 6-character color hexcode string in format RRGGBB
|
|
-- to 3 numbers red, green, blue.
|
|
lzr_util.hexcode_to_rgb = function(hexcode)
|
|
if not hexcode or string.len(hexcode) ~= 6 then
|
|
return
|
|
end
|
|
local rhex = string.sub(hexcode, 1, 2)
|
|
local ghex = string.sub(hexcode, 3, 4)
|
|
local bhex = string.sub(hexcode, 5, 6)
|
|
local r = tonumber(rhex, 16)
|
|
local g = tonumber(ghex, 16)
|
|
local b = tonumber(bhex, 16)
|
|
if r and g and b then
|
|
r = math.min(255, math.max(0, r))
|
|
g = math.min(255, math.max(0, g))
|
|
b = math.min(255, math.max(0, b))
|
|
return r, g, b
|
|
end
|
|
end
|
|
|
|
-- Convert 3 numbers for red, green and blue (0-255 each)
|
|
-- to a hexadecical code of length 6 in format RRGGBB.
|
|
lzr_util.rgb_to_hexcode = function(r, g, b)
|
|
return string.format("%02X%02X%02X", r, g, b)
|
|
end
|
|
|
|
-- Converts RGB values (0..255 each) to HSV values (0..1 each)
|
|
lzr_util.rgb_to_hsv = function(r, g, b)
|
|
r = r / max_value
|
|
g = g / max_value
|
|
b = b / max_value
|
|
|
|
local max = math.max(r, g, b)
|
|
local min = math.min(r, g, b)
|
|
local h, s, v = 0, 0, (max + min) / 2
|
|
|
|
local d = max - min
|
|
v = max
|
|
s = max == 0 and 0 or d / max
|
|
|
|
if max ~= min then
|
|
if max == r then
|
|
h = (g - b) / d + (g < b and 6 or 0)
|
|
elseif max == g then
|
|
h = (b - r) / d + 2
|
|
elseif max == b then
|
|
h = (r - g) / d + 4
|
|
end
|
|
h = h / 6
|
|
end
|
|
return h, s, v
|
|
end
|
|
|
|
-- Converts HSV values (0..1 each) to RGB values (0..255 each)
|
|
lzr_util.hsv_to_rgb = function(h, s, v)
|
|
local r, g, b
|
|
|
|
local i = math.floor(h * 6)
|
|
local f = h * 6 - i
|
|
local p = v * (1 - s)
|
|
local q = v * (1 - f * s)
|
|
local t = v * (1 - (1 - f) * s)
|
|
|
|
i = i % 6
|
|
|
|
if i == 0 then
|
|
r, g, b = v, t, p
|
|
elseif i == 1 then
|
|
r, g, b = q, v, p
|
|
elseif i == 2 then
|
|
r, g, b = p, v, t
|
|
elseif i == 3 then
|
|
r, g, b = p, q, v
|
|
elseif i == 4 then
|
|
r, g, b = t, p, v
|
|
elseif i == 5 then
|
|
r, g, b = v, p, q
|
|
end
|
|
|
|
return math.floor(r * max_value), math.floor(g * max_value), math.floor(b * max_value)
|
|
end
|
|
|
|
-- Returns true if the given file exists, false otherwise.
|
|
-- * path: Path to file (without file name)
|
|
-- * filename: File name of file (without path)
|
|
lzr_util.file_exists = function(path, filename)
|
|
local levels = minetest.get_dir_list(path, false)
|
|
for l=1, #levels do
|
|
if levels[l] == filename then
|
|
return true
|
|
end
|
|
end
|
|
return false
|
|
end
|