From 41954aff63c9828aadae27f6cb20f7fd0fdb8717 Mon Sep 17 00:00:00 2001 From: Lorenzo Cogotti Date: Fri, 26 Jan 2024 16:23:55 +0100 Subject: [PATCH] [color] Add helper functions for HSV and HSL color conversion --- color.lua | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/color.lua b/color.lua index c75d657..f971dae 100644 --- a/color.lua +++ b/color.lua @@ -38,6 +38,50 @@ function Color.lighten(r, g, b, amount) return r, g, b end +function Color.hsl(h, s, l, a) + a = a or 1 + if s <= 0 then return 1, 1, 1, a end + + h = h * 6 + + local abs = math.abs + local c = (1 - abs(l*2 - 1))*s + local x = (1 - abs(h%2 - 1))*c + local m = l - c*0.5 + + local r, g, b + if h < 1 then r, g, b = c, x, 0 + elseif h < 2 then r, g, b = x, c, 0 + elseif h < 3 then r, g, b = 0, c, x + elseif h < 4 then r, g, b = 0, x, c + elseif h < 5 then r, g, b = x, 0, c + else r, g, b = c, 0, x + end + return r+m, g+m, b+m, a +end + +function Color.hsv(h, s, v, a) + a = a or 1 + if s <= 0 then return v, v, v, a end + + h = h * 6 + + local c = v * s + local x = (1 - math.abs(h%2 - 1))*c + local m = v - c + + local r, g, b + if h < 1 then r, g, b = c, x, 0 + elseif h < 2 then r, g, b = x, c, 0 + elseif h < 3 then r, g, b = 0, c, x + elseif h < 4 then r, g, b = 0, x, c + elseif h < 5 then r, g, b = x, 0, c + else r, g, b = c, 0, x + end + return r+m, g+m, b+m, a + +end + --- Given two RGB colors, calculate fade by the specified amount. -- -- @number cr first color, red channel