@texel/color 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -93,9 +93,7 @@ import { gamutMapOKLCH, sRGBGamut, sRGBLinear, OKLCH } from "@texel/color";
93
93
  // gamut map to sRGB but return linear sRGB
94
94
  const lrgb = gamutMapOKLCH(oklch, sRGBGamut, sRGBLinear);
95
95
 
96
- // or gamut map to sRGB but return OKLCH
97
- // note, when finally converting this back to sRGB you will likely
98
- // want to clip the result to 0..1 bounds due to floating point loss
96
+ // or gamut map to sRGB but return OKLCH (does not perform RGB clip)
99
97
  const lch = gamutMapOKLCH(oklch, sRGBGamut, OKLCH);
100
98
  ```
101
99
 
@@ -118,6 +116,8 @@ gamutMapOKLCH(oklch, sRGBGamut, sRGB, rgb, MapToL);
118
116
 
119
117
  The `cusp` can also be passed as the last parameter, allowing for faster evaluation for known hues. See below for calculating the cusp.
120
118
 
119
+ > :Note: If you output to an OKLab-based target (OKLCH, OKHSL etc), the final step of RGB clipping will be skipped. This produces more predictable OKLab and OKLCH based results, but you will likely want to perform a final clampedRGB() step when converting to a displayable color.
120
+
121
121
  #### `LC = findCuspOKLCH(a, b, gamut, out = [0, 0])`
122
122
 
123
123
  Finds the 'cusp' of a given OKLab hue plane (denoted with normalized `a` and `b` values in OKLab space), returning the `[L, C]` (lightness and chroma). This is useful for pre-computing aspects of gamut mapping when you are working across a known hue:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@texel/color",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "a minimal and modern color library",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/gamut.js CHANGED
@@ -288,8 +288,19 @@ export const gamutMapOKLCH = (
288
288
  // convert oklch to base gamut space (i.e. linear sRGB)
289
289
  convert(out, OKLCH, gamutSpaceBase, rgbVec);
290
290
 
291
+ // Note: this is a possible area of performance improvement for some edge cases
292
+ // If you gamut map without clipping, you end up lying on the edge of the gamut,
293
+ // but in some cases very slightly out of gamut. Gamut mapping *again* is redundant
294
+ // as it will produce the same result; and in those cases, it should just skip straight
295
+ // to clipping. So, in theory, a small epsilon like 1e-7 would catch these and prevent redundant gamut mapping.
296
+ // See test/check-gamut-epsilon.js
297
+ // However, in practice, inputs to this function are likely not going to be already-mapped-but-not-clipped points,
298
+ // so we are talking about a very negligible improvement, and it is probably better to be accurate in as many cases
299
+ // as possible than to shave off a little time.
300
+ const RGB_CLIP_EPSILON = 0;
301
+
291
302
  // check where the point lies in gamut space
292
- if (!isRGBInGamut(rgbVec, 0)) {
303
+ if (!isRGBInGamut(rgbVec, RGB_CLIP_EPSILON)) {
293
304
  // we aren't in gamut, so let's map toward it
294
305
  const L = out[0];
295
306
  const C = out[1];
@@ -314,17 +325,20 @@ export const gamutMapOKLCH = (
314
325
  out[0] = lerp(LTarget, L, t);
315
326
  out[1] *= t;
316
327
 
317
- // special case: if requested targetSpace is base=OKLCH, we can return early.
318
- // note this creates a potential difference compared to other targetSpaces, which
319
- // will be clipped in RGB before converting to the target space.
320
- // however, due to floating point arithmetic, a user doing OKLCH -> RGB will still
321
- // need to clip the result again anyways, so perhaps this difference is negligible.
322
- const targetSpaceBase = targetSpace.base ?? targetSpaceBase;
328
+ // Note: if requested targetSpace is base=OKLCH, we can return early.
329
+ // note this creates a potential difference compared to going to other targetSpaces:
330
+ // a) mapping to sRGB then finally converting back to OKLCH the result may be lossy in
331
+ // some coordinates that you might not expect, e.g. hue loss when hue should be unchanged
332
+ // during gamut mapping, due to conversion / floating point math
333
+ // b) if you map to sRGB it will perform clipping, but if you map to OKLCH then no sRGB clipping
334
+ // will be applied. The OKLCH result is _basically_ in gamut, but not exactly; you'll need to clip at final stage.
335
+ // I've documented this behaviour in the readme.
336
+ const targetSpaceBase = targetSpace.base ?? targetSpace;
323
337
  if (targetSpaceBase == OKLab) {
324
338
  return convert(out, OKLCH, targetSpace, out);
325
339
  }
326
340
 
327
- // now that we have a LCH that sits on the gamut, convert again to linear space
341
+ // now that we have a LCH that sits on (or nearly on) the gamut, convert again to linear space
328
342
  convert(out, OKLCH, gamutSpaceBase, rgbVec);
329
343
  }
330
344
  // clip the linear RGB to 0..1 range
@@ -19,6 +19,8 @@ import {
19
19
  import { p3, toGamut, oklch, okhsl, converter } from "culori";
20
20
 
21
21
  const N = 256 * 256;
22
+ const gamut = DisplayP3Gamut;
23
+ const target = gamut.space;
22
24
 
23
25
  // get N OKLCH in-gamut pixels by sampling uniformly from OKHSL cube
24
26
  const oklchPixelsInGamut = Array(N)
@@ -27,8 +29,8 @@ const oklchPixelsInGamut = Array(N)
27
29
  const t = i / (lst.length - 1);
28
30
  // note if we use the standard OKHSL space, it is bound to sRGB gamut...
29
31
  // so instead we use the OKHSLToOKLab function and pass P3 gamut
30
- const okhsl = [t, t, t * 360];
31
- const oklab = OKHSLToOKLab(okhsl, DisplayP3Gamut);
32
+ const okhsl = [t * 360, t, t];
33
+ const oklab = OKHSLToOKLab(okhsl, gamut);
32
34
  return convert(oklab, OKLab, OKLCH);
33
35
  });
34
36
 
@@ -44,12 +46,34 @@ const toP3Gamut = toGamut("p3", "oklch");
44
46
  // same perf as p3() it seems
45
47
  // const p3Converter = converter("p3");
46
48
 
47
- test(oklchPixelsInGamut, "Random Samling in P3 Gamut");
48
- test(oklchPixelsRandom, "Random Samling in OKLab L Planes");
49
+ test(oklchPixelsInGamut, "Random Sampling in P3 Gamut");
50
+ test(oklchPixelsRandom, "Random Sampling in OKLab L Planes");
51
+ test(oklchPixelsRandom, "Random Sampling in OKLab L Planes", true);
52
+
53
+ function test(inputPixelsOKLCH, label, fixedCusp) {
54
+ let cuspMap;
55
+ if (fixedCusp) {
56
+ cuspMap = new Array(360).fill(null);
57
+ inputPixelsOKLCH = inputPixelsOKLCH.map((oklch) => {
58
+ const H = constrainAngle(Math.round(oklch[2]));
59
+ oklch = oklch.slice();
60
+ oklch[2] = H;
61
+ if (!cuspMap[H]) {
62
+ const Hr = degToRad(H);
63
+ const a = Math.cos(Hr);
64
+ const b = Math.sin(Hr);
65
+ cuspMap[H] = findCuspOKLCH(a, b, gamut);
66
+ }
67
+ return oklch;
68
+ });
69
+ }
49
70
 
50
- function test(inputPixelsOKLCH, label) {
51
- console.log("Testing with input type: %s", label);
52
- const culoriInputsOKLCH = oklchPixelsRandom.map(([l, c, h]) => {
71
+ console.log(
72
+ "Testing with input type: %s%s",
73
+ label,
74
+ fixedCusp ? " (Fixed Cusp)" : ""
75
+ );
76
+ const culoriInputsOKLCH = inputPixelsOKLCH.map(([l, c, h]) => {
53
77
  return {
54
78
  mode: "oklch",
55
79
  l,
@@ -66,7 +90,7 @@ function test(inputPixelsOKLCH, label) {
66
90
  tmp = [0, 0, 0];
67
91
  now = performance.now();
68
92
  for (let oklch of inputPixelsOKLCH) {
69
- convert(oklch, OKLCH, DisplayP3, tmp);
93
+ convert(oklch, OKLCH, target, tmp);
70
94
  }
71
95
  elapsedOurs = performance.now() - now;
72
96
 
@@ -74,7 +98,7 @@ function test(inputPixelsOKLCH, label) {
74
98
  for (let oklchColor of culoriInputsOKLCH) {
75
99
  p3(oklchColor);
76
100
 
77
- // same perf
101
+ // same perf ?
78
102
  // p3Converter(oklchColor);
79
103
  }
80
104
  elapsedCulori = performance.now() - now;
@@ -83,11 +107,20 @@ function test(inputPixelsOKLCH, label) {
83
107
  //// gamut
84
108
 
85
109
  tmp = [0, 0, 0];
86
- now = performance.now();
87
- for (let oklch of inputPixelsOKLCH) {
88
- gamutMapOKLCH(oklch, DisplayP3Gamut, DisplayP3, tmp);
110
+ if (fixedCusp && cuspMap) {
111
+ now = performance.now();
112
+ for (let oklch of inputPixelsOKLCH) {
113
+ const cusp = cuspMap[oklch[2]];
114
+ gamutMapOKLCH(oklch, gamut, target, tmp, undefined, cusp);
115
+ }
116
+ elapsedOurs = performance.now() - now;
117
+ } else {
118
+ now = performance.now();
119
+ for (let oklch of inputPixelsOKLCH) {
120
+ gamutMapOKLCH(oklch, gamut, target, tmp);
121
+ }
122
+ elapsedOurs = performance.now() - now;
89
123
  }
90
- elapsedOurs = performance.now() - now;
91
124
 
92
125
  now = performance.now();
93
126
  for (let oklchColor of culoriInputsOKLCH) {
@@ -13,12 +13,13 @@ import {
13
13
  constrainAngle,
14
14
  floatToByte,
15
15
  isRGBInGamut,
16
+ clampedRGB,
16
17
  } from "../src/index.js";
17
18
  import arrayAlmostEqual from "./almost-equal.js";
18
19
 
19
20
  const settings = {
20
21
  dimensions: [768, 768],
21
- animate: true,
22
+ animate: false,
22
23
  playbackRate: "throttle",
23
24
  fps: 2,
24
25
  attributes: {
@@ -34,7 +35,8 @@ const sketch = ({ width, height }) => {
34
35
 
35
36
  context.fillStyle = "gray";
36
37
  context.fillRect(0, 0, width, height);
37
- const H = constrainAngle((frame * 45) / 2);
38
+ const H = 264.1;
39
+ // const H = constrainAngle((frame * 45) / 2);
38
40
 
39
41
  // console.time("map");
40
42
  // console.profile("map");
@@ -123,7 +125,7 @@ const sketch = ({ width, height }) => {
123
125
  context.lineTo(...LCtoXY(mapped));
124
126
  context.stroke();
125
127
  context.globalAlpha = 1;
126
- drawLCPoint(context, mapped.slice(0, 2), radius, "white");
128
+ drawLCPoint(context, mapped.slice(0, 2), radius / 4, "white");
127
129
  } else {
128
130
  drawLCPoint(context, lc, radius);
129
131
  }
@@ -0,0 +1,136 @@
1
+ // When gamut mapping with OKLCH approximation,
2
+ // the resulting points do not always lie exactly in gamut.
3
+ // The same may be true of OKHSL to RGB spaces.
4
+ // Let's figure out how far away they are:
5
+ // if a given point is under this threshold, gamut mapping
6
+ // will be redundant as it will just produce the same epsilon.
7
+ // This value is used in gamut.js as the RGB_CLIP_EPSILON
8
+
9
+ import {
10
+ clampedRGB,
11
+ convert,
12
+ degToRad,
13
+ findCuspOKLCH,
14
+ findGamutIntersectionOKLCH,
15
+ gamutMapOKLCH,
16
+ isRGBInGamut,
17
+ lerp,
18
+ MapToCuspL,
19
+ OKLCH,
20
+ sRGB,
21
+ sRGBGamut,
22
+ sRGBLinear,
23
+ } from "../src/index.js";
24
+
25
+ const gamut = sRGBGamut;
26
+ const target = gamut.space.base; // linear form
27
+
28
+ // slice the plane into a square
29
+ const slices = 100;
30
+ let avgDelta = 0;
31
+ let avgCount = 0;
32
+ let minDelta = Infinity;
33
+ let maxDelta = -Infinity;
34
+
35
+ // a very small number which still catches many gamut-mapped points
36
+ // but produces very little difference in practical and visual results
37
+ const RGB_CLIP_EPSILON = 0.0000001;
38
+ let totalPointsOutOfGamut = 0;
39
+ let totalPointsUnderEpsilon = 0;
40
+ let totalPointsUnderEpsilonBeforeMapping = 0;
41
+
42
+ // this particular hue is a little funky
43
+ // https://github.com/color-js/color.js/issues/81
44
+ // it produces out of gamut sRGB, however, the oklab gamut approximation seems to handle it fine
45
+ const hue = 264.1;
46
+ const lightness = 0.4;
47
+ for (let chroma = 0.22; chroma < 0.285; chroma += 0.001) {
48
+ const oklch = [lightness, chroma, hue];
49
+ const rgb = convert(oklch, OKLCH, sRGBLinear);
50
+ if (!isRGBInGamut(rgb, 0)) {
51
+ const mappedOKLCH = gamutMapWithoutClipOKLCH(oklch);
52
+ const mappedRGB = convert(mappedOKLCH, OKLCH, sRGBLinear);
53
+ const delta = clipDelta(mappedRGB);
54
+ if (!delta.every((n) => n == 0)) console.log("hue", hue, "delta", delta);
55
+ }
56
+ }
57
+
58
+ // test all hue planes Nº difference apart
59
+ // we will see some gamut mapped points still do not lie exactly in gamut
60
+ for (let H = 0; H < 360; H += 0.5) {
61
+ for (let y = 0; y < slices; y++) {
62
+ for (let x = 0; x < slices; x++) {
63
+ const u = x / (slices - 1);
64
+ const v = y / (slices - 1);
65
+ const L = 1 - v;
66
+ const C = u * 0.4;
67
+
68
+ // try conversion
69
+ let rgbl = convert([L, C, H], OKLCH, target);
70
+
71
+ // not exactly in space
72
+ if (!isRGBInGamut(rgbl, 0)) {
73
+ // check epsilons
74
+ if (isRGBInGamut(rgbl, RGB_CLIP_EPSILON)) {
75
+ totalPointsUnderEpsilonBeforeMapping++;
76
+ }
77
+
78
+ const oklch = gamutMapWithoutClipOKLCH([L, C, H]);
79
+ rgbl = convert(oklch, OKLCH, target);
80
+
81
+ const [dr, dg, db] = clipDelta(rgbl);
82
+ const avg = (dr + dg + db) / 3;
83
+ const min = Math.min(dr, dg, db);
84
+ const max = Math.max(dr, dg, db);
85
+ avgDelta += avg;
86
+ avgCount++;
87
+ minDelta = Math.min(min, minDelta);
88
+ maxDelta = Math.max(max, maxDelta);
89
+
90
+ totalPointsOutOfGamut++;
91
+ if (isRGBInGamut(rgbl, RGB_CLIP_EPSILON)) {
92
+ totalPointsUnderEpsilon++;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ }
98
+
99
+ function clipDelta(rgb) {
100
+ const clipped = clampedRGB(rgb);
101
+ const dr = Math.abs(rgb[0] - clipped[0]);
102
+ const dg = Math.abs(rgb[1] - clipped[1]);
103
+ const db = Math.abs(rgb[2] - clipped[2]);
104
+ return [dr, dg, db];
105
+ }
106
+
107
+ function gamutMapWithoutClipOKLCH(oklch) {
108
+ const [L, C, H] = oklch;
109
+ // we aren't in gamut, so let's map toward it
110
+ const hueAngle = degToRad(H);
111
+ const aNorm = Math.cos(hueAngle);
112
+ const bNorm = Math.sin(hueAngle);
113
+
114
+ const out = [L, C, H];
115
+ // choose our strategy
116
+ const cusp = findCuspOKLCH(aNorm, bNorm, gamut);
117
+ const LTarget = MapToCuspL(out, cusp);
118
+
119
+ let t = findGamutIntersectionOKLCH(aNorm, bNorm, L, C, LTarget, cusp, gamut);
120
+ out[0] = lerp(LTarget, L, t);
121
+ out[1] *= t;
122
+ return out;
123
+ }
124
+
125
+ avgDelta /= avgCount;
126
+
127
+ console.log("Min Epsilon:", minDelta);
128
+ console.log("Max Epsilon:", maxDelta);
129
+ console.log("Average Epsilon:", avgDelta);
130
+ console.log("Compare against epsilon:", RGB_CLIP_EPSILON);
131
+ console.log("Total points out of gamut:", totalPointsOutOfGamut);
132
+ console.log(
133
+ "Total points under epsilon (before map):",
134
+ totalPointsUnderEpsilonBeforeMapping
135
+ );
136
+ console.log("Total points under epsilon (after map):", totalPointsUnderEpsilon);