--
--	rastergraphics: raster graphics primitives
--	Copyright (C) 2007  Adam Sampson <ats@offog.org>
--
--	This library is free software; you can redistribute it and/or
--	modify it under the terms of the GNU Lesser General Public
--	License as published by the Free Software Foundation, either
--	version 2 of the License, or (at your option) any later version.
--
--	This library is distributed in the hope that it will be useful,
--	but WITHOUT ANY WARRANTY; without even the implied warranty of
--	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
--	Lesser General Public License for more details.
--
--	You should have received a copy of the GNU Lesser General Public
--	License along with this library.  If not, see
--	<http://www.gnu.org/licenses/>.
--

--** @module rastergraphics

#INCLUDE "graphics.inc"

--{{{  FUNCTION desaturate.colour
--* Desaturate a colour value.
--
--  This adds [@code amount] to each of the colour's components, capping them at
--  [@code #FF].
-- 
--  @param colour Colour
--  @param amount Amount to add
--  @return The new colour

INT FUNCTION desaturate.colour (VAL INT colour, amount)
  INT FUNCTION d (VAL INT bits)
    INT v:
    VALOF
      SEQ
        v := ((colour >> bits) /\ #FF) + amount
        IF
          v > #FF
            v := #FF
          TRUE
            SKIP
      RESULT v << bits
  :
  VALOF
    SKIP
    RESULT (d (16) \/ d (8)) \/ d (0)
:
--}}}

--{{{  INT FUNCTION hsv.to.rgb
--* Convert a colour from HSV to RGB.
--
-- The HSV colourspace specifies colour shades in terms of hue (basic colour),
-- saturation and value (brightness), each a real value between 0 and 1.
-- It's useful if you want to turn a continuous range of values into a smooth
-- series of colours: fix the saturation and value and vary the hue.
--
-- This is an implementation of [@link
-- http://www.cs.rit.edu/~ncs/color/t_convert.html N.  Schaller's algorithm].
--
-- @param h Hue
-- @param s Saturation
-- @param v Value
-- @return [@code #rrggbb]

INT FUNCTION hsv.to.rgb (VAL REAL32 h, s, v)
  REAL32 r, g, b:
  VALOF
    IF
      s = 0.0
        r, g, b := v, v, v
      TRUE
        INT i:
        REAL32 hh, f, p, q, t:
        SEQ
          hh := h * 6.0
          i := INT TRUNC hh
          f := hh - (REAL32 ROUND i)
          p := v * (1.0 - s)
          q := v * (1.0 - (s * f))
          t := v * (1.0 - (s * (1.0 - f)))
          CASE i
            0
              r, g, b := v, t, p
            1
              r, g, b := q, v, p
            2
              r, g, b := p, v, t
            3
              r, g, b := p, q, v
            4
              r, g, b := t, p, v
            ELSE
              r, g, b := v, p, q
    RESULT pack.colour.float (r, g, b)
:
--}}}
