package
{
    /// HSVモデルの色をあらわす
    public class HSV
    {
        public var h:Number = 0;    ///< 色相(360max)
        public var s:Number = 0;    ///< 彩度(256max)
        public var v:Number = 0;    ///< 明度(256max)

        /// コンストラクタ
        public function HSV( r:int, g:int, b:int ){
            rgb2hsv(r, g, b);
        }

        /// RGB値をHSVに変換する
        public function rgb2hsv( r:int, g:int, b:int ):void{

            var cmax:Number = Math.max(r,Math.max(g,b));
            var cmin:Number = Math.min(r,Math.min(g,b));
            v = cmax;
            var c:int = cmax - cmin;
            if (cmax == 0){
                s = 0;
                h = 0;
                return;
            }else{
                s = (255*c)/cmax;
            }

            if (s != 0.0){

                var Cr:Number = (cmax - r)/c;
                var Cg:Number = (cmax - g)/c;
                var Cb:Number = (cmax - b)/c;

                if (r == cmax)
                {
                    h = Cb - Cg;
                }else if (g == cmax) {
                    h = 2 + Cr - Cb;
                }else if (b == cmax){
                    h = 4 + Cg - Cr;
                }

                h *= 60;

                if (h < 0.0){
                    h += 360;
                }
            }

        }

        /// RGBに変換
        private function getRGB(r:int, g:int, b:int):uint{
            return ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
        }

        /// hsvをRGBにして返す
        public function getRGBColor():uint{

            if( s == 0 ){
                return getRGB(v, v, v);
            }

            var I:int = Math.floor(h/60);
            var F:int = h/60 - I;
            var M:int = v * (1 - (s/255) );
            var N:int = v * (1 - (s/255)*F);
            var K:int = v * (1 - (s/255)*(1-F));

            switch (I){
            case 0:
                return getRGB(v, K, M);
            case 1:
                return getRGB(N, v, M);
            case 2:
                return getRGB(M, v, K);
            case 3:
                return getRGB(M, N, v);
            case 4:
                return getRGB(K, M, v);
            case 5:
                return getRGB(v, M, N);
            }

            return 0;
        }

    }
}