Debian Codegraph @

node/colorjs.io/src/spaces/cam16.js

raw
1 import ColorSpace from "../ColorSpace.js";
2 import { multiply_v3_m3x3, interpolate, copySign, spow, zdiv, bisectLeft } from "../util.js";
3 import { constrain } from "../angles.js";
4 import xyz_d65 from "./xyz-d65.js";
5 import { WHITES } from "../adapt.js";
6
7 /** @import { Coords, Matrix3x3, Vector3 } from "../types.js" */
8
9 // Type re-exports
10 /** @typedef {import("../types.js").Cam16Object} Cam16Object */
11 /** @typedef {import("../types.js").Cam16Input} Cam16Input */
12 /** @typedef {import("../types.js").Cam16Environment} Cam16Environment */
13
14 const white = WHITES.D65;
15 const adaptedCoef = 0.42;
16 const adaptedCoefInv = 1 / adaptedCoef;
17 const tau = 2 * Math.PI;
18
19 /**
20 * Matrices used by this color space, also available as `CAM16_JMh.M`
21 * @type {Record<string, Matrix3x3>}
22 */
23 // prettier-ignore
24 export const M = {
25 cat16: [
26 [ 0.401288, 0.650173, -0.051461 ],
27 [ -0.250268, 1.204414, 0.045854 ],
28 [ -0.002079, 0.048952, 0.953127 ],
29 ],
30 cat16Inv: [
31 [ 1.8620678550872327, -1.0112546305316843, 0.14918677544445175 ],
32 [ 0.38752654323613717, 0.6214474419314753, -0.008973985167612518 ],
33 [ -0.015841498849333856, -0.03412293802851557, 1.0499644368778496 ],
34 ],
35 m1: [
36 [ 460.0, 451.0, 288.0 ],
37 [ 460.0, -891.0, -261.0 ],
38 [ 460.0, -220.0, -6300.0 ],
39 ],
40 };
41
42 const surroundMap = {
43 dark: [0.8, 0.525, 0.8],
44 dim: [0.9, 0.59, 0.9],
45 average: [1, 0.69, 1],
46 };
47
48 const hueQuadMap = {
49 // Red, Yellow, Green, Blue, Red
50 h: [20.14, 90.0, 164.25, 237.53, 380.14],
51 e: [0.8, 0.7, 1.0, 1.2, 0.8],
52 H: [0.0, 100.0, 200.0, 300.0, 400.0],
53 };
54
55 const rad2deg = 180 / Math.PI;
56 const deg2rad = Math.PI / 180;
57
58 /**
59 * @param {Coords} coords
60 * @param {number} fl
61 * @returns {[number, number, number]}
62 */
63 export function adapt (coords, fl) {
64 const temp = /** @type {[number, number, number]} */ (
65 coords.map(c => {
66 const x = spow(fl * Math.abs(c) * 0.01, adaptedCoef);
67 return (400 * copySign(x, c)) / (x + 27.13);
68 })
69 );
70 return temp;
71 }
72
73 /**
74 * @param {Coords} adapted
75 * @param {number} fl
76 * @returns {[number, number, number]}
77 */
78 export function unadapt (adapted, fl) {
79 const constant = (100 / fl) * 27.13 ** adaptedCoefInv;
80 return /** @type {[number, number, number]} */ (
81 adapted.map(c => {
82 const cabs = Math.abs(c);
83 return copySign(constant * spow(cabs / (400 - cabs), adaptedCoefInv), c);
84 })
85 );
86 }
87
88 /**
89 * @param {number} h
90 */
91 export function hueQuadrature (h) {
92 let hp = constrain(h);
93 if (hp <= hueQuadMap.h[0]) {
94 hp += 360;
95 }
96
97 const i = bisectLeft(hueQuadMap.h, hp) - 1;
98 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
99 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
100 const Hi = hueQuadMap.H[i];
101
102 const t = (hp - hi) / ei;
103 return Hi + (100 * t) / (t + (hii - hp) / eii);
104 }
105
106 /**
107 * @param {number} H
108 */
109 export function invHueQuadrature (H) {
110 let Hp = ((H % 400) + 400) % 400;
111 const i = Math.floor(0.01 * Hp);
112 Hp = Hp % 100;
113 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
114 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
115
116 return constrain((Hp * (eii * hi - ei * hii) - 100 * hi * eii) / (Hp * (eii - ei) - 100 * eii));
117 }
118
119 /**
120 * @param {[number, number, number]} refWhite
121 * @param {number} adaptingLuminance
122 * @param {number} backgroundLuminance
123 * @param {keyof typeof surroundMap} surround
124 * @param {boolean} discounting
125 * @returns {Cam16Environment}
126 */
127 export function environment (
128 refWhite,
129 adaptingLuminance,
130 backgroundLuminance,
131 surround,
132 discounting,
133 ) {
134 const env = {};
135
136 env.discounting = discounting;
137 env.refWhite = refWhite;
138 env.surround = surround;
139 const xyzW = /** @type {Vector3} */ (
140 refWhite.map(c => {
141 return c * 100;
142 })
143 );
144
145 // The average luminance of the environment in `cd/m^2cd/m` (a.k.a. nits)
146 env.la = adaptingLuminance;
147 // The relative luminance of the nearby background
148 env.yb = backgroundLuminance;
149 // Absolute luminance of the reference white.
150 const yw = xyzW[1];
151
152 // Cone response for reference white
153 const rgbW = multiply_v3_m3x3(xyzW, M.cat16);
154
155 // Surround: dark, dim, and average
156 let values = surroundMap[env.surround];
157 const f = values[0];
158 env.c = values[1];
159 env.nc = values[2];
160
161 const k = 1 / (5 * env.la + 1);
162 const k4 = k ** 4;
163
164 // Factor of luminance level adaptation
165 env.fl = k4 * env.la + 0.1 * (1 - k4) * (1 - k4) * Math.cbrt(5 * env.la);
166 env.flRoot = env.fl ** 0.25;
167
168 env.n = env.yb / yw;
169 env.z = 1.48 + Math.sqrt(env.n);
170 env.nbb = 0.725 * env.n ** -0.2;
171 env.ncb = env.nbb;
172
173 // Degree of adaptation calculating if not discounting
174 // illuminant (assumed eye is fully adapted)
175 const d = discounting
176 ? 1
177 : Math.max(Math.min(f * (1 - (1 / 3.6) * Math.exp((-env.la - 42) / 92)), 1), 0);
178 env.dRgb = /** @type {[number, number, number]} */ (
179 rgbW.map(c => {
180 return interpolate(1, yw / c, d);
181 })
182 );
183 env.dRgbInv = /** @type {[number, number, number]} */ (
184 env.dRgb.map(c => {
185 return 1 / c;
186 })
187 );
188
189 // Achromatic response
190 const rgbCW = /** @type {[number, number, number]} */ (
191 rgbW.map((c, i) => {
192 return c * env.dRgb[i];
193 })
194 );
195 const rgbAW = adapt(rgbCW, env.fl);
196 env.aW = env.nbb * (2 * rgbAW[0] + rgbAW[1] + 0.05 * rgbAW[2]);
197
198 // console.log(env);
199
200 return env;
201 }
202
203 // Pre-calculate everything we can with the viewing conditions
204 const viewingConditions = environment(white, (64 / Math.PI) * 0.2, 20, "average", false);
205
206 /**
207 * @param {Cam16Input} cam16
208 * @param {Cam16Environment} env
209 * @returns {[number, number, number]}
210 */
211 export function fromCam16 (cam16, env) {
212 // These check ensure one, and only one attribute for a
213 // given category is provided.
214 // @ts-expect-error The '^` operator is not allowed for boolean types
215 if (!((cam16.J !== undefined) ^ (cam16.Q !== undefined))) {
216 throw new Error("Conversion requires one and only one: 'J' or 'Q'");
217 }
218
219 // @ts-expect-error - The '^` operator is not allowed for boolean types
220 if (!((cam16.C !== undefined) ^ (cam16.M !== undefined) ^ (cam16.s !== undefined))) {
221 throw new Error("Conversion requires one and only one: 'C', 'M' or 's'");
222 }
223
224 // Hue is absolutely required
225 // @ts-expect-error - The '^` operator is not allowed for boolean types
226 if (!((cam16.h !== undefined) ^ (cam16.H !== undefined))) {
227 throw new Error("Conversion requires one and only one: 'h' or 'H'");
228 }
229
230 // Black
231 if (cam16.J === 0.0 || cam16.Q === 0.0) {
232 return [0.0, 0.0, 0.0];
233 }
234
235 // Break hue into Cartesian components
236 let hRad = 0.0;
237 if (cam16.h !== undefined) {
238 hRad = constrain(cam16.h) * deg2rad;
239 }
240 else {
241 hRad = invHueQuadrature(cam16.H) * deg2rad;
242 }
243
244 const cosh = Math.cos(hRad);
245 const sinh = Math.sin(hRad);
246
247 // Calculate `Jroot` from one of the lightness derived coordinates.
248 let Jroot = 0.0;
249 if (cam16.J !== undefined) {
250 Jroot = spow(cam16.J, 1 / 2) * 0.1;
251 }
252 else if (cam16.Q !== undefined) {
253 Jroot = (0.25 * env.c * cam16.Q) / ((env.aW + 4) * env.flRoot);
254 }
255
256 // Calculate the `t` value from one of the chroma derived coordinates
257 let alpha = 0.0;
258 if (cam16.C !== undefined) {
259 alpha = cam16.C / Jroot;
260 }
261 else if (cam16.M !== undefined) {
262 alpha = cam16.M / env.flRoot / Jroot;
263 }
264 else if (cam16.s !== undefined) {
265 alpha = (0.0004 * cam16.s ** 2 * (env.aW + 4)) / env.c;
266 }
267 const t = spow(alpha * Math.pow(1.64 - Math.pow(0.29, env.n), -0.73), 10 / 9);
268
269 // Eccentricity
270 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
271
272 // Achromatic response
273 const A = env.aW * spow(Jroot, 2 / env.c / env.z);
274
275 // Calculate red-green and yellow-blue components
276 const p1 = (5e4 / 13) * env.nc * env.ncb * et;
277 const p2 = A / env.nbb;
278 const r = 23 * (p2 + 0.305) * zdiv(t, 23 * p1 + t * (11 * cosh + 108 * sinh));
279 const a = r * cosh;
280 const b = r * sinh;
281
282 // Calculate back from cone response to XYZ
283 const rgb_c = unadapt(
284 /** @type {Vector3} */
285 (
286 multiply_v3_m3x3([p2, a, b], M.m1).map(c => {
287 return (c * 1) / 1403;
288 })
289 ),
290 env.fl,
291 );
292 return /** @type {Vector3} */ (
293 multiply_v3_m3x3(
294 /** @type {Vector3} */ (
295 rgb_c.map((c, i) => {
296 return c * env.dRgbInv[i];
297 })
298 ),
299 M.cat16Inv,
300 ).map(c => {
301 return c / 100;
302 })
303 );
304 }
305
306 /**
307 * @param {[number, number, number]} xyzd65
308 * @param {Cam16Environment} env
309 * @returns {Cam16Object}
310 */
311 export function toCam16 (xyzd65, env) {
312 // Cone response
313 const xyz100 = /** @type {Vector3} */ (
314 xyzd65.map(c => {
315 return c * 100;
316 })
317 );
318 const rgbA = adapt(
319 /** @type {[number, number, number]} */
320 (
321 multiply_v3_m3x3(xyz100, M.cat16).map((c, i) => {
322 return c * env.dRgb[i];
323 })
324 ),
325 env.fl,
326 );
327
328 // Calculate hue from red-green and yellow-blue components
329 const a = rgbA[0] + (-12 * rgbA[1] + rgbA[2]) / 11;
330 const b = (rgbA[0] + rgbA[1] - 2 * rgbA[2]) / 9;
331 const hRad = ((Math.atan2(b, a) % tau) + tau) % tau;
332
333 // Eccentricity
334 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
335
336 const t =
337 (5e4 / 13) *
338 env.nc *
339 env.ncb *
340 zdiv(et * Math.sqrt(a ** 2 + b ** 2), rgbA[0] + rgbA[1] + 1.05 * rgbA[2] + 0.305);
341 const alpha = spow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, env.n), 0.73);
342
343 // Achromatic response
344 const A = env.nbb * (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]);
345
346 const Jroot = spow(A / env.aW, 0.5 * env.c * env.z);
347
348 // Lightness
349 const J = 100 * spow(Jroot, 2);
350
351 // Brightness
352 const Q = (4 / env.c) * Jroot * (env.aW + 4) * env.flRoot;
353
354 // Chroma
355 const C = alpha * Jroot;
356
357 // Colorfulness
358 const colorfulness = C * env.flRoot;
359
360 // Hue
361 const h = constrain(hRad * rad2deg);
362
363 // Hue quadrature
364 const H = hueQuadrature(h);
365
366 // Saturation
367 const s = 50 * spow((env.c * alpha) / (env.aW + 4), 1 / 2);
368
369 // console.log({J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H});
370
371 return { J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H };
372 }
373
374 // Provided as a way to directly evaluate the CAM16 model
375 // https://observablehq.com/@jrus/cam16: reference implementation
376 // https://arxiv.org/pdf/1802.06067.pdf: Nico Schlömer
377 // https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.22324: hue quadrature
378 // https://www.researchgate.net/publication/318152296_Comprehensive_color_solutions_CAM16_CAT16_and_CAM16-UCS
379 // Results compared against: https://github.com/colour-science/colour
380 export default new ColorSpace({
381 id: "cam16-jmh",
382 cssId: "--cam16-jmh",
383 name: "CAM16-JMh",
384 coords: {
385 j: {
386 refRange: [0, 100],
387 name: "J",
388 },
389 m: {
390 refRange: [0, 105.0],
391 name: "Colorfulness",
392 },
393 h: {
394 refRange: [0, 360],
395 type: "angle",
396 name: "Hue",
397 },
398 },
399
400 base: xyz_d65,
401
402 M,
403
404 fromBase (xyz) {
405 // If another derivation is created, ε could vary, so we can't hardcode
406 if (this.ε === undefined) {
407 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
408 }
409 const cam16 = toCam16(xyz, viewingConditions);
410 const isAchromatic = Math.abs(cam16.M) < this.ε;
411 return [cam16.J, isAchromatic ? 0 : cam16.M, isAchromatic ? null : cam16.h];
412 },
413 toBase (cam16) {
414 return fromCam16({ J: cam16[0], M: cam16[1], h: cam16[2] }, viewingConditions);
415 },
416 });