]> gerrit.simantics Code Review - simantics/district.git/blobdiff - org.simantics.district.network/src/org/simantics/district/network/profile/Colors.java
First prototype of HSV color space based dynamic DN element coloring
[simantics/district.git] / org.simantics.district.network / src / org / simantics / district / network / profile / Colors.java
diff --git a/org.simantics.district.network/src/org/simantics/district/network/profile/Colors.java b/org.simantics.district.network/src/org/simantics/district/network/profile/Colors.java
new file mode 100644 (file)
index 0000000..9ead5c3
--- /dev/null
@@ -0,0 +1,55 @@
+package org.simantics.district.network.profile;
+
+import java.awt.Color;
+
+/**
+ * @author Tuukka Lehtonen
+ * @since 1.35.0
+ */
+public class Colors {
+
+    private static class Cache implements ColorGradient {
+        private final ColorGradient proxy;
+        private final int discretization;
+        private final Color[] cache;
+
+        public Cache(ColorGradient proxy, int discretization) {
+            this.proxy = proxy;
+            this.discretization = discretization;
+            this.cache = new Color[discretization+1];
+        }
+
+        private int discretize(double t) {
+            return (int) (saturate(t) * discretization);
+        }
+
+        @Override
+        public Color get(double t) {
+            int d = discretize(t);
+            Color cached = cache[d];
+            if (cached != null)
+                return cached;
+            cached = cache[d] = proxy.get(t);
+            return cached;
+        }
+    }
+
+    public static final ColorGradient cached(ColorGradient cg) {
+        return new Cache(cg, 512);
+    }
+
+    public static final ColorGradient hsvGradient(float hue, float saturation) {
+        return t -> {
+            return Color.getHSBColor(hue, saturation, saturate((float) t));
+        };
+    }
+
+    private static float saturate(float t) {
+        return Math.max(0f, Math.min(t, 1f));
+    }
+
+    private static double saturate(double t) {
+        return Math.max(0, Math.min(t, 1));
+    }
+
+}