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 CSS Color 4 syntax support, color interpolation changes #94

Merged
merged 8 commits into from
Apr 11, 2023
Merged
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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
## main

### ✨ Features and improvements

* Add support for defining colors using CSS Color 4 syntax [#94](https://github.com/maplibre/maplibre-style/pull/94)
* [Breaking] Interpretation of interpolation of colors with alpha channel equal to 0 has changed. When interpolating colors with alpha channel equal to 0, the values of the other color channels in the specified color space are included in the calculation. Previously they were ignored and only the alpha value of the other, not fully transparent, color was interpolated. [#94](https://github.com/maplibre/maplibre-style/pull/94)

### 🐛 Bug fixes

* Fix incorrect color interpolation in HCL and LAB color spaces when interpolation results are outside the sRGB gamut. [#94](https://github.com/maplibre/maplibre-style/pull/94)

## 18.0.0
* maplibre-gl-style-spec now has it's own repository. The major bump is mainly a precautionary measure, in case the restructuring causes friction.

Expand Down
8 changes: 4 additions & 4 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import type {Config} from 'jest';

const sharedConfig = {
const sharedConfig: Partial<Config> = {
transform: {
// use typescript to convert from esm to cjs
'[.](m|c)?(ts|js)(x)?$': ['ts-jest', {
'isolatedModules': true,
isolatedModules: true,
}],
},
// any tests that operate on dist files shouldn't compile them again.
transformIgnorePatterns: ['<rootDir>/dist']
} as Partial<Config>;
transformIgnorePatterns: ['<rootDir>/dist'],
};

const config: Config = {
projects: [
Expand Down
32 changes: 24 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"@mapbox/point-geometry": "^0.1.0",
"@mapbox/unitbezier": "^0.0.1",
"@types/mapbox__point-geometry": "^0.1.2",
"csscolorparser": "~1.0.3",
"color-string": "^1.9.1",
"json-stringify-pretty-compact": "^3.0.0",
"minimist": "^1.2.8",
"rw": "^1.3.3",
Expand Down
7 changes: 4 additions & 3 deletions src/expression/definitions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ function rgba(ctx, [r, g, b, a]) {
const alpha = a ? a.evaluate(ctx) : 1;
const error = validateRGBA(r, g, b, alpha);
if (error) throw new RuntimeError(error);
return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha);
return new Color(r / 255, g / 255, b / 255, alpha, false);
}

function has(key, obj) {
Expand Down Expand Up @@ -138,8 +138,9 @@ CompoundExpression.register(expressions, {
array(NumberType, 4),
[ColorType],
(ctx, [v]) => {
return v.evaluate(ctx).toArray();
}
const [r, g, b, a] = v.evaluate(ctx).rgb;
return [r * 255, g * 255, b * 255, a];
},
],
'rgb': [
ColorType,
Expand Down
37 changes: 17 additions & 20 deletions src/expression/definitions/interpolate.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import UnitBezier from '@mapbox/unitbezier';

import * as interpolate from '../../util/interpolate';
import {toString, NumberType, ColorType} from '../types';
import interpolate from '../../util/interpolate';
import {array, ArrayType, ColorType, ColorTypeT, NumberType, NumberTypeT, PaddingType, PaddingTypeT, toString, verifyType} from '../types';
import {findStopLessThanOrEqualTo} from '../stops';
import {hcl, lab} from '../../util/color_spaces';

import type {Stops} from '../stops';
import type {Expression} from '../expression';
Expand All @@ -20,17 +19,18 @@ export type InterpolationType = {
name: 'cubic-bezier';
controlPoints: [number, number, number, number];
};
type InterpolatedValueType = NumberTypeT | ColorTypeT | PaddingTypeT | ArrayType<NumberTypeT>;

class Interpolate implements Expression {
type: Type;
type: InterpolatedValueType;

operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab';
interpolation: InterpolationType;
input: Expression;
labels: Array<number>;
outputs: Array<Expression>;

constructor(type: Type, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) {
constructor(type: InterpolatedValueType, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) {
this.type = type;
this.operator = operator;
this.interpolation = interpolation;
Expand Down Expand Up @@ -133,14 +133,10 @@ class Interpolate implements Expression {
stops.push([label, parsed]);
}

if (outputType.kind !== 'number' &&
outputType.kind !== 'color' &&
outputType.kind !== 'padding' &&
!(
outputType.kind === 'array' &&
outputType.itemType.kind === 'number' &&
typeof outputType.N === 'number'
)
if (!verifyType(outputType, NumberType) &&
!verifyType(outputType, ColorType) &&
!verifyType(outputType, PaddingType) &&
!verifyType(outputType, array(NumberType))
) {
return context.error(`Type ${toString(outputType)} is not interpolatable.`) as null;
}
Expand All @@ -156,7 +152,7 @@ class Interpolate implements Expression {
return outputs[0].evaluate(ctx);
}

const value = (this.input.evaluate(ctx) as any as number);
const value: number = this.input.evaluate(ctx);
if (value <= labels[0]) {
return outputs[0].evaluate(ctx);
}
Expand All @@ -174,12 +170,13 @@ class Interpolate implements Expression {
const outputLower = outputs[index].evaluate(ctx);
const outputUpper = outputs[index + 1].evaluate(ctx);

if (this.operator === 'interpolate') {
return ((interpolate[this.type.kind.toLowerCase()] as any))(outputLower, outputUpper, t); // eslint-disable-line import/namespace
} else if (this.operator === 'interpolate-hcl') {
return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t));
} else {
return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t));
switch (this.operator) {
case 'interpolate':
return interpolate[this.type.kind](outputLower, outputUpper, t);
case 'interpolate-hcl':
return interpolate.color(outputLower, outputUpper, t, 'hcl');
case 'interpolate-lab':
return interpolate.color(outputLower, outputUpper, t, 'lab');
}
}

Expand Down
34 changes: 30 additions & 4 deletions src/expression/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ export type EvaluationKind = 'constant' | 'source' | 'camera' | 'composite';
export type Type = NullTypeT | NumberTypeT | StringTypeT | BooleanTypeT | ColorTypeT | ObjectTypeT | ValueTypeT |
ArrayType | ErrorTypeT | CollatorTypeT | FormattedTypeT | PaddingTypeT | ResolvedImageTypeT;

export type ArrayType = {
export interface ArrayType<T extends Type = Type> {
kind: 'array';
itemType: Type;
itemType: T;
N: number;
};
}

export type NativeType = 'number' | 'string' | 'boolean' | 'null' | 'array' | 'object';

Expand All @@ -61,7 +61,7 @@ export const FormattedType = {kind: 'formatted'} as FormattedTypeT;
export const PaddingType = {kind: 'padding'} as PaddingTypeT;
export const ResolvedImageType = {kind: 'resolvedImage'} as ResolvedImageTypeT;

export function array(itemType: Type, N?: number | null): ArrayType {
export function array<T extends Type>(itemType: T, N?: number | null): ArrayType<T> {
return {
kind: 'array',
itemType,
Expand Down Expand Up @@ -138,3 +138,29 @@ export function isValidNativeType(provided: any, allowedTypes: Array<NativeType>
}
});
}

/**
* Verify whether the specified type is of the same type as the specified sample.
*
* @param provided Type to verify
* @param sample Sample type to reference
* @returns `true` if both objects are of the same type, `false` otherwise
* @example basic types
* if (verifyType(outputType, ValueType)) {
* // type narrowed to:
* outputType.kind; // 'value'
* }
* @example array types
* if (verifyType(outputType, array(NumberType))) {
* // type narrowed to:
* outputType.kind; // 'array'
* outputType.itemType; // NumberTypeT
* outputType.itemType.kind; // 'number'
* }
*/
export function verifyType<T extends Type>(provided: Type, sample: T): provided is T {
if (provided.kind === 'array' && sample.kind === 'array') {
return provided.itemType.kind === sample.itemType.kind && typeof provided.N === 'number';
}
return provided.kind === sample.kind;
}
40 changes: 19 additions & 21 deletions src/function/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {expectToMatchColor} from '../../test/unit/test_utils';
import {createFunction} from './index';
import Color from '../util/color';
import Formatted from '../expression/types/formatted';
Expand Down Expand Up @@ -175,52 +176,49 @@ describe('exponential function', () => {
type: 'color'
}).evaluate;

expect(f({zoom: 0}, undefined)).toEqual(new Color(1, 0, 0, 1));
expect(f({zoom: 5}, undefined)).toEqual(new Color(0.6, 0, 0.4, 1));
expect(f({zoom: 11}, undefined)).toEqual(new Color(0, 0, 1, 1));

expectToMatchColor(f({zoom: 0}, undefined), 'rgb(100% 0% 0% / 1)');
expectToMatchColor(f({zoom: 5}, undefined), 'rgb(60% 0% 40% / 1)');
expectToMatchColor(f({zoom: 11}, undefined), 'rgb(0% 0% 100% / 1)');
});

test('lab colorspace', () => {
test('color hcl colorspace', () => {
const f = createFunction({
type: 'exponential',
colorSpace: 'lab',
stops: [[1, 'rgba(0,0,0,1)'], [10, 'rgba(0,255,255,1)']]
colorSpace: 'hcl',
stops: [[0, 'rgb(36 98 36 / 0.6)'], [10, 'hsl(222,73%,32%)']],
}, {
type: 'color'
}).evaluate;

expect(f({zoom: 0}, undefined)).toEqual(new Color(0, 0, 0, 1));
expect(f({zoom: 5}, undefined).r).toBeCloseTo(0);
expect(f({zoom: 5}, undefined).g).toBeCloseTo(0.444);
expect(f({zoom: 5}, undefined).b).toBeCloseTo(0.444);

expectToMatchColor(f({zoom: 0}, undefined), 'rgb(14.12% 38.43% 14.12% / .6)', 4);
expectToMatchColor(f({zoom: 5}, undefined), 'rgb(0% 35.71% 46.73% / .8)', 4);
expectToMatchColor(f({zoom: 10}, undefined), 'rgb(8.64% 22.66% 55.36% / 1)', 4);
});

test('rgb colorspace', () => {
test('color lab colorspace', () => {
const f = createFunction({
type: 'exponential',
colorSpace: 'rgb',
stops: [[0, 'rgba(0,0,0,1)'], [10, 'rgba(255,255,255,1)']]
colorSpace: 'lab',
stops: [[0, '#0009'], [10, 'rgba(0,255,255,1)']],
}, {
type: 'color'
}).evaluate;

expect(f({zoom: 5}, undefined)).toEqual(new Color(0.5, 0.5, 0.5, 1));

expectToMatchColor(f({zoom: 0}, undefined), 'rgb(0% 0% 0% / .6)');
expectToMatchColor(f({zoom: 5}, undefined), 'rgb(14.29% 46.73% 46.63% / .8)', 4);
expectToMatchColor(f({zoom: 10}, undefined), 'rgb(0% 100% 100% / 1)');
});

test('unknown color spaces', () => {
test('color invalid colorspace', () => {
expect(() => {
createFunction({
type: 'exponential',
colorSpace: 'unknown',
colorSpace: 'invalid',
stops: [[1, [0, 0, 0, 1]], [10, [0, 1, 1, 1]]]
}, {
type: 'color'
});
}).toThrow();

}).toThrow('Unknown color space: "invalid"');
});

test('interpolation mutation avoidance', () => {
Expand Down
19 changes: 6 additions & 13 deletions src/function/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@

import * as colorSpaces from '../util/color_spaces';
import Color from '../util/color';
import extend from '../util/extend';
import getType from '../util/get_type';
import * as interpolate from '../util/interpolate';
import interpolate, {isSupportedInterpolationColorSpace} from '../util/interpolate';
import Interpolate from '../expression/definitions/interpolate';
import Formatted from '../expression/types/formatted';
import ResolvedImage from '../expression/types/resolved_image';
Expand Down Expand Up @@ -44,8 +42,8 @@ export function createFunction(parameters, propertySpec) {
}
}

if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { // eslint-disable-line import/namespace
throw new Error(`Unknown color space: ${parameters.colorSpace}`);
if (parameters.colorSpace && !isSupportedInterpolationColorSpace(parameters.colorSpace)) {
throw new Error(`Unknown color space: "${parameters.colorSpace}"`);
}

let innerFun;
Expand Down Expand Up @@ -176,12 +174,7 @@ function evaluateExponentialFunction(parameters, propertySpec, input) {

const outputLower = parameters.stops[index][1];
const outputUpper = parameters.stops[index + 1][1];
let interp = interpolate[propertySpec.type] || identityFunction; // eslint-disable-line import/namespace

if (parameters.colorSpace && parameters.colorSpace !== 'rgb') {
const colorspace = colorSpaces[parameters.colorSpace]; // eslint-disable-line import/namespace
interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t));
}
const interp = interpolate[propertySpec.type] || identityFunction;

if (typeof outputLower.evaluate === 'function') {
return {
Expand All @@ -192,12 +185,12 @@ function evaluateExponentialFunction(parameters, propertySpec, input) {
if (evaluatedLower === undefined || evaluatedUpper === undefined) {
return undefined;
}
return interp(evaluatedLower, evaluatedUpper, t);
return interp(evaluatedLower, evaluatedUpper, t, parameters.colorSpace);
}
};
}

return interp(outputLower, outputUpper, t);
return interp(outputLower, outputUpper, t, parameters.colorSpace);
}

function evaluateIdentityFunction(parameters, propertySpec, input) {
Expand Down
Loading