1 package kaka.cakelight;
4 private static int[] gammaCorrection = new int[256];
6 public static void calculateGammaCorrection(double gamma) {
7 for (int i = 0, max = 255; i <= max; i++) {
8 gammaCorrection[i] = (int)(Math.pow((double)i / max, gamma) * max);
14 public static Color rgb(double r, double g, double b) {
15 return rgb((int)(255 * r), (int)(255 * g), (int)(255 * b));
18 public static Color rgb(int r, int g, int b) {
19 Color c = new Color();
27 * @param hue 0.0 - 1.0
28 * @param saturation 0.0 - 1.0
29 * @param value 0.0 - 1.0
31 public static Color hsv(double hue, double saturation, double value) {
32 double normalizedHue = hue - Math.floor(hue);
33 int h = (int)(normalizedHue * 6);
34 double f = normalizedHue * 6 - h;
35 double p = value * (1 - saturation);
36 double q = value * (1 - f * saturation);
37 double t = value * (1 - (1 - f) * saturation);
40 case 0: return rgb(value, t, p);
41 case 1: return rgb(q, value, p);
42 case 2: return rgb(p, value, t);
43 case 3: return rgb(p, q, value);
44 case 4: return rgb(t, p, value);
45 case 5: return rgb(value, p, q);
46 default: throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + hue + ", " + saturation + ", " + value);
50 public double[] toHSV() {
51 return toHSV(r / 255.0, g / 255.0, b / 255.0);
55 * @return an array with hsv values ranging from 0.0 to 1.0
57 public static double[] toHSV(double r, double g, double b) {
59 double min = Math.min(Math.min(r, g), b);
60 double max = Math.max(Math.max(r, g), b);
63 return new double[] {0, 0, 0};
70 double delta = max - min;
75 h = (g - b) / delta; // between yellow & magenta
76 } else if (g == max) {
77 h = 2 + (b - r) / delta; // between cyan & yellow
79 h = 4 + (r - g) / delta; // between magenta & cyan
86 return new double[] {h, s, v};
90 return gammaCorrection[r];
94 return gammaCorrection[g];
98 return gammaCorrection[b];
101 public Color interpolate(Color other, double value) {
102 double invertedValue = 1 - value;
104 (int)(r * invertedValue + other.r * value),
105 (int)(g * invertedValue + other.g * value),
106 (int)(b * invertedValue + other.b * value)