{-# LANGUAGE BlockArguments #-}module Geomancy.Color.Hue ( hue , fromHSV , toHSV , fromHSL , toHSL ) whereimport Geomancy.Gl.Funs (glFract, glMix, glSaturate)import Geomancy.Vec3 (Vec3, vec3, withVec3, (^*)){-# INLINE hue #-}hue :: Float -> Vec3hue turns = glSaturate (abs (glFract (vec3 turns (turns + 2 / 3) (turns + 1 / 3)) * 6 - 3) - 1){-# INLINE fromHSV #-}fromHSV :: Vec3 -> Vec3fromHSV hsv = withVec3 hsv \h s v -> glMix 1 (hue h) s ^* v{-# INLINE toHSV #-}toHSV :: Vec3 -> Vec3toHSV rgb = withHue rgb \h hi lo -> vec3 h (if hi == 0 then 0 else (hi - lo) / hi) hi{-# INLINE fromHSL #-}fromHSL :: Vec3 -> Vec3fromHSL hsl = withVec3 hsl \h s l -> vec3 l l l + (hue h - 0.5) ^* (2 * s * min l (1 - l)){-# INLINE toHSL #-}toHSL :: Vec3 -> Vec3toHSL rgb = withHue rgb \h hi lo -> let l = (hi + lo) / 2 headroom = min l (1 - l) in vec3 h (if headroom == 0 then 0 else (hi - l) / headroom) l{-# INLINE withHue #-}withHue :: Vec3 -> (Float -> Float -> Float -> r) -> rwithHue rgb f = withVec3 rgb \r g b -> let hi = max r (max g b) lo = min r (min g b) chroma = hi - lo sector | chroma == 0 = 0 | hi == r = (g - b) / chroma | hi == g = 2 + (b - r) / chroma | otherwise = 4 + (r - g) / chroma in f (wrapTurns (sector / 6)) hi lo{-# INLINE wrapTurns #-}wrapTurns :: Float -> FloatwrapTurns x = let turns = glFract x in if turns >= 1 then 0 else turns