Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add color spaces for Luv, LCHuv, HSLuv and HPLuv. #339

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions get/modules.json
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,33 @@
"id": "acescg",
"url": "https://en.wikipedia.org/wiki/Academy_Color_Encoding_System",
"description": "Scene-referred Academy Color Encoding System, using the wide gamut but physically realizable AP1 primaries and linear-light encoding. Used for physical rendering."
},
{
"name": "Luv",
"id": "luv",
"url": "https://en.wikipedia.org/wiki/CIELUV",
"description": ""
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does need a description, but that can be added later

},
{
"name": "LCHuv",
"id": "lchuv",
"dependencies": ["luv"],
"url": "https://en.wikipedia.org/wiki/CIELUV",
"description": "The polar (Hue, Chroma) form of CIE Luv."
},
{
"name": "HSLuv",
"id": "hsluv",
"dependencies": ["lchuv"],
"url": "https://www.hsluv.org/comparison/",
"description": "The HSLuv color space is a perceptually uniform adaptation of the traditional HSL (Hue, Saturation, Lightness) color model. Engineered upon the foundations of the CIELUV color space, HSLuv ensures that colors that appear equally spaced in its representation also present consistent perceptual differences to the human observer. This results in a color space where changes in hue, saturation, or lightness produce predictable and coherent visual outcomes, addressing inconsistencies and unpredictable color shifts often found in standard HSL."
},
{
"name": "HPLuv",
"id": "hpluv",
"dependencies": ["lchuv"],
"url": "https://www.hsluv.org/comparison/",
"description": "The HPLuv color space emphasizes perceptual uniformity specifically in its lightness component. HPLuv ensures that changes in lightness are consistently perceived by the human eye, regardless of the hue or saturation of the color. The resulting palette is a subset of sRGB and the colors are mainly pastel."
}
],
"optional": [
Expand Down
99 changes: 59 additions & 40 deletions src/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,56 @@ import ColorSpace from "./space.js";

const noneTypes = new Set(["<number>", "<percentage>", "<angle>"]);

/**
* Validates the coordinates of a color against a format's coord grammar and
* maps the coordinates to the range or refRange of the coordinates.
* @param {ColorSpace} space - Colorspace the coords are in
* @param {object} format - the format object to validate against
* @param {string} name - the name of the color function. e.g. "oklab" or "color"
* @returns {object[]} - an array of type metadata for each coordinate
*/
function coerceCoords (space, format, name, coords) {
let types = Object.entries(space.coords).map(([id, coordMeta], i) => {
let coordGrammar = format.coordGrammar[i];
let arg = coords[i];
let providedType = arg?.type;

// Find grammar alternative that matches the provided type
// Non-strict equals is intentional because we are comparing w/ string objects
let type;
if (arg.none) {
type = coordGrammar.find(c => noneTypes.has(c));
}
else {
type = coordGrammar.find(c => c == providedType);
}

// Check that each coord conforms to its grammar
if (!type) {
// Type does not exist in the grammar, throw
let coordName = coordMeta.name || id;
throw new TypeError(`${providedType ?? arg.raw} not allowed for ${coordName} in ${name}()`);
}

let fromRange = type.range;

if (providedType === "<percentage>") {
fromRange ||= [0, 1];
}

let toRange = coordMeta.range || coordMeta.refRange;

if (fromRange && toRange) {
coords[i] = util.mapRange(fromRange, toRange, coords[i]);
}

return type;
});

return types;
}


/**
* Convert a CSS Color string to a color object
* @param {string} str
Expand All @@ -24,7 +74,6 @@ export default function parse (str, {meta} = {}) {
if (env.parsed) {
// Is a functional syntax
let name = env.parsed.name;

if (name === "color") {
// color() function
let id = env.parsed.args.shift();
Expand All @@ -40,8 +89,14 @@ export default function parse (str, {meta} = {}) {
// If less <number>s or <percentage>s are provided than parameters that the colorspace takes, the missing parameters default to 0. (This is particularly convenient for multichannel printers where the additional inks are spot colors or varnishes that most colors on the page won’t use.)
const coords = Object.keys(space.coords).map((_, i) => env.parsed.args[i] || 0);

let types;

if (colorSpec.coordGrammar) {
types = coerceCoords(space, colorSpec, "color", coords);
}

if (meta) {
meta.formatId = "color";
Object.assign(meta, {formatId: "color", types});
}

return {spaceId: space.id, coords, alpha};
Expand Down Expand Up @@ -74,46 +129,10 @@ export default function parse (str, {meta} = {}) {
}

let coords = env.parsed.args;

let types;

if (format.coordGrammar) {
types = Object.entries(space.coords).map(([id, coordMeta], i) => {
let coordGrammar = format.coordGrammar[i];
let arg = coords[i];
let providedType = arg?.type;

// Find grammar alternative that matches the provided type
// Non-strict equals is intentional because we are comparing w/ string objects
let type;
if (arg.none) {
type = coordGrammar.find(c => noneTypes.has(c));
}
else {
type = coordGrammar.find(c => c == providedType);
}

// Check that each coord conforms to its grammar
if (!type) {
// Type does not exist in the grammar, throw
let coordName = coordMeta.name || id;
throw new TypeError(`${providedType ?? arg.raw} not allowed for ${coordName} in ${name}()`);
}

let fromRange = type.range;

if (providedType === "<percentage>") {
fromRange ||= [0, 1];
}

let toRange = coordMeta.range || coordMeta.refRange;

if (fromRange && toRange) {
coords[i] = util.mapRange(fromRange, toRange, coords[i]);
}

return type;
});
types = coerceCoords(space, format, name, coords);
}

if (meta) {
Expand Down Expand Up @@ -160,4 +179,4 @@ export default function parse (str, {meta} = {}) {

// If we're here, we couldn't parse
throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`);
}
}
20 changes: 19 additions & 1 deletion src/space.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ export default class ColorSpace {
this.toBase = options.toBase;
}

if (options.gamutCheck) {
if (options.gamutCheck === "self") {
this.gamutCheck = this;
}
else {
this.gamutCheck = ColorSpace.get(options.gamutCheck);
}
}

// Coordinate metadata

let coords = options.coords ?? this.base.coords;
Expand Down Expand Up @@ -68,8 +77,17 @@ export default class ColorSpace {
}

inGamut (coords, {epsilon = ε} = {}) {
if (this.isPolar) {
// If the gamutCheck space is specified and not ourself then
// use the gamutCheck space to check if the coords are in gamut
if (this.gamutCheck && !this.equals(this.gamutCheck)) {
coords = this.to(this.gamutCheck, coords);
return this.gamutCheck.inGamut(coords, {epsilon});
}

if (this.isPolar && !this.equals(this.gamutCheck)) {
// Do not check gamut through polar coordinates
// unless this space is the gamutCheck space

coords = this.toBase(coords);

return this.base.inGamut(coords, {epsilon});
Expand Down
129 changes: 129 additions & 0 deletions src/spaces/hpluv.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts

Copyright (c) 2012-2022 Alexei Boronine

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import ColorSpace from "../space.js";
import LCHuv from "./lchuv.js";
import {fromXYZ_M} from "./srgb-linear.js";
import {calculateBoundingLines} from "./hsluv.js";

const ε = 216/24389; // 6^3/29^3 == (24/116)^3
const κ = 24389/27; // 29^3/3^3

const m_r0 = fromXYZ_M[0][0];
const m_r1 = fromXYZ_M[0][1];
const m_r2 = fromXYZ_M[0][2];
const m_g0 = fromXYZ_M[1][0];
const m_g1 = fromXYZ_M[1][1];
const m_g2 = fromXYZ_M[1][2];
const m_b0 = fromXYZ_M[2][0];
const m_b1 = fromXYZ_M[2][1];
const m_b2 = fromXYZ_M[2][2];

function distanceFromOrigin (slope, intercept) {
return Math.abs(intercept) / Math.sqrt(Math.pow(slope, 2) + 1);
}

function calcMaxChromaHpluv (lines) {
let r0 = distanceFromOrigin(lines.r0s, lines.r0i);
let r1 = distanceFromOrigin(lines.r1s, lines.r1i);
let g0 = distanceFromOrigin(lines.g0s, lines.g0i);
let g1 = distanceFromOrigin(lines.g1s, lines.g1i);
let b0 = distanceFromOrigin(lines.b0s, lines.b0i);
let b1 = distanceFromOrigin(lines.b1s, lines.b1i);

return Math.min(r0, r1, g0, g1, b0, b1);
}

export default new ColorSpace({
id: "hpluv",
name: "HPLuv",
coords: {
h: {
refRange: [0, 360],
type: "angle",
name: "Hue"
},
s: {
range: [0, 100],
name: "Saturation"
},
l: {
range: [0, 100],
name: "Lightness"
}
},

base: LCHuv,
gamutCheck: "self",

// Convert LCHuv to HPLuv
fromBase (lch) {
let [L, c, h] = lch;
let s, l;

if (L > 99.9999999) {
s = 0;
l = 100;
}
else if (L < 0.00000001) {
s = 0;
l = 0;
}
else {
let lines = calculateBoundingLines(L);
let max = calcMaxChromaHpluv(lines);
s = c / max * 100;
l = L;
}
return [h, s, l];
},

// Convert HPLuv to LCHuv
toBase (hsl) {
let [h, s, l] = hsl;
let L, c;
if (l > 99.9999999) {
L = 100;
c = 0;
}
else if (l < 0.00000001) {
L = 0;
c = 0;
}
else {
L = l;
let lines = calculateBoundingLines(L);
let max = calcMaxChromaHpluv(lines, h);
c = max / 100 * s;
}
return [L, c, h];
},

formats: {
color: {
id: "--hpluv",
coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
}
},
});
Loading
Loading