| 1 |
import * as util from "./util.js"; |
| 2 |
import ColorSpace from "./ColorSpace.js"; |
| 3 |
import defaults from "./defaults.js"; |
| 4 |
import deltaE2000 from "./deltaE/deltaE2000.js"; |
| 5 |
import deltaEOK from "./deltaE/deltaEOK.js"; |
| 6 |
import inGamut from "./inGamut.js"; |
| 7 |
import to from "./to.js"; |
| 8 |
import get from "./get.js"; |
| 9 |
import oklab from "./spaces/oklab.js"; |
| 10 |
import oklch from "./spaces/oklch.js"; |
| 11 |
import set from "./set.js"; |
| 12 |
import clone from "./clone.js"; |
| 13 |
import getColor from "./getColor.js"; |
| 14 |
import deltaEMethods from "./deltaE/index.js"; |
| 15 |
import { WHITES } from "./adapt.js"; |
| 16 |
import RGBColorSpace from "./RGBColorSpace.js"; |
| 17 |
|
| 18 |
/** @import { ColorTypes, PlainColorObject } from "./types.js" */ |
| 19 |
|
| 20 |
// Type re-exports |
| 21 |
/** @typedef {import("./types.js").ToGamutOptions} ToGamutOptions */ |
| 22 |
|
| 23 |
/** |
| 24 |
* Calculate the epsilon to 2 degrees smaller than the specified JND. |
| 25 |
* @param {number} jnd The target "just noticeable difference". |
| 26 |
* @returns {number} |
| 27 |
*/ |
| 28 |
function calcEpsilon (jnd) { |
| 29 |
// Calculate the epsilon to 2 degrees smaller than the specified JND. |
| 30 |
|
| 31 |
const order = !jnd ? 0 : Math.floor(Math.log10(Math.abs(jnd))); |
| 32 |
// Limit to an arbitrary value to ensure value is never too small and causes infinite loops. |
| 33 |
return Math.max(parseFloat(`1e${order - 2}`), 1e-6); |
| 34 |
} |
| 35 |
|
| 36 |
const GMAPPRESET = { |
| 37 |
hct: { |
| 38 |
method: "hct.c", |
| 39 |
jnd: 2, |
| 40 |
deltaEMethod: "hct", |
| 41 |
blackWhiteClamp: {}, |
| 42 |
}, |
| 43 |
"hct-tonal": { |
| 44 |
method: "hct.c", |
| 45 |
jnd: 0, |
| 46 |
deltaEMethod: "hct", |
| 47 |
blackWhiteClamp: { channel: "hct.t", min: 0, max: 100 }, |
| 48 |
}, |
| 49 |
}; |
| 50 |
|
| 51 |
/** |
| 52 |
* Force coordinates to be in gamut of a certain color space. |
| 53 |
* Mutates the color it is passed. |
| 54 |
* @overload |
| 55 |
* @param {ColorTypes} color |
| 56 |
* @param {ToGamutOptions} [options] |
| 57 |
* @returns {PlainColorObject} |
| 58 |
*/ |
| 59 |
/** |
| 60 |
* @overload |
| 61 |
* @param {ColorTypes} color |
| 62 |
* @param {string} [space] |
| 63 |
* @returns {PlainColorObject} |
| 64 |
*/ |
| 65 |
/** |
| 66 |
* @param {ColorTypes} color |
| 67 |
* @param {string & Partial<ToGamutOptions> | ToGamutOptions} [space] |
| 68 |
* @returns {PlainColorObject} |
| 69 |
*/ |
| 70 |
export default function toGamut ( |
| 71 |
color, |
| 72 |
{ |
| 73 |
method = defaults.gamut_mapping, |
| 74 |
space = undefined, |
| 75 |
deltaEMethod = "", |
| 76 |
jnd = 2, |
| 77 |
blackWhiteClamp = undefined, |
| 78 |
} = {}, |
| 79 |
) { |
| 80 |
color = getColor(color); |
| 81 |
|
| 82 |
if (util.isString(arguments[1])) { |
| 83 |
space = arguments[1]; |
| 84 |
} |
| 85 |
else if (!space) { |
| 86 |
space = color.space; |
| 87 |
} |
| 88 |
|
| 89 |
space = ColorSpace.get(space); |
| 90 |
|
| 91 |
// 3 spaces: |
| 92 |
// color.space: current color space |
| 93 |
// space: space whose gamut we are mapping to |
| 94 |
// mapSpace: space with the coord we're reducing |
| 95 |
|
| 96 |
if (inGamut(color, space, { epsilon: 0 })) { |
| 97 |
return /** @type {PlainColorObject} */ (color); |
| 98 |
} |
| 99 |
|
| 100 |
let spaceColor; |
| 101 |
if (method === "css") { |
| 102 |
spaceColor = toGamutCSS(color, { space }); |
| 103 |
} |
| 104 |
else if (method === "raytrace") { |
| 105 |
spaceColor = toGamutRayTrace(color, { space }); |
| 106 |
} |
| 107 |
else { |
| 108 |
if (method !== "clip") { |
| 109 |
if (Object.prototype.hasOwnProperty.call(GMAPPRESET, method)) { |
| 110 |
({ method, jnd, deltaEMethod, blackWhiteClamp } = GMAPPRESET[method]); |
| 111 |
} |
| 112 |
|
| 113 |
// Get the correct delta E method |
| 114 |
let de = deltaE2000; |
| 115 |
if (deltaEMethod !== "") { |
| 116 |
for (let m in deltaEMethods) { |
| 117 |
if ("deltae" + deltaEMethod.toLowerCase() === m.toLowerCase()) { |
| 118 |
de = deltaEMethods[m]; |
| 119 |
break; |
| 120 |
} |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
if (jnd === 0) { |
| 125 |
jnd = 1e-16; |
| 126 |
} |
| 127 |
|
| 128 |
let clipped = toGamut(to(color, space), { method: "clip", space }); |
| 129 |
if (de(color, clipped) > jnd) { |
| 130 |
// Clamp to SDR white and black if required |
| 131 |
if (blackWhiteClamp && Object.keys(blackWhiteClamp).length === 3) { |
| 132 |
let channelMeta = ColorSpace.resolveCoord(blackWhiteClamp.channel); |
| 133 |
let channel = get(to(color, channelMeta.space), channelMeta.id); |
| 134 |
if (util.isNone(channel)) { |
| 135 |
channel = 0; |
| 136 |
} |
| 137 |
if (channel >= blackWhiteClamp.max) { |
| 138 |
return to({ space: "xyz-d65", coords: WHITES["D65"] }, color.space); |
| 139 |
} |
| 140 |
else if (channel <= blackWhiteClamp.min) { |
| 141 |
return to({ space: "xyz-d65", coords: [0, 0, 0] }, color.space); |
| 142 |
} |
| 143 |
} |
| 144 |
|
| 145 |
// Reduce a coordinate of a certain color space until the color is in gamut |
| 146 |
let coordMeta = ColorSpace.resolveCoord(method); |
| 147 |
let mapSpace = coordMeta.space; |
| 148 |
let coordId = coordMeta.id; |
| 149 |
|
| 150 |
let mappedColor = to(color, mapSpace); |
| 151 |
// If we were already in the mapped color space, we need to resolve undefined channels |
| 152 |
mappedColor.coords.forEach((c, i) => { |
| 153 |
if (util.isNone(c)) { |
| 154 |
mappedColor.coords[i] = 0; |
| 155 |
} |
| 156 |
}); |
| 157 |
let bounds = coordMeta.range || coordMeta.refRange; |
| 158 |
let min = bounds[0]; |
| 159 |
let ε = calcEpsilon(jnd); |
| 160 |
let low = min; |
| 161 |
let high = get(mappedColor, coordId); |
| 162 |
|
| 163 |
while (high - low > ε) { |
| 164 |
let clipped = clone(mappedColor); |
| 165 |
clipped = toGamut(clipped, { space, method: "clip" }); |
| 166 |
let deltaE = de(mappedColor, clipped); |
| 167 |
|
| 168 |
if (deltaE - jnd < ε) { |
| 169 |
low = get(mappedColor, coordId); |
| 170 |
} |
| 171 |
else { |
| 172 |
high = get(mappedColor, coordId); |
| 173 |
} |
| 174 |
|
| 175 |
set(mappedColor, coordId, (low + high) / 2); |
| 176 |
} |
| 177 |
|
| 178 |
spaceColor = to(mappedColor, space); |
| 179 |
} |
| 180 |
else { |
| 181 |
spaceColor = clipped; |
| 182 |
} |
| 183 |
} |
| 184 |
else { |
| 185 |
spaceColor = to(color, space); |
| 186 |
} |
| 187 |
|
| 188 |
if ( |
| 189 |
method === "clip" || // Dumb coord clipping |
| 190 |
// finish off smarter gamut mapping with clip to get rid of ε, see #17 |
| 191 |
!inGamut(spaceColor, space, { epsilon: 0 }) |
| 192 |
) { |
| 193 |
let bounds = Object.values(space.coords).map(c => c.range || []); |
| 194 |
|
| 195 |
spaceColor.coords = /** @type {[number, number, number]} */ ( |
| 196 |
spaceColor.coords.map((c, i) => { |
| 197 |
let [min, max] = bounds[i]; |
| 198 |
|
| 199 |
if (min !== undefined) { |
| 200 |
c = Math.max(min, c); |
| 201 |
} |
| 202 |
|
| 203 |
if (max !== undefined) { |
| 204 |
c = Math.min(c, max); |
| 205 |
} |
| 206 |
|
| 207 |
return c; |
| 208 |
}) |
| 209 |
); |
| 210 |
} |
| 211 |
} |
| 212 |
|
| 213 |
if (space !== color.space) { |
| 214 |
spaceColor = to(spaceColor, color.space); |
| 215 |
} |
| 216 |
|
| 217 |
color.coords = spaceColor.coords; |
| 218 |
return /** @type {PlainColorObject} */ (color); |
| 219 |
} |
| 220 |
|
| 221 |
/** @type {"color"} */ |
| 222 |
toGamut.returns = "color"; |
| 223 |
|
| 224 |
/** |
| 225 |
* The reference colors to be used if lightness is out of the range 0-1 in the |
| 226 |
* `Oklch` space. These are created in the `Oklab` space, as it is used by the |
| 227 |
* DeltaEOK calculation, so it is guaranteed to be imported. |
| 228 |
* @satisfies {Record<string, ColorTypes>} |
| 229 |
*/ |
| 230 |
const COLORS = { |
| 231 |
WHITE: { space: oklab, coords: [1, 0, 0], alpha: 1 }, |
| 232 |
BLACK: { space: oklab, coords: [0, 0, 0], alpha: 1 }, |
| 233 |
}; |
| 234 |
|
| 235 |
/** |
| 236 |
* Given a color `origin`, returns a new color that is in gamut using |
| 237 |
* the CSS Gamut Mapping Algorithm. If `space` is specified, it will be in gamut |
| 238 |
* in `space`, and returned in `space`. Otherwise, it will be in gamut and |
| 239 |
* returned in the color space of `origin`. |
| 240 |
* @param {ColorTypes} origin |
| 241 |
* @param {{ space?: string | ColorSpace | undefined }} options |
| 242 |
* @returns {PlainColorObject} |
| 243 |
*/ |
| 244 |
export function toGamutCSS (origin, { space } = {}) { |
| 245 |
const JND = 0.02; |
| 246 |
const ε = 0.0001; |
| 247 |
|
| 248 |
origin = getColor(origin); |
| 249 |
|
| 250 |
if (!space) { |
| 251 |
space = origin.space; |
| 252 |
} |
| 253 |
|
| 254 |
space = ColorSpace.get(space); |
| 255 |
|
| 256 |
if (space.isUnbounded) { |
| 257 |
return to(origin, space); |
| 258 |
} |
| 259 |
|
| 260 |
const origin_OKLCH = to(origin, oklch); |
| 261 |
let L = origin_OKLCH.coords[0]; |
| 262 |
|
| 263 |
// return media white or black, if lightness is out of range |
| 264 |
if (L >= 1) { |
| 265 |
const white = to(COLORS.WHITE, space); |
| 266 |
white.alpha = origin.alpha; |
| 267 |
return to(white, space); |
| 268 |
} |
| 269 |
if (L <= 0) { |
| 270 |
const black = to(COLORS.BLACK, space); |
| 271 |
black.alpha = origin.alpha; |
| 272 |
return to(black, space); |
| 273 |
} |
| 274 |
|
| 275 |
if (inGamut(origin_OKLCH, space, { epsilon: 0 })) { |
| 276 |
return to(origin_OKLCH, space); |
| 277 |
} |
| 278 |
|
| 279 |
function clip (_color) { |
| 280 |
const destColor = to(_color, space); |
| 281 |
const spaceCoords = Object.values(/** @type {ColorSpace} */ (space).coords); |
| 282 |
destColor.coords = /** @type {[number, number, number]} */ ( |
| 283 |
destColor.coords.map((coord, index) => { |
| 284 |
if ("range" in spaceCoords[index]) { |
| 285 |
const [min, max] = spaceCoords[index].range; |
| 286 |
return util.clamp(min, coord, max); |
| 287 |
} |
| 288 |
return coord; |
| 289 |
}) |
| 290 |
); |
| 291 |
return destColor; |
| 292 |
} |
| 293 |
let min = 0; |
| 294 |
let max = origin_OKLCH.coords[1]; |
| 295 |
let min_inGamut = true; |
| 296 |
let current = clone(origin_OKLCH); |
| 297 |
let clipped = clip(current); |
| 298 |
|
| 299 |
let E = deltaEOK(clipped, current); |
| 300 |
if (E < JND) { |
| 301 |
return clipped; |
| 302 |
} |
| 303 |
|
| 304 |
while (max - min > ε) { |
| 305 |
const chroma = (min + max) / 2; |
| 306 |
current.coords[1] = chroma; |
| 307 |
if (min_inGamut && inGamut(current, space, { epsilon: 0 })) { |
| 308 |
min = chroma; |
| 309 |
} |
| 310 |
else { |
| 311 |
clipped = clip(current); |
| 312 |
E = deltaEOK(clipped, current); |
| 313 |
if (E < JND) { |
| 314 |
if (JND - E < ε) { |
| 315 |
break; |
| 316 |
} |
| 317 |
else { |
| 318 |
min_inGamut = false; |
| 319 |
min = chroma; |
| 320 |
} |
| 321 |
} |
| 322 |
else { |
| 323 |
max = chroma; |
| 324 |
} |
| 325 |
} |
| 326 |
} |
| 327 |
return clipped; |
| 328 |
} |
| 329 |
|
| 330 |
/** |
| 331 |
* Given `start` and `end` coordinates of a 3D ray and a `bmin` and `bmax` bounding box, |
| 332 |
* find the intersection of the ray and box. Return an empty list if no intersect is found.` |
| 333 |
* @param {[number, number, number]} start |
| 334 |
* @param {[number, number, number]} end |
| 335 |
* @param {[number, number, number]} bmin |
| 336 |
* @param {[number, number, number]} bmax |
| 337 |
* @returns {[number, number, number] | []} |
| 338 |
*/ |
| 339 |
function raytrace_box (start, end, bmin = [0, 0, 0], bmax = [1, 1, 1]) { |
| 340 |
// Use slab method to detect intersection of ray and box and return intersect. |
| 341 |
// https://en.wikipedia.org/wiki/Slab_method |
| 342 |
|
| 343 |
// Calculate whether there was a hit |
| 344 |
let tfar = Infinity; |
| 345 |
let tnear = -Infinity; |
| 346 |
let direction = []; |
| 347 |
|
| 348 |
for (let i = 0; i < 3; i++) { |
| 349 |
const a = start[i]; |
| 350 |
const b = end[i]; |
| 351 |
const d = b - a; |
| 352 |
const bn = bmin[i]; |
| 353 |
const bx = bmax[i]; |
| 354 |
direction.push(d); |
| 355 |
|
| 356 |
// Non parallel cases |
| 357 |
// 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types |
| 358 |
if (Math.abs(d) > 1e-12) { |
| 359 |
const inv_d = 1 / d; |
| 360 |
const t1 = (bn - a) * inv_d; |
| 361 |
const t2 = (bx - a) * inv_d; |
| 362 |
tnear = Math.max(Math.min(t1, t2), tnear); |
| 363 |
tfar = Math.min(Math.max(t1, t2), tfar); |
| 364 |
} |
| 365 |
|
| 366 |
// Impossible parallel case |
| 367 |
else if (a < bn || a > bx) { |
| 368 |
return []; |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
// No hit |
| 373 |
if (tnear > tfar || tfar < 0) { |
| 374 |
return []; |
| 375 |
} |
| 376 |
|
| 377 |
// Favor the intersection first in the direction start -> end |
| 378 |
if (tnear < 0) { |
| 379 |
tnear = tfar; |
| 380 |
} |
| 381 |
|
| 382 |
// A point, or something approaching a single point where start and end are the same. |
| 383 |
if (!isFinite(tnear)) { |
| 384 |
return []; |
| 385 |
} |
| 386 |
|
| 387 |
// Calculate nearest intersection via interpolation |
| 388 |
return [ |
| 389 |
start[0] + direction[0] * tnear, |
| 390 |
start[1] + direction[1] * tnear, |
| 391 |
start[2] + direction[2] * tnear, |
| 392 |
]; |
| 393 |
} |
| 394 |
|
| 395 |
/** |
| 396 |
* Given a color `origin`, returns a new color that is in gamut using |
| 397 |
* the CSS Ray Trace Gamut Mapping Algorithm. If `space` is specified, |
| 398 |
* it will be in gamut `space`, and returned in `space`. Otherwise, |
| 399 |
* it will be in gamut and returned in the color space of `origin`. |
| 400 |
* @param {ColorTypes} origin |
| 401 |
* @param {{ space?: string | ColorSpace | undefined }} options |
| 402 |
* @returns {PlainColorObject} |
| 403 |
*/ |
| 404 |
export function toGamutRayTrace (origin, { space } = {}) { |
| 405 |
origin = getColor(origin); |
| 406 |
|
| 407 |
if (!space) { |
| 408 |
space = origin.space; |
| 409 |
} |
| 410 |
|
| 411 |
space = ColorSpace.get(space); |
| 412 |
|
| 413 |
// If the space is already in gamut, stop. |
| 414 |
if (space.isUnbounded) { |
| 415 |
return to(origin, space); |
| 416 |
} |
| 417 |
|
| 418 |
// Get the OkLCh coordinates. |
| 419 |
let oklchOrigin = to(origin, oklch); |
| 420 |
let [lightness, chroma, hue] = oklchOrigin.coords; |
| 421 |
|
| 422 |
// Return white or black if color's lightness exceeds the SDR range. |
| 423 |
if (lightness >= 1) { |
| 424 |
const white = to(COLORS.WHITE, space); |
| 425 |
white.alpha = origin.alpha; |
| 426 |
return to(white, space); |
| 427 |
} |
| 428 |
else if (lightness <= 0) { |
| 429 |
const black = to(COLORS.BLACK, space); |
| 430 |
black.alpha = origin.alpha; |
| 431 |
return to(black, space); |
| 432 |
} |
| 433 |
|
| 434 |
// Get a copy of the origin color as the RGB target space. |
| 435 |
const originSpace = space; |
| 436 |
const rGamut = space.rgbGamut; |
| 437 |
if (rGamut !== undefined) { |
| 438 |
space = rGamut; |
| 439 |
} |
| 440 |
|
| 441 |
if (!util.isInstance(space, RGBColorSpace)) { |
| 442 |
throw Error('An RGB gamut is required') |
| 443 |
} |
| 444 |
|
| 445 |
// Get SDR bounds. Some HDR spaces have headroom, so reduce max to SDR range. |
| 446 |
let [mn, mx] = Object.values(space.coords)[0].range; |
| 447 |
let max = /** @type {[number, number, number]} */ ([mx, mx, mx]); |
| 448 |
|
| 449 |
// See if we have a linear version of the color space |
| 450 |
const lGamut = space.linearGamut; |
| 451 |
if (lGamut !== undefined) { |
| 452 |
// Recalculate minimum and maximum relative to the linear space |
| 453 |
let temp = to({ space: space, coords: max, alpha: origin.alpha }, lGamut); |
| 454 |
mx = temp.coords[0]; |
| 455 |
max = /** @type {[number, number, number]} */ ([mx, mx, mx]); |
| 456 |
space = lGamut; |
| 457 |
mn = Object.values(space.coords)[0].range[0]; |
| 458 |
} |
| 459 |
let min = /** @type {[number, number, number]} */ ([mn, mn, mn]); |
| 460 |
let rgbOrigin = to(oklchOrigin, space); |
| 461 |
|
| 462 |
if (!rgbOrigin.coords.every(x => mn <= x && x <= mx)) { |
| 463 |
// If this were performed within a perceptual space like CAM16, which has achromatics that do not align |
| 464 |
// with the RGB achromatic line, projecting the color onto the RGB achromatic line may be preferable, |
| 465 |
// but since OkLCh's achromatics align with all CSS RGB spaces, just set chroma to zero. |
| 466 |
let anchor = to({ space: oklch, coords: [lightness, 0, hue] }, space).coords; |
| 467 |
|
| 468 |
// Calculate bounds to adjust the anchor closer to the gamut surface. |
| 469 |
// We don't want to make the ray too short, so offset some amount from the low and high range. |
| 470 |
// 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types. |
| 471 |
const low = mn + 1e-12; |
| 472 |
const high = mx - 1e-12; |
| 473 |
|
| 474 |
// Cast a ray from the zero chroma color to the target color. |
| 475 |
// Trace the line to the RGB cube edge and find where it intersects. |
| 476 |
// Correct L and h within the perceptual OkLCh after each attempt. |
| 477 |
let last = rgbOrigin.coords; |
| 478 |
for (let i = 0; i < 4; i++) { |
| 479 |
if (i) { |
| 480 |
// For constant luminance, we correct the color by simply setting lightness and hue to |
| 481 |
// match the original color. In a non constant luminance reduction, it is better to |
| 482 |
// project the color onto the reduction path vector. |
| 483 |
const oklchColor = to(rgbOrigin, oklch); |
| 484 |
oklchColor.coords[0] = lightness; |
| 485 |
oklchColor.coords[2] = hue; |
| 486 |
rgbOrigin = to(oklchColor, space); |
| 487 |
} |
| 488 |
// Cast a ray from the achromatic anchor to the RGB target and find the gamut intersection. |
| 489 |
const intersection = raytrace_box(anchor, rgbOrigin.coords, min, max); |
| 490 |
|
| 491 |
// If we cannot find an intersection, reset to last successful iteration of the color. |
| 492 |
// In OkLCh, this is only likely to happen if our ray gets too small, in that case, it is time to stop. |
| 493 |
if (intersection.length === 0) { |
| 494 |
rgbOrigin.coords = [...last]; |
| 495 |
break; |
| 496 |
} |
| 497 |
|
| 498 |
// Adjust anchor point closer to surface, when possible, to improve results for some spaces. |
| 499 |
if (i && rgbOrigin.coords.every(x => low < x && x < high)) { |
| 500 |
anchor = [...rgbOrigin.coords]; |
| 501 |
} |
| 502 |
|
| 503 |
// If we have an intersection, update the color. |
| 504 |
last = /** @type {[number, number, number]} */ (intersection); |
| 505 |
rgbOrigin.coords = [...intersection]; |
| 506 |
} |
| 507 |
} |
| 508 |
|
| 509 |
// Convert to the original, specified gamut |
| 510 |
rgbOrigin = to(rgbOrigin, originSpace) |
| 511 |
const spaceCoords = Object.values(/** @type {ColorSpace} */ (originSpace).coords); |
| 512 |
|
| 513 |
// Remove noise from floating point math by clipping |
| 514 |
rgbOrigin.coords = /** @type {[number, number, number]} */ ( |
| 515 |
rgbOrigin.coords.map((coord, index) => { |
| 516 |
if ("range" in spaceCoords[index]) { |
| 517 |
const [lower, upper] = spaceCoords[index].range; |
| 518 |
return util.clamp(lower, coord, upper); |
| 519 |
} |
| 520 |
return coord; |
| 521 |
}) |
| 522 |
); |
| 523 |
|
| 524 |
return rgbOrigin; |
| 525 |
} |