-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconvert.js
More file actions
2420 lines (2161 loc) · 82.2 KB
/
Copy pathconvert.js
File metadata and controls
2420 lines (2161 loc) · 82.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*************************************************************************
* @license
*
*
* Copyright © 2019, 2024 Glenn Wilton
* O2 Creative Limited
* www.o2creative.co.nz
* support@o2creative.co.nz
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
*/
'use strict';
/**
* ============================================================================
* convert.js — colour-math helper layer
* ============================================================================
*
* This module is the maths floor of jsColorEngine. It is a flat collection of
* pure (and a few side-effecting) functions that:
*
* - Construct typed colour objects (`RGB()`, `Lab()`, `XYZ()`, `CMYK()`...)
* - Convert between colour spaces using closed-form maths (XYZ ↔ Lab ↔ LCH,
* RGB matrix profiles ↔ XYZ ↔ Lab, xyY ↔ XYZ).
* - Perform Bradford chromatic adaptation between whitepoints.
* - Compute, invert, transpose and multiply 3x3 RGB-profile matrices.
* - Apply / invert per-channel gamma (sRGB curve and pure-gamma).
* - Compute ΔE colour-difference (1976, 1994, 2000, CMC).
* - A handful of display/format helpers (RGB→hex, intent→string, etc.).
*
* ----------------------------------------------------------------------------
* WHEN TO USE THIS FILE vs Transform.js
* ----------------------------------------------------------------------------
*
* - convert.js → ACCURACY PATH. Single colour, full precision, allocates
* small objects. Ideal for swatches, ΔE, analysis, and as
* the building blocks Transform.js calls when it isn't
* walking a CLUT. NEVER call these in a per-pixel loop over
* image data — use Transform's prebuilt-LUT image path.
*
* - Transform.js → speed-and-correctness path: ICC pipeline, LUT baking,
* per-pixel inner loops.
*
* ----------------------------------------------------------------------------
* TYPED COLOUR OBJECT CONVENTION
* ----------------------------------------------------------------------------
*
* Every colour value is a plain object tagged with `type` (an `eColourType`
* enum value) and uppercase channel keys:
*
* RGB { type, R, G, B } // 0–255 byte
* RGBf { type, Rf, Gf, Bf } // 0.0–1.0 float
* CMYK { type, C, M, Y, K } // 0–100 percent
* CMYKf { type, Cf, Mf, Yf, Kf } // 0.0–1.0 float
* Gray { type, G } // 0–255 byte (see TODO D1)
* Duo { type, a, b } // 0–100 percent
* Lab { type, L, a, b, whitePoint } // L 0–100, a/b ≈ ±128
* LabD50 { L, a, b } // un-tagged D50 helper
* LCH { type, L, C, H, whitePoint } // H 0–360
* XYZ { type, X, Y, Z, whitePoint? } // Y normalised to 1.0
* xyY { type, x, y, Y } // chromaticity + luminance
*
* Lab/LCH carry their reference whitepoint with them so a downstream
* conversion can adapt automatically. XYZ optionally carries one but the
* adaptation API takes whitepoints as explicit args.
*
* ----------------------------------------------------------------------------
* WHITEPOINT CONVENTION ⚠ enforced invariant
* ----------------------------------------------------------------------------
*
* All whitepoints in this engine are XYZ values NORMALISED SO `Y === 1.0`.
* They are attached to `convert` as `convert.d50`, `convert.d65`,
* `convert.a`, etc. Look up by name with `getWhitePoint('d65')`
* (defaults to D50).
*
* This invariant is leaned on as a perf optimisation throughout the file:
* a number of functions deliberately drop `wp.Y` multiplies/divides
* because the result is identical when Y === 1.0. Each such site has an
* inline `INTENTIONAL: Y === 1.0` comment — do NOT "fix" them by adding
* the `* wp.Y` term back. Sites:
*
* - XYZ2Lab yr = XYZ.Y (instead of / wp.Y)
* - Lab2XYZ Y: yr (instead of yr * wp.Y)
* - Lab2RGBDevice Y: yr (same as Lab2XYZ)
* - RGBDevice2LabD50 yr = XYZ.Y (same as XYZ2Lab)
* - RGBf2Lab yr = XYZ.Y (same as XYZ2Lab)
* - adaptation drops `* sourceWhite.Y` and `* destWhite.Y`
* in the cone-space projections (the input XYZ.Y
* multiplies are KEPT — colour Y is not 1.0).
*
* If you ever need to support un-normalised whitepoints, every site
* listed above has to be updated together — and the perf tradeoff
* reconsidered.
*
* ----------------------------------------------------------------------------
* CIE Lab MATH CONSTANTS (used throughout)
* ----------------------------------------------------------------------------
*
* kE = 216 / 24389 ≈ 0.008856 (CIE epsilon, the "linear-segment knee")
* kK = 24389 / 27 ≈ 903.296 (CIE kappa)
* kKE = 8 (kE * kK, used as L threshold)
*
* These are the modern (TC1-48 corrected) values. `Lab2sRGB` below uses the
* older `0.008856 / 7.787` constants for historical reasons — same maths to
* ~6 d.p., kept as an alternate D65 fast-path.
*
* ----------------------------------------------------------------------------
* RGB MATRIX PROFILES
* ----------------------------------------------------------------------------
*
* An RGB matrix profile (sRGB, AdobeRGB, etc.) is just a set of:
* - primary chromaticities (cRx,cRy / cGx,cGy / cBx,cBy)
* - a media whitepoint
* - a gamma curve (or the sRGB piecewise curve)
*
* `computeMatrix(profile)` derives the RGB→XYZ and XYZ→RGB 3x3 matrices from
* the primaries + whitepoint and stuffs them onto `profile.RGBMatrix.matrixV4`
* / `.matrixInv`. After that, the per-pixel maths is:
*
* linear = gammaInv(rgb) // display → linear
* XYZ = matrixV4 · linear // 3x3 multiply
* [adapt] = bradford(XYZ, src→dst whitepoint, if needed)
* Lab = XYZ2Lab(adapted, dst whitepoint)
*
* ----------------------------------------------------------------------------
* HISTORY / RESOLVED ISSUES
* ----------------------------------------------------------------------------
*
* C1 Lab2RGB — FIXED: copy-paste typo (RGBDevice[0] for all
* channels) replaced with [0]/[1]/[2].
* C2 RGB2Lab — FIXED: was double-adapting across whitepoints
* because RGBf2XYZ already adapts internally.
* C3 Lab2RGBDevice — RECLASSIFIED as intentional Y === 1.0 perf
* C4 RGBf2Lab optimisation. See WHITEPOINT CONVENTION above.
* D2 Lab2sRGB — RECLASSIFIED as by-design: it is a display-
* only "show this Lab roughly on screen" helper,
* not a colorimetric path. No adaptation, no
* profile, hardcoded sRGB/D65. Doc updated.
*
* REMAINING DOC NOTES (not bugs, just things to be aware of):
*
* D1 Gray ctor — JSDoc-vs-clamp range conflict; clamp wins
* (0–255). Doc updated.
* D3 gamma/gammaInv — naming reads back-to-front; mnemonic in JSDoc.
* D4 computeMatrix — side-effecting initialiser; documented.
* D5 transpose — mutates input in place; documented.
*
* ----------------------------------------------------------------------------
* REFERENCES
* ----------------------------------------------------------------------------
*
* Bruce Lindbloom — http://www.brucelindbloom.com/
* ICC.1:2010 (Profile spec)
* CIE 15:2004 (Colorimetry, 3rd ed.)
* CIE 142:2001 (CIEDE2000)
* Wyszecki & Stiles, Color Science (2nd ed.)
*/
var defs = require('./def');
var eIntent = defs.eIntent;
var eColourType = defs.eColourType;
// ============================================================================
// TYPEDEFS — shapes of the colour objects passed around the engine
// ============================================================================
/**
* @typedef {object} _cmsWhitePoint
* @property {string} desc Short label, e.g. 'd50', 'd65', 'a'.
* @property {number} X Normalised X (Y is always 1.0 in the bundled WPs).
* @property {number} Y Normalised Y (always 1.0 for bundled WPs).
* @property {number} Z Normalised Z.
*/
/**
* @typedef {object} _cmsGrey
* @property {number} type
* @property {number} g
*/
/**
* @typedef {object} _cmsDuo
* @property {number} type
* @property {number} a
* @property {number} b
*/
/**
* @typedef {object} _cmsCMYK
* @property {number} type
* @property {number} C
* @property {number} M
* @property {number} Y
* @property {number} K
*/
/**
* XYZ tristimulus, normalised so reference white Y == 1.0.
*
* `whitePoint` is optional and informational — most XYZ-consuming functions
* take a separate explicit whitepoint argument. When set, downstream Lab
* conversions can pick it up automatically.
*
* @typedef {object} _cmsXYZ
* @property {number} type eColourType.XYZ
* @property {number} X
* @property {number} Y
* @property {number} Z
* @property {_cmsWhitePoint} [whitePoint]
*/
/**
* @typedef {object} _cmsLab
* @property {number} type eColourType
* @property {number} L
* @property {number} a
* @property {number} b
* @property {_cmsWhitePoint} whitePoint
*/
/**
* @typedef {object} _cmsLabD50
* @property {number} L
* @property {number} a
* @property {number} b
*/
/**
* @typedef {object} _cmsLCH
* @property {number} type eColourType
* @property {number} L
* @property {number} C
* @property {number} H
* @property {_cmsWhitePoint} whitePoint
*/
/**
* @typedef {object} _cmsRGB
* @property {number} type
* @property {number} R
* @property {number} G
* @property {number} B
*/
/**
* @typedef {object} _cmsRGBf
* @property {number} type
* @property {number} Rf
* @property {number} Gf
* @property {number} Bf
*/
// ============================================================================
// INTERNAL UTILS
// ============================================================================
/**
* Round `n` to `places` decimal places. Used by the display/format helpers and
* by `Lab2RGB`. Not for hot paths.
*
* @param {number} n
* @param {number} places
* @returns {number}
*/
function roundN(n , places) {
var p = Math.pow(10, places)
return Math.round(n * p) / p;
}
var convert = {};
// ============================================================================
// DISPLAY / FORMAT HELPERS
// ============================================================================
/**
* Map an `eIntent` enum value to its short ICC name.
*
* @param {number} intent
* @returns {string} 'Perceptual' | 'Relative' | 'Saturation' | 'Absolute' | 'Unknown'
*/
convert.intent2String = function(intent){
switch(intent){
case eIntent.perceptual: return 'Perceptual';
case eIntent.relative: return 'Relative';
case eIntent.saturation: return 'Saturation';
case eIntent.absolute: return 'Absolute';
}
return 'Unknown'
};
// ============================================================================
// CHROMATIC ADAPTATION — Bradford matrices
// ============================================================================
//
// Forward and inverse Bradford cone-response matrices used by
// `convert.adaptation()`.
//
// PUBLIC API:
//
// convert.getBradfordMtxAdapt() // recommended — returns frozen ref
// convert.getBradfordMtxAdaptInv()
//
// convert.BradfordMtxAdapt // legacy direct-property access
// convert.BradfordMtxAdaptInv // (also frozen)
//
// Both are protected with `Object.freeze` so external code cannot mutate
// them. The getter functions are preferred for new code (cleaner intent,
// avoids accidental rebinds) and are written as plain functions — NOT
// defineProperty getters — so the API stays compatible with old JS engines
// that don't support ES5 accessors.
//
// Reference: Lindbloom — http://www.brucelindbloom.com/Eqn_ChromAdapt.html
//
// ============================================================================
/**
* Bradford cone-response matrix (XYZ → LMS). Frozen singleton — do not
* attempt to mutate (assignment is silently ignored in non-strict mode and
* throws in strict mode).
* @type {{m00:number,m01:number,m02:number,m10:number,m11:number,m12:number,m20:number,m21:number,m22:number}}
*/
convert.BradfordMtxAdapt = Object.freeze({
m00 : 0.8951,
m01 : -0.7502,
m02 : 0.0389,
m10 : 0.2664,
m11 : 1.7135,
m12 : -0.0685,
m20 : -0.1614,
m21 : 0.0367,
m22 : 1.0296
});
/**
* Inverse Bradford matrix (LMS → XYZ). Frozen singleton — see notes on
* `BradfordMtxAdapt`.
* @type {{m00:number,m01:number,m02:number,m10:number,m11:number,m12:number,m20:number,m21:number,m22:number}}
*/
convert.BradfordMtxAdaptInv = Object.freeze({
m00 : 0.9869929,
m01 : 0.4323053,
m02 : -0.0085287,
m10 : -0.1470543,
m11 : 0.5183603,
m12 : 0.0400428,
m20 : 0.1599627,
m21 : 0.0492912,
m22 : 0.9684867
});
/**
* Get the Bradford cone-response matrix (XYZ → LMS). Returns the frozen
* singleton — safe to read, mutation is rejected.
*
* If you need a mutable copy (e.g. for matrix-composition experiments), do:
*
* var m = Object.assign({}, convert.getBradfordMtxAdapt());
*
* @returns {{m00:number,m01:number,m02:number,m10:number,m11:number,m12:number,m20:number,m21:number,m22:number}}
*/
convert.getBradfordMtxAdapt = function(){
return convert.BradfordMtxAdapt;
};
/**
* Get the inverse Bradford matrix (LMS → XYZ). Returns the frozen
* singleton — safe to read, mutation is rejected. See `getBradfordMtxAdapt`
* for how to obtain a mutable copy.
*
* @returns {{m00:number,m01:number,m02:number,m10:number,m11:number,m12:number,m20:number,m21:number,m22:number}}
*/
convert.getBradfordMtxAdaptInv = function(){
return convert.BradfordMtxAdaptInv;
};
/**
* Format a typed colour object as a human-readable string for logs / UI.
*
* cmsColor2String(convert.RGB(255,0,0))
* // -> 'RGB: 255, 0, 0'
* cmsColor2String(convert.Lab(50,20,-30), 2)
* // -> 'Lab: 50, 20, -30 (d50)'
*
* @param {object} color Any typed colour object (must have `.type`).
* @param {number} [precision=4] Decimal places to round each channel to.
* @returns {string}
*/
convert.cmsColor2String = function(color, precision){
if(typeof precision === 'undefined'){
precision = 4;
}
switch (color.type){
case eColourType.CMYK: return col2Str('CMYK', color, ['C','M','Y','K']);
case eColourType.CMYKf: return col2Str('CMYKf', color, ['Cf','Mf','Yf','Kf']);
case eColourType.RGB: return col2Str('RGB', color, ['R','G','B']);
case eColourType.RGBf: return col2Str('RGBf', color, ['Rf','Gf','Bf']);
case eColourType.Gray: return col2Str('Gray', color, ['G']);
case eColourType.Lab: return col2Str('Lab', color, ['L','a','b']) + (color.whitePoint ? ' (' + color.whitePoint.desc + ')' : '');
case eColourType.LCH: return col2Str('LCH', color, ['L','C','H']) + (color.whitePoint ? ' (' + color.whitePoint.desc + ')' : '');
case eColourType.XYZ: return col2Str('XYZ', color, ['X','Y','Z']);
default:
return color.toString();
}
function col2Str(title, obj, props, includeProp){
var cols = [];
for(var i=0; i<props.length; i++){
if(includeProp){
cols.push(props[i] + ': ' + roundN(obj[props[i]], precision));
} else {
cols.push( roundN(obj[props[i]], precision));
}
}
return title + ': ' + cols.join(', ');
}
};
/**
* Format a whitepoint as `'(White d50 X0.9642 Y1.0000 Z0.8252)'`.
* @param {_cmsWhitePoint} whitePoint
* @returns {string}
*/
convert.whitepoint2String = function(whitePoint){
return '(White ' + whitePoint.desc + ' X' + whitePoint.X.toFixed(4) + ' Y' + whitePoint.Y.toFixed(4) + ' Z' + whitePoint.Z.toFixed(4) + ')';
};
// ============================================================================
// TYPED COLOUR CONSTRUCTORS
// ============================================================================
//
// Most constructors accept an optional `rangeCheck` flag. When it is the
// literal `false` the inputs are stored as-is (useful when feeding values
// that are already known good, or when out-of-gamut/negative values are
// intentional). Otherwise the constructor clamps and rounds.
//
// Whitepoint defaulting: Lab/LCH default to D50 (the ICC PCS whitepoint).
//
// ============================================================================
/**
* Build an XYZ colour. Components are normally in 0.0–1.0 (Y normalised so
* the reference white is 1.0).
* @param {number} X
* @param {number} Y
* @param {number} Z
* @param {_cmsWhitePoint=} whitePoint Defaults to D50.
* @returns {_cmsXYZ}
*/
convert.XYZ = function(X, Y, Z, whitePoint){
return {
type: eColourType.XYZ,
X:X,
Y:Y,
Z:Z,
whitePoint: whitePoint || this.d50
};
};
/**
* Build a Lab colour at the given whitepoint. By default L is clamped to
* 0–100 and a/b are clamped to ±127 (Lab16 ICC convention). Pass
* `rangeCheck === false` to skip clamping (e.g. for delta-E maths where
* negative or >100 L can occur intermediately).
*
* @param {number} L 0.0 - 100.0 (clamped unless rangeCheck === false)
* @param {number} a ±127 (clamped unless rangeCheck === false)
* @param {number} b ±127 (clamped unless rangeCheck === false)
* @param {_cmsWhitePoint=} whitePoint Defaults to D50.
* @param {boolean=} rangeCheck Pass `false` to disable clamping.
* @returns {_cmsLab}
*/
convert.Lab = function(L, a, b, whitePoint, rangeCheck){
if(rangeCheck === false){
return {
type: eColourType.Lab,
L: L,
a: a,
b: b,
whitePoint: whitePoint || this.d50
};
}
return {
type: eColourType.Lab,
L: (L > 100.0 ? 100.0 : L < 0.0 ? 0.0 : L),
a: (a > 127.0 ? 127.0 : a < -128.0 ? -128.0 : a),
b: (b > 127.0 ? 127.0 : b < -128.0 ? -128.0 : b),
whitePoint: whitePoint || this.d50
};
};
/**
* Build an LCH (cylindrical Lab) colour. L 0–100, C clamped ≥ 0, H wrapped
* into 0–360. Note: the negative-H wrap uses `(h + 3600) % 360` so very
* large negative inputs (h < -3600) won't wrap correctly — fine for normal
* use, but worth knowing.
*
* @param {number} L 0.0 - 100.0
* @param {number} c Chroma, clamped to ≥ 0.
* @param {number} h Hue in degrees, wrapped into 0–360.
* @param {_cmsWhitePoint=} whitePoint Defaults to D50.
* @returns {_cmsLCH}
*/
convert.Lch = function(L, c, h, whitePoint){
return {
type: eColourType.LCH,
L: (L > 100.0 ? 100.0 : L < 0.0 ? 0.0 : L),
C: (c < 0.0 ? 0.0 : c),
H: (h > 360.0 ? h % 360.0 : h < 0.0 ? (h + 3600) % 360 : h),
whitePoint: whitePoint || this.d50
}
};
convert.LCH = convert.Lch;
/**
* Build a Gray colour. Stored as 0–255 byte (despite the legacy JSDoc range).
*
* TODO (doc bug D1): JSDoc historically said 0–100 but the clamp is 0–255.
* The 0–255 clamp matches the rest of the engine's grey handling, so the
* range tag here is what's wrong. Fix when next touching the file.
*
* @param {number} g 0–255
* @param {boolean=} rangeCheck Pass `false` to disable clamping/rounding.
* @returns {_cmsGrey}
*/
convert.Gray = function(g, rangeCheck){
if(rangeCheck === false){
return {
type: eColourType.Gray,
G: g,
}
}
return {
type: eColourType.Gray,
G:(g > 255 ? 255 : g < 0 ? 0 : Math.round(g)),
};
};
/**
* Build a Duotone (2-channel) colour. Each channel is an ink percent 0–100.
* @param {number} a 0–100
* @param {number} b 0–100
* @param {boolean=} rangeCheck Pass `false` to disable clamping/rounding.
* @returns {_cmsDuo}
*/
convert.Duo = function(a, b, rangeCheck){
if(rangeCheck === false){
return {
type: eColourType.Duo,
a: a,
b: b,
}
}
return {
type: eColourType.Duo,
a:(a > 100 ? 100 : a < 0 ? 0 : Math.round(a)),
b:(b > 100 ? 100 : b < 0 ? 0 : Math.round(b))
};
};
/**
* Convert an `_cmsRGB` byte triple to a `#rrggbb` string.
*
* Implementation note: the `(1 << 24) + ... | 0` trick is the well-known
* leading-zero pad hack — the leading `1` becomes a 7th hex digit which is
* stripped by `slice(1)`, guaranteeing exactly 6 chars.
*
* @param {_cmsRGB} rgb
* @returns {string} e.g. '#ff0000'
*/
convert.RGB2Hex = function(rgb) {
return "#" + ((1 << 24) + (rgb.R << 16) + (rgb.G << 8) + rgb.B | 0).toString(16).slice(1);
};
/**
* Build an RGB byte colour. Components clamped to 0–255 and rounded unless
* `rangeCheck === false`.
*
* @param {number} r 0–255
* @param {number} g 0–255
* @param {number} b 0–255
* @param {boolean=} rangeCheck Pass `false` to disable clamping/rounding.
* @returns {_cmsRGB}
*/
convert.RGB = function(r, g, b, rangeCheck){
if(rangeCheck === false){
return {
type: eColourType.RGB,
R: r,
G: g,
B: b
}
}
return {
type: eColourType.RGB,
R:(r > 255 ? 255 : r < 0 ? 0 : Math.round(r)),
G:(g > 255 ? 255 : g < 0 ? 0 : Math.round(g)),
B:(b > 255 ? 255 : b < 0 ? 0 : Math.round(b))
};
};
/**
* Build an RGB float colour (no clamping). Alias of `RGBFloat`.
* @param {number} r 0.0 - 1.0 (typically; out-of-gamut is allowed)
* @param {number} g 0.0 - 1.0
* @param {number} b 0.0 - 1.0
* @returns {_cmsRGBf}
*/
convert.RGBf = function(r, g, b){
return {
type: eColourType.RGBf,
Rf: r,
Gf: g,
Bf: b
}
};
/**
* Build an RGB float colour. Normal range is 0.0–1.0 but values may fall
* outside that range to represent out-of-gamut colours (handled by clipping
* downstream when needed).
* @param {number} rf
* @param {number} gf
* @param {number} bf
* @returns {_cmsRGBf}
*/
convert.RGBFloat = function(rf, gf, bf){
return {
type: eColourType.RGBf,
Rf:rf,
Gf:gf,
Bf:bf
};
};
/**
* RGB 0-255 -> Float 0.0-1.0
* @param {number} r
* @param {number} g
* @param {number} b
* @returns {_cmsRGBf}
*/
convert.RGBbyte2Float = function(r, g, b){
return {
type: eColourType.RGBf,
Rf:r / 255,
Gf:g / 255,
Bf:b / 255
};
};
/**
*
* @param {number} c 0-100
* @param {number} m 0-100
* @param {number} y 0-100
* @param {number} k 0-100
* @param {boolean=} rangeCheck
* @returns {_cmsCMYK}
*/
convert.CMYK = function(c, m, y, k, rangeCheck){
if(rangeCheck === false){
return {
type: eColourType.CMYK,
C: c,
M: m,
Y: y,
K: k
};
}
return {
type: eColourType.CMYK,
C: (c > 100 ? 100 : c<0 ? 0 : Math.round(c)),
M: (m > 100 ? 100 : m<0 ? 0 : Math.round(m)),
Y: (y > 100 ? 100 : y<0 ? 0 : Math.round(y)),
K: (k > 100 ? 100 : k<0 ? 0 : Math.round(k))
};
};
/**
* Build a CMYK float colour (0.0–1.0 per channel). No clamping.
* @param {number} c
* @param {number} m
* @param {number} y
* @param {number} k
* @returns {_cmsCMYK}
*/
convert.CMYKf = function(c, m, y, k){
return {
type: eColourType.CMYKf,
Cf: c,
Mf: m,
Yf: y,
Kf: k
}
};
/**
* Build an xyY chromaticity+luminance colour.
* @param {number} x Chromaticity x (0–1).
* @param {number} y Chromaticity y (0–1).
* @param {number} Y Luminance (matches the XYZ Y normalisation).
* @returns {{type: number, x: number, y: number, Y: number}}
*/
convert.xyY = function(x, y, Y){
return {
type: eColourType.xyY,
x:x,
y:y,
Y:Y
};
};
// ============================================================================
// WHITEPOINTS — bundled CIE standard illuminants
// ============================================================================
//
// All values are XYZ tristimuli normalised so Y = 1.0 (ASTM E308-01, except
// where noted). They are stored on `convert` itself as `convert.d50`,
// `convert.d65`, etc. Look them up by name with `getWhitePoint('d65')`.
//
// D50 is the ICC PCS reference and is the default for Lab/LCH constructors.
//
// ============================================================================
/**
* Look up a bundled whitepoint by short name (case-insensitive).
* Falls through to D65 if the name is not recognised.
*
* getWhitePoint('d65') // -> convert.d65
* getWhitePoint('D50') // -> convert.d50
* getWhitePoint('foo') // -> convert.d65 (fallback)
*
* @param {string} whitepointDescription
* One of: 'a','b','c','d50','d55','d65','d75','e','f2','f7','f11'.
* @returns {_cmsWhitePoint}
*/
convert.getWhitePoint = function(whitepointDescription){
switch(whitepointDescription.toLowerCase()){
case 'a': //A (ASTM E308-01)
return this.a;
case 'b': // B (Wyszecki & Stiles, p. 769))
return this.b;
case 'c': // C (ASTM E308-01)
return this.c;
case 'd50': // D50 (ASTM E308-01)
return this.d50;
case 'd55': // D55 (ASTM E308-01)
return this.d55;
case 'd75': //D75 (ASTM E308-01)
return this.d75;
case 'e': // E (ASTM E308-01)
return this.e;
case 'f2': // F2 (ASTM E308-01)
return this.f2;
case 'f7': // F7 (ASTM E308-01)
return this.f7;
case 'f11': // F11 (ASTM E308-01)
return this.f11;
default: // D65 (ASTM E308-01)
return this.d65;
}
};
convert.a = {desc:'a', Y: 1.0, X: 1.09850, Z: 0.35585};
convert.b = {desc: 'b', Y: 1.0, X: 0.99072, Z: 0.85223};
convert.c = {desc: 'c', Y: 1.0, X: 0.98074, Z: 1.18232};
convert.d50 = {desc: 'd50', Y: 1.0, X: 0.96422, Z: 0.82521};
convert.d55 = {desc: 'd55', Y: 1.0, X: 0.95682, Z: 0.92149};
convert.d65 = {desc: 'd65', Y: 1.0, X: 0.95047, Z: 1.08883};
convert.d75 = {desc: 'd75', Y: 1.0, X: 0.94972, Z: 1.22638};
convert.e = {desc: 'e', Y: 1.0, X: 1.00000, Z: 1.00000};
convert.f2 = {desc: 'f2', Y: 1.0, X: 0.99186, Z: 0.67393};
convert.f7 = {desc: 'f7', Y: 1.0, X: 0.95041, Z: 1.08747};
convert.f11 = {desc: 'f11', Y: 1.0, X: 1.00962, Z: 0.64350};
/**
* Reverse lookup: given an XYZ illuminant (typically the output of a
* spectral integration) return the matching named whitepoint, or a
* synthesised one if no bundled illuminant matches within ±0.001.
*
* @param {{X:number, Y:number, Z:number}} illuminant
* @returns {_cmsWhitePoint}
*/
convert.getWhitePointFromIlluminant = function(illuminant){
if(t(illuminant.X, 1.0985)){ //A (ASTM E308-01)
return this.a;
}
if(t(illuminant.X, 0.9907)){ // B (Wyszecki & Stiles, p. 769))
return this.b;
}
if(t(illuminant.X, 0.98074)){ // C (ASTM E308-01)
return this.c;
}
if(t(illuminant.X, 0.96422)) { // D50 (ASTM E308-01)
return this.d50;
}
if(t(illuminant.X, 0.95682)) { // D55 (ASTM E308-01)
return this.d55;
}
if(t(illuminant.X, 0.94972)) { //D75 (ASTM E308-01)
return this.d75
}
if(t(illuminant.X, 1.00000)) { // E (ASTM E308-01)
return this.e;
}
if(t(illuminant.X, 0.99186)) { // F2 (ASTM E308-01)
return this.f2;
}
if(t(illuminant.X, 0.95041)) { // F7 (ASTM E308-01)
return this.f7;
}
if(t(illuminant.X, 1.00962)) { // F11 (ASTM E308-01)
return this.f11;
}
return {desc:'', Y: illuminant.Y , X: illuminant.X, Z: illuminant.Z};
function t(x,n){
var tolerance = 0.001;
return (x > (n-tolerance) && x < (n+tolerance));
}
};
// ============================================================================
// COLOUR-SPACE CONVERSIONS
// XYZ ↔ xyY ↔ Lab ↔ LCH (closed-form, no profile data needed)
// ============================================================================
/**
* XYZ → xyY chromaticity. If the XYZ sum is zero (pure black) the
* chromaticity is taken from `whitePoint` so the output isn't NaN.
*
* @param {_cmsXYZ} cmsXYZ
* @param {_cmsWhitePoint} whitePoint Used only for the black-fallback chromaticity.
* @returns {{x: number, y: number, Y: number}}
*/
convert.XYZ2xyY = function(cmsXYZ, whitePoint)
{
/** @type {number} den */
var den = cmsXYZ.X + cmsXYZ.Y + cmsXYZ.Z;
var xyY ={x:0,y:0,Y:0};
if (den > 0.0)
{
xyY.x = cmsXYZ.X / den;// TODO: Need to handle divide by zero
xyY.y = cmsXYZ.Y / den;
}
else
{
xyY.x = whitePoint.X / (whitePoint.X + 1 + whitePoint.Z);
xyY.y = 1 / (whitePoint.X + 1 + whitePoint.Z);
}
xyY.Y = cmsXYZ.Y;
return this.xyY(xyY.x,xyY.y,xyY.Y);
};
/**
* xyY → XYZ. Returns black if y is effectively zero (avoids divide-by-zero).
*
* @param {{x: number, y: number, Y: number}} cmsxyY
* @returns {_cmsXYZ}
*/
convert.xyY2XYZ = function(cmsxyY)
{
var X, Y, Z ;
if (cmsxyY.y < 0.000001)
{
X = Y = Z = 0.0;
}
else
{
X = (cmsxyY.x * cmsxyY.Y) / cmsxyY.y;
Y = cmsxyY.Y;
Z = ((1.0 - cmsxyY.x - cmsxyY.y) * cmsxyY.Y) / cmsxyY.y;
}
return this.XYZ(X,Y,Z);
};
/**
* XYZ → CIE Lab at the given whitepoint (CIE 15:2004).
*
* Uses the modern (TC1-48 corrected) constants: kE = 216/24389,
* kK = 24389/27. The whitepoint argument is REQUIRED — no D50 fallback —
* and the same whitepoint is attached to the result so any subsequent Lab→
* conversion can pick it up.
*
* @param {_cmsXYZ} XYZ
* @param {_cmsWhitePoint} whitePoint Reference white. NOT optional.
* @returns {_cmsLab}
*/
convert.XYZ2Lab = function(XYZ, whitePoint)
{
var kE = 216.0 / 24389.0;
var kK = 24389.0 / 27.0;
//var kKE = 8.0;
var xr = XYZ.X / whitePoint.X;
// yr: by convention, every whitepoint in this engine has Y === 1.0,
// so `XYZ.Y / whitePoint.Y` reduces to `XYZ.Y`. Don't "fix" this back.
var yr = XYZ.Y;
var zr = XYZ.Z / whitePoint.Z;
var fx = (xr > kE) ? Math.pow(xr, 1.0 / 3.0) : ((kK * xr + 16.0) / 116.0);
var fy = (yr > kE) ? Math.pow(yr, 1.0 / 3.0) : ((kK * yr + 16.0) / 116.0);
var fz = (zr > kE) ? Math.pow(zr, 1.0 / 3.0) : ((kK * zr + 16.0) / 116.0);
return {
L: 116.0 * fy - 16.0,
a: 500.0 * (fx - fy),
b: 200.0 * (fy - fz),
whitePoint: whitePoint,
type: eColourType.Lab
};
};
/**
* CIE Lab → XYZ. Uses `cmsLab.whitePoint` as the reference white (defaults
* to D50 if missing). Inverse of `XYZ2Lab`.
*
* @param {_cmsLab | _cmsLabD50} cmsLab
* @returns {_cmsXYZ}
*/
convert.Lab2XYZ = function(cmsLab)
{
var kE = 216.0 / 24389.0;
var kK = 24389.0 / 27.0;
var kKE = 8.0;
var fy = (cmsLab.L + 16.0) / 116.0;
var fx = 0.002 * cmsLab.a + fy;
var fz = fy - 0.005 * cmsLab.b;
var fx3 = fx * fx * fx;
var fz3 = fz * fz * fz;
var xr = (fx3 > kE) ? fx3 : ((116.0 * fx - 16.0) / kK);
var yr = (cmsLab.L > kKE) ? Math.pow((cmsLab.L + 16.0) / 116.0, 3.0) : (cmsLab.L / kK);
var zr = (fz3 > kE) ? fz3 : ((116.0 * fz - 16.0) / kK);
var whitePoint = cmsLab.whitePoint || this.d50;
return {
X: xr * whitePoint.X,
// Y: every whitepoint in this engine has Y === 1.0 by convention,
// so `yr * whitePoint.Y` reduces to `yr`. Don't "fix" this back.
Y: yr,
Z: zr * whitePoint.Z,
type: eColourType.XYZ
};
};
/**
* Adapt a Lab value into D50 Lab (the ICC PCS reference). Returns a stripped
* `{L,a,b}` (no whitepoint, no type) since the result is by definition D50.
*
* If the source is already at D50 (within tolerance) this is a near-no-op
* field copy — no XYZ round-trip.
*
* @param {_cmsLab} sourceLab
* @returns {_cmsLabD50}
*/
convert.Lab2LabD50 = function(sourceLab){
var destWhitepoint = this.d50
if( !this.compareWhitePoints(destWhitepoint, sourceLab.whitePoint)){
var XYZ = convert.Lab2XYZ(sourceLab);
XYZ = convert.adaptation(XYZ, sourceLab.whitePoint, destWhitepoint);
sourceLab = convert.XYZ2Lab(XYZ, destWhitepoint );
}
return {
L: sourceLab.L,
a: sourceLab.a,
b: sourceLab.b
}
};
/**
* Adapt a Lab value to a different reference whitepoint. Round-trips