Skip to content

🎥 Make videos programmatically with React

`@remotion/effects`: Add source alpha masking option (#8219)

Jonny Burgera2cbc260458d
diff --git a/packages/docs/docs/effects/halftone-linear-gradient.mdx b/packages/docs/docs/effects/halftone-linear-gradient.mdx
index f52201398c..3f867c6f11 100644
--- a/packages/docs/docs/effects/halftone-linear-gradient.mdx
+++ b/packages/docs/docs/effects/halftone-linear-gradient.mdx
@@ -124,6 +124,12 @@ If `colorMode` is `'source'`, don't pass `dotColor`.
Color of the dots when `colorMode` is `'solid'`. Defaults to `'black'`.
+### `maskToSourceAlpha?`<AvailableFrom v="4.0.474" />
+
+Masks solid-color dots to the source alpha channel. Defaults to `false`.
+
+Set this to `true` to prevent solid-color dots from appearing in fully transparent source pixels. In `colorMode: 'source'`, dots already use the source alpha channel.
+
### `disabled?`
When `true`, the effect is skipped. Defaults to `false`.
diff --git a/packages/docs/docs/effects/lines.mdx b/packages/docs/docs/effects/lines.mdx
index 7e200a624d..ec04ad9084 100644
--- a/packages/docs/docs/effects/lines.mdx
+++ b/packages/docs/docs/effects/lines.mdx
@@ -90,6 +90,12 @@ Offset in pixels. Defaults to `0`.
Animate this value with [`useCurrentFrame()`](/docs/use-current-frame) to scroll the lines.
+### `maskToSourceAlpha?`<AvailableFrom v="4.0.474" />
+
+Masks the generated line pattern to the source alpha channel. Defaults to `false`.
+
+Set this to `true` to prevent the line pattern from appearing in fully transparent source pixels.
+
### `disabled?`
When `true`, the effect is skipped. Defaults to `false`.
diff --git a/packages/docs/docs/effects/rings.mdx b/packages/docs/docs/effects/rings.mdx
index 2865afa900..26f2491dbd 100644
--- a/packages/docs/docs/effects/rings.mdx
+++ b/packages/docs/docs/effects/rings.mdx
@@ -78,6 +78,12 @@ Radial offset in pixels. Defaults to `0`.
Animate this value with [`useCurrentFrame()`](/docs/use-current-frame) to expand or contract the rings.
+### `maskToSourceAlpha?`<AvailableFrom v="4.0.474" />
+
+Masks the generated ring pattern to the source alpha channel. Defaults to `false`.
+
+Set this to `true` to prevent the ring pattern from appearing in fully transparent source pixels.
+
### `disabled?`
When `true`, the effect is skipped. Defaults to `false`.
diff --git a/packages/docs/docs/effects/waves.mdx b/packages/docs/docs/effects/waves.mdx
index 420a4de51e..5da9dee7ed 100644
--- a/packages/docs/docs/effects/waves.mdx
+++ b/packages/docs/docs/effects/waves.mdx
@@ -97,6 +97,12 @@ Wave phase in degrees. Defaults to `0`.
Animate this value with [`useCurrentFrame()`](/docs/use-current-frame) to move the wave shape without scrolling through the bands.
+### `maskToSourceAlpha?`<AvailableFrom v="4.0.474" />
+
+Masks the generated wave pattern to the source alpha channel. Defaults to `false`.
+
+Set this to `true` to prevent the wave pattern from appearing in fully transparent source pixels.
+
### `disabled?`
When `true`, the effect is skipped. Defaults to `false`.
diff --git a/packages/docs/docs/effects/zigzag.mdx b/packages/docs/docs/effects/zigzag.mdx
index a7e955719d..5839cf90e4 100644
--- a/packages/docs/docs/effects/zigzag.mdx
+++ b/packages/docs/docs/effects/zigzag.mdx
@@ -93,6 +93,12 @@ Zig-zag displacement in pixels. Defaults to `40`.
Distance in pixels before the zig-zag repeats. Defaults to `160`. Must be greater than `0`.
+### `maskToSourceAlpha?`<AvailableFrom v="4.0.474" />
+
+Masks the generated zig-zag pattern to the source alpha channel. Defaults to `false`.
+
+Set this to `true` to prevent the zig-zag pattern from appearing in fully transparent source pixels.
+
### `disabled?`
When `true`, the effect is skipped. Defaults to `false`.
diff --git a/packages/effects/src/halftone-linear-gradient.ts b/packages/effects/src/halftone-linear-gradient.ts
index c41d4ede68..4a8b452120 100644
--- a/packages/effects/src/halftone-linear-gradient.ts
+++ b/packages/effects/src/halftone-linear-gradient.ts
@@ -7,6 +7,7 @@ import {
} from './color-utils.js';
import {
assertEffectParamsObject,
+ assertOptionalBoolean,
assertOptionalColor,
} from './validate-effect-param.js';
@@ -20,6 +21,7 @@ const DEFAULT_FIRST_STOP_POSITION = [0, 0.5] as const;
const DEFAULT_SECOND_STOP_POSITION = [1, 0.5] as const;
const DEFAULT_GRID_SIZE = 24;
const DEFAULT_DOT_COLOR = 'black';
+const DEFAULT_MASK_TO_SOURCE_ALPHA = false as const;
export const halftoneLinearGradientSchema = {
firstStopDotSize: {
@@ -81,6 +83,11 @@ export const halftoneLinearGradientSchema = {
source: {},
},
},
+ maskToSourceAlpha: {
+ type: 'boolean',
+ default: DEFAULT_MASK_TO_SOURCE_ALPHA,
+ description: 'Mask to source alpha',
+ },
} as const satisfies SequenceSchema;
export type HalftoneLinearGradientColorMode =
@@ -109,6 +116,10 @@ type HalftoneLinearGradientCommonParams = {
* Distance between adjacent dot centers.
*/
readonly gridSize?: number;
+ /**
+ * Masks solid-color dots to the source alpha channel. Defaults to `false`.
+ */
+ readonly maskToSourceAlpha?: boolean;
};
export type HalftoneLinearGradientParams = HalftoneLinearGradientCommonParams &
@@ -131,6 +142,7 @@ type HalftoneLinearGradientResolved = {
gridSize: number;
colorMode: HalftoneLinearGradientColorMode;
dotColor: string;
+ maskToSourceAlpha: boolean;
};
const formatEnum = (variants: readonly string[]): string => {
@@ -173,6 +185,7 @@ const resolve = (
colorMode: p.colorMode ?? 'solid',
dotColor:
'dotColor' in p ? (p.dotColor ?? DEFAULT_DOT_COLOR) : DEFAULT_DOT_COLOR,
+ maskToSourceAlpha: p.maskToSourceAlpha ?? DEFAULT_MASK_TO_SOURCE_ALPHA,
});
const validateNonNegative = (value: number, name: string): void => {
@@ -214,6 +227,7 @@ const validateHalftoneLinearGradientParams = (
assertOptionalUvCoordinate(params.firstStopPosition, 'firstStopPosition');
assertOptionalUvCoordinate(params.secondStopPosition, 'secondStopPosition');
assertOptionalFiniteNumber(params.gridSize, 'gridSize');
+ assertOptionalBoolean(params.maskToSourceAlpha, 'maskToSourceAlpha');
assertOptionalEnum(
params.colorMode,
'colorMode',
@@ -269,6 +283,7 @@ uniform vec2 uSecondStopPosition;
uniform float uGridSize;
uniform vec4 uColor;
uniform bool uUseSourceColor;
+uniform bool uMaskToSourceAlpha;
float gradientProgress(vec2 uv) {
vec2 stopVector = uSecondStopPosition - uFirstStopPosition;
@@ -284,6 +299,13 @@ vec4 sourceOver(vec4 backdrop, vec4 overlay) {
return overlay + backdrop * (1.0 - overlay.a);
}
+vec4 sourceAtop(vec4 backdrop, vec4 overlay) {
+ return vec4(
+ overlay.rgb * backdrop.a + backdrop.rgb * (1.0 - overlay.a),
+ backdrop.a
+ );
+}
+
void main() {
vec2 fragPos = vUv * uResolution;
vec2 center = uResolution * 0.5;
@@ -312,7 +334,11 @@ void main() {
vec2 sampleUv = clamp(centerUv, vec2(0.0), vec2(1.0));
vec4 texColor = texture(uSource, sampleUv);
vec4 dotColor = (uUseSourceColor ? texColor : uColor) * coverage;
- fragColor = uUseSourceColor ? dotColor : sourceOver(texColor, dotColor);
+ fragColor = uUseSourceColor
+ ? dotColor
+ : uMaskToSourceAlpha
+ ? sourceAtop(texColor, dotColor)
+ : sourceOver(texColor, dotColor);
}
`;
@@ -331,6 +357,7 @@ type HalftoneLinearGradientState = {
uGridSize: WebGLUniformLocation | null;
uColor: WebGLUniformLocation | null;
uUseSourceColor: WebGLUniformLocation | null;
+ uMaskToSourceAlpha: WebGLUniformLocation | null;
colorCtx: CanvasRenderingContext2D;
cachedColorStr: string;
cachedColorRgba: ParsedColorRgba;
@@ -394,7 +421,8 @@ export const halftoneLinearGradient = createEffect<
backend: 'webgl2',
calculateKey: (params) => {
const r = resolve(params);
- return `halftone-linear-gradient-${r.firstStopDotSize}-${r.secondStopDotSize}-${r.firstStopPosition.join(':')}-${r.secondStopPosition.join(':')}-${r.gridSize}-${r.colorMode}-${r.dotColor}`;
+ const maskSuffix = r.maskToSourceAlpha ? '-mask-to-source-alpha' : '';
+ return `halftone-linear-gradient-${r.firstStopDotSize}-${r.secondStopDotSize}-${r.firstStopPosition.join(':')}-${r.secondStopPosition.join(':')}-${r.gridSize}-${r.colorMode}-${r.dotColor}${maskSuffix}`;
},
setup: (target) => {
const gl = target.getContext('webgl2', {
@@ -484,6 +512,7 @@ export const halftoneLinearGradient = createEffect<
uGridSize: gl.getUniformLocation(program, 'uGridSize'),
uColor: gl.getUniformLocation(program, 'uColor'),
uUseSourceColor: gl.getUniformLocation(program, 'uUseSourceColor'),
+ uMaskToSourceAlpha: gl.getUniformLocation(program, 'uMaskToSourceAlpha'),
colorCtx,
cachedColorStr: '',
cachedColorRgba: [0, 0, 0, 255],
@@ -549,6 +578,8 @@ export const halftoneLinearGradient = createEffect<
);
if (state.uUseSourceColor)
gl.uniform1i(state.uUseSourceColor, r.colorMode === 'source' ? 1 : 0);
+ if (state.uMaskToSourceAlpha)
+ gl.uniform1i(state.uMaskToSourceAlpha, r.maskToSourceAlpha ? 1 : 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
diff --git a/packages/effects/src/halftone.ts b/packages/effects/src/halftone.ts
index 0016175e5e..5a5761e75b 100644
--- a/packages/effects/src/halftone.ts
+++ b/packages/effects/src/halftone.ts
@@ -6,6 +6,7 @@ import {
type ParsedColorRgba,
} from './color-utils.js';
import {
+ assertOptionalBoolean,
assertEffectParamsObject,
assertOptionalColor,
} from './validate-effect-param.js';
@@ -160,18 +161,6 @@ const assertOptionalEnum = <T extends string>(
}
};
-const assertOptionalBoolean = (value: unknown, name: string): void => {
- if (value === undefined) {
- return;
- }
-
- if (typeof value !== 'boolean') {
- throw new TypeError(
- `"${name}" must be a boolean, but got ${JSON.stringify(value)}`,
- );
- }
-};
-
const resolve = (p: HalftoneParams): HalftoneResolved => ({
shape: p.shape ?? 'circle',
dotSize: p.dotSize ?? 20,
diff --git a/packages/effects/src/lines.ts b/packages/effects/src/lines.ts
index 334ecf2fbb..f0cd3b6ac7 100644
--- a/packages/effects/src/lines.ts
+++ b/packages/effects/src/lines.ts
@@ -7,6 +7,7 @@ import {
} from './color-utils.js';
import {
assertEffectParamsObject,
+ assertOptionalBoolean,
assertRequiredColor,
} from './validate-effect-param.js';
@@ -20,6 +21,7 @@ const DEFAULT_THICKNESS = 40 as const;
const DEFAULT_GAP = 0 as const;
const DEFAULT_ANGLE = 0 as const;
const DEFAULT_OFFSET = 0 as const;
+const DEFAULT_MASK_TO_SOURCE_ALPHA = false as const;
export const linesSchema = {
direction: {
@@ -62,6 +64,11 @@ export const linesSchema = {
description: 'Offset',
hiddenFromList: false,
},
+ maskToSourceAlpha: {
+ type: 'boolean',
+ default: DEFAULT_MASK_TO_SOURCE_ALPHA,
+ description: 'Mask to source alpha',
+ },
} as const satisfies SequenceSchema;
export type LinesDirection = (typeof LINE_DIRECTIONS)[number];
@@ -79,6 +86,8 @@ export type LinesParams = {
readonly angle?: number;
/** Offset in pixels. Animate this value to scroll the lines. Defaults to `0`. */
readonly offset?: number;
+ /** Masks the generated line pattern to the source alpha channel. Defaults to `false`. */
+ readonly maskToSourceAlpha?: boolean;
};
type LinesResolved = {
@@ -88,6 +97,7 @@ type LinesResolved = {
spacing: number;
angle: number;
offset: number;
+ maskToSourceAlpha: boolean;
};
type LinesState = {
@@ -108,6 +118,7 @@ type LinesState = {
readonly uSpacing: WebGLUniformLocation | null;
readonly uAngle: WebGLUniformLocation | null;
readonly uOffset: WebGLUniformLocation | null;
+ readonly uMaskToSourceAlpha: WebGLUniformLocation | null;
};
cachedPaletteKey: string;
palettePixelData: Uint8Array;
@@ -124,6 +135,7 @@ const resolve = (p: LinesParams): LinesResolved => {
spacing: thickness + gap,
angle: p.angle ?? DEFAULT_ANGLE,
offset: p.offset ?? DEFAULT_OFFSET,
+ maskToSourceAlpha: p.maskToSourceAlpha ?? DEFAULT_MASK_TO_SOURCE_ALPHA,
};
};
@@ -193,6 +205,7 @@ const validateLinesParams = (params: LinesParams): void => {
assertOptionalFiniteNumber(params.gap, 'gap');
assertOptionalFiniteNumber(params.angle, 'angle');
assertOptionalFiniteNumber(params.offset, 'offset');
+ assertOptionalBoolean(params.maskToSourceAlpha, 'maskToSourceAlpha');
const thickness = params.thickness ?? DEFAULT_THICKNESS;
const gap = params.gap ?? DEFAULT_GAP;
@@ -226,6 +239,7 @@ uniform float uThickness;
uniform float uSpacing;
uniform float uAngle;
uniform float uOffset;
+uniform bool uMaskToSourceAlpha;
void main() {
vec4 texColor = texture(uSource, vUv);
@@ -257,6 +271,14 @@ float c = cos(uAngle);
float lineAlpha = lineColor.a;
vec3 premultipliedLine = lineColor.rgb * lineAlpha;
+ if (uMaskToSourceAlpha) {
+ fragColor = vec4(
+ premultipliedLine * texColor.a + texColor.rgb * (1.0 - lineAlpha),
+ texColor.a
+ );
+ return;
+ }
+
fragColor = vec4(
premultipliedLine + texColor.rgb * (1.0 - lineAlpha),
lineAlpha + texColor.a * (1.0 - lineAlpha)
@@ -406,6 +428,7 @@ const setupLines = (target: HTMLCanvasElement): LinesState => {
uSpacing: gl.getUniformLocation(program, 'uSpacing'),
uAngle: gl.getUniformLocation(program, 'uAngle'),
uOffset: gl.getUniformLocation(program, 'uOffset'),
+ uMaskToSourceAlpha: gl.getUniformLocation(program, 'uMaskToSourceAlpha'),
},
cachedPaletteKey: '',
palettePixelData: new Uint8Array(0),
@@ -447,7 +470,8 @@ export const lines = createEffect<LinesParams, LinesState>({
backend: 'webgl2',
calculateKey: (params) => {
const r = resolve(params);
- return `lines-${r.colors.join('|')}-${r.direction}-${r.thickness}-${r.spacing}-${r.angle}-${r.offset}`;
+ const maskSuffix = r.maskToSourceAlpha ? '-mask-to-source-alpha' : '';
+ return `lines-${r.colors.join('|')}-${r.direction}-${r.thickness}-${r.spacing}-${r.angle}-${r.offset}${maskSuffix}`;
},
setup: (target) => setupLines(target),
apply: ({source, width, height, params, state, flipSourceY}) => {
@@ -504,6 +528,8 @@ export const lines = createEffect<LinesParams, LinesState>({
if (uniforms.uAngle)
gl.uniform1f(uniforms.uAngle, (r.angle * Math.PI) / 180);
if (uniforms.uOffset) gl.uniform1f(uniforms.uOffset, r.offset);
+ if (uniforms.uMaskToSourceAlpha)
+ gl.uniform1i(uniforms.uMaskToSourceAlpha, r.maskToSourceAlpha ? 1 : 0);
gl.bindVertexArray(vao);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
diff --git a/packages/effects/src/rings.ts b/packages/effects/src/rings.ts
index a1ad60dd29..14309bf802 100644
--- a/packages/effects/src/rings.ts
+++ b/packages/effects/src/rings.ts
@@ -8,6 +8,7 @@ import {
} from './color-utils.js';
import {
assertEffectParamsObject,
+ assertOptionalBoolean,
assertRequiredColor,
} from './validate-effect-param.js';
@@ -18,6 +19,7 @@ const DEFAULT_CENTER = [0.5, 0.5] as const;
const DEFAULT_THICKNESS = 40 as const;
const DEFAULT_GAP = 0 as const;
const DEFAULT_OFFSET = 0 as const;
+const DEFAULT_MASK_TO_SOURCE_ALPHA = false as const;
export const ringsSchema = {
center: {
@@ -53,6 +55,11 @@ export const ringsSchema = {
description: 'Offset',
hiddenFromList: false,
},
+ maskToSourceAlpha: {
+ type: 'boolean',
+ default: DEFAULT_MASK_TO_SOURCE_ALPHA,
+ description: 'Mask to source alpha',
+ },
} as const satisfies SequenceSchema;
export type RingsCenter = readonly [number, number];
@@ -68,6 +75,8 @@ export type RingsParams = {
readonly gap?: number;
/** Radial offset in pixels. Animate to expand or contract the rings. */
readonly offset?: number;
+ /** Masks the generated ring pattern to the source alpha channel. Defaults to `false`. */
+ readonly maskToSourceAlpha?: boolean;
};
type RingsResolved = {
@@ -76,6 +85,7 @@ type RingsResolved = {
thickness: number;
spacing: number;
offset: number;
+ maskToSourceAlpha: boolean;
};
type RingsState = {
@@ -95,6 +105,7 @@ type RingsState = {
readonly uThickness: WebGLUniformLocation | null;
readonly uSpacing: WebGLUniformLocation | null;
readonly uOffset: WebGLUniformLocation | null;
+ readonly uMaskToSourceAlpha: WebGLUniformLocation | null;
};
cachedPaletteKey: string;
palettePixelData: Uint8Array;
@@ -110,6 +121,7 @@ const resolve = (p: RingsParams): RingsResolved => {
thickness,
spacing: thickness + gap,
offset: p.offset ?? DEFAULT_OFFSET,
+ maskToSourceAlpha: p.maskToSourceAlpha ?? DEFAULT_MASK_TO_SOURCE_ALPHA,
};
};
@@ -169,6 +181,7 @@ const validateRingsParams = (params: RingsParams): void => {
assertOptionalFiniteNumber(params.thickness, 'thickness');
assertOptionalFiniteNumber(params.gap, 'gap');
assertOptionalFiniteNumber(params.offset, 'offset');
+ assertOptionalBoolean(params.maskToSourceAlpha, 'maskToSourceAlpha');
const thickness = params.thickness ?? DEFAULT_THICKNESS;
const gap = params.gap ?? DEFAULT_GAP;
@@ -201,6 +214,7 @@ uniform vec2 uCenter;
uniform float uThickness;
uniform float uSpacing;
uniform float uOffset;
+uniform bool uMaskToSourceAlpha;
void main() {
vec4 texColor = texture(uSource, vUv);
@@ -227,6 +241,14 @@ void main() {
float ringAlpha = ringColor.a;
vec3 premultipliedRing = ringColor.rgb * ringAlpha;
+ if (uMaskToSourceAlpha) {
+ fragColor = vec4(
+ premultipliedRing * texColor.a + texColor.rgb * (1.0 - ringAlpha),
+ texColor.a
+ );
+ return;
+ }
+
fragColor = vec4(
premultipliedRing + texColor.rgb * (1.0 - ringAlpha),
ringAlpha + texColor.a * (1.0 - ringAlpha)
@@ -375,6 +397,7 @@ const setupRings = (target: HTMLCanvasElement): RingsState => {
uThickness: gl.getUniformLocation(program, 'uThickness'),
uSpacing: gl.getUniformLocation(program, 'uSpacing'),
uOffset: gl.getUniformLocation(program, 'uOffset'),
+ uMaskToSourceAlpha: gl.getUniformLocation(program, 'uMaskToSourceAlpha'),
},
cachedPaletteKey: '',
palettePixelData: new Uint8Array(0),
@@ -416,7 +439,8 @@ export const rings = createEffect<RingsParams, RingsState>({
backend: 'webgl2',
calculateKey: (params) => {
const r = resolve(params);
- return `rings-${r.colors.join('|')}-${r.center.join(':')}-${r.thickness}-${r.spacing}-${r.offset}`;
+ const maskSuffix = r.maskToSourceAlpha ? '-mask-to-source-alpha' : '';
+ return `rings-${r.colors.join('|')}-${r.center.join(':')}-${r.thickness}-${r.spacing}-${r.offset}${maskSuffix}`;
},
setup: (target) => setupRings(target),
apply: ({source, width, height, params, state, flipSourceY}) => {
@@ -471,6 +495,8 @@ export const rings = createEffect<RingsParams, RingsState>({
if (uniforms.uThickness) gl.uniform1f(uniforms.uThickness, r.thickness);
if (uniforms.uSpacing) gl.uniform1f(uniforms.uSpacing, r.spacing);
if (uniforms.uOffset) gl.uniform1f(uniforms.uOffset, r.offset);
+ if (uniforms.uMaskToSourceAlpha)
+ gl.uniform1i(uniforms.uMaskToSourceAlpha, r.maskToSourceAlpha ? 1 : 0);
gl.bindVertexArray(vao);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index 83f3ed64a3..d928e5814e 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -506,6 +506,12 @@ test('waves() rejects non-positive thickness', () => {
);
});
+test('waves() rejects non-boolean maskToSourceAlpha', () => {
+ expect(() => waves({maskToSourceAlpha: 'yes' as unknown as boolean})).toThrow(
+ '"maskToSourceAlpha" must be a boolean',
+ );
+});
+
test('waves() parameters produce distinct effect keys', () => {
const defaults = waves();
const colored = waves({colors: ['#ffffff', 'transparent']});
@@ -517,6 +523,7 @@ test('waves() parameters produce distinct effect keys', () => {
const stronger = waves({amplitude: 30});
const longer = waves({wavelength: 220});
const phased = waves({phase: 90});
+ const masked = waves({maskToSourceAlpha: true});
expect(
new Set([
@@ -530,8 +537,9 @@ test('waves() parameters produce distinct effect keys', () => {
stronger.effectKey,
longer.effectKey,
phased.effectKey,
+ masked.effectKey,
]).size,
- ).toBe(10);
+ ).toBe(11);
});
test('zigzag() accepts default params', () => {
@@ -571,6 +579,12 @@ test('zigzag() rejects non-positive thickness', () => {
);
});
+test('zigzag() rejects non-boolean maskToSourceAlpha', () => {
+ expect(() =>
+ zigzag({maskToSourceAlpha: 'yes' as unknown as boolean}),
+ ).toThrow('"maskToSourceAlpha" must be a boolean');
+});
+
test('zigzag() parameters produce distinct effect keys', () => {
const defaults = zigzag();
const colored = zigzag({colors: ['#ffffff', 'transparent']});
@@ -581,6 +595,7 @@ test('zigzag() parameters produce distinct effect keys', () => {
const shifted = zigzag({offset: 10});
const stronger = zigzag({amplitude: 30});
const longer = zigzag({wavelength: 220});
+ const masked = zigzag({maskToSourceAlpha: true});
expect(
new Set([
@@ -593,8 +608,9 @@ test('zigzag() parameters produce distinct effect keys', () => {
shifted.effectKey,
stronger.effectKey,
longer.effectKey,
+ masked.effectKey,
]).size,
- ).toBe(9);
+ ).toBe(10);
});
test('whiteNoise() accepts default params', () => {
@@ -1200,6 +1216,14 @@ test('halftoneLinearGradient() rejects dotColor for source color mode', () => {
).toThrow('"dotColor" can only be set when "colorMode" is "solid"');
});
+test('halftoneLinearGradient() rejects non-boolean maskToSourceAlpha', () => {
+ expect(() =>
+ halftoneLinearGradient({
+ maskToSourceAlpha: 'yes' as unknown as boolean,
+ }),
+ ).toThrow('"maskToSourceAlpha" must be a boolean');
+});
+
test('halftoneLinearGradient() parameters produce distinct effect keys', () => {
const defaultGradient = halftoneLinearGradient();
const shiftedFirstStop = halftoneLinearGradient({firstStopDotSize: 8});
@@ -1208,6 +1232,7 @@ test('halftoneLinearGradient() parameters produce distinct effect keys', () => {
firstStopPosition: [0.2, 0.5],
});
const sourceColor = halftoneLinearGradient({colorMode: 'source'});
+ const masked = halftoneLinearGradient({maskToSourceAlpha: true});
expect(
new Set([
@@ -1216,8 +1241,9 @@ test('halftoneLinearGradient() parameters produce distinct effect keys', () => {
shiftedSecondStop.effectKey,
shiftedFirstPosition.effectKey,
sourceColor.effectKey,
+ masked.effectKey,
]).size,
- ).toBe(5);
+ ).toBe(6);
});
test('dotGrid() accepts default params', () => {
@@ -1531,6 +1557,12 @@ test('lines() rejects non-finite offset', () => {
);
});
+test('lines() rejects non-boolean maskToSourceAlpha', () => {
+ expect(() => lines({maskToSourceAlpha: 'yes' as unknown as boolean})).toThrow(
+ '"maskToSourceAlpha" must be a boolean',
+ );
+});
+
test('lines() parameters produce distinct effect keys', () => {
const defaultLines = lines();
const colored = lines({colors: ['#ffffff', 'transparent']});
@@ -1539,6 +1571,7 @@ test('lines() parameters produce distinct effect keys', () => {
const gapped = lines({gap: 24});
const angled = lines({angle: 45});
const shifted = lines({offset: 10});
+ const masked = lines({maskToSourceAlpha: true});
expect(
new Set([
@@ -1549,8 +1582,9 @@ test('lines() parameters produce distinct effect keys', () => {
gapped.effectKey,
angled.effectKey,
shifted.effectKey,
+ masked.effectKey,
]).size,
- ).toBe(7);
+ ).toBe(8);
});
test('linearProgressiveBlur() accepts default params', () => {
@@ -1674,6 +1708,12 @@ test('rings() rejects non-finite offset', () => {
);
});
+test('rings() rejects non-boolean maskToSourceAlpha', () => {
+ expect(() => rings({maskToSourceAlpha: 'yes' as unknown as boolean})).toThrow(
+ '"maskToSourceAlpha" must be a boolean',
+ );
+});
+
test('rings() parameters produce distinct effect keys', () => {
const defaultRings = rings();
const colored = rings({colors: ['#ffffff', 'transparent']});
@@ -1681,6 +1721,7 @@ test('rings() parameters produce distinct effect keys', () => {
const thin = rings({thickness: 20});
const gapped = rings({gap: 24});
const shifted = rings({offset: 10});
+ const masked = rings({maskToSourceAlpha: true});
expect(
new Set([
@@ -1690,8 +1731,9 @@ test('rings() parameters produce distinct effect keys', () => {
thin.effectKey,
gapped.effectKey,
shifted.effectKey,
+ masked.effectKey,
]).size,
- ).toBe(6);
+ ).toBe(7);
});
test('hue() accepts default params', () => {
diff --git a/packages/effects/src/validate-effect-param.ts b/packages/effects/src/validate-effect-param.ts
index 209ba50672..5fbfe4b11c 100644
--- a/packages/effects/src/validate-effect-param.ts
+++ b/packages/effects/src/validate-effect-param.ts
@@ -35,3 +35,15 @@ export const assertOptionalColor = (value: unknown, name: string): void => {
assertRequiredColor(value, name);
};
+
+export const assertOptionalBoolean = (value: unknown, name: string): void => {
+ if (value === undefined) {
+ return;
+ }
+
+ if (typeof value !== 'boolean') {
+ throw new TypeError(
+ `"${name}" must be a boolean, but got ${JSON.stringify(value)}`,
+ );
+ }
+};
diff --git a/packages/effects/src/waves.ts b/packages/effects/src/waves.ts
index b652715450..2f30dd3118 100644
--- a/packages/effects/src/waves.ts
+++ b/packages/effects/src/waves.ts
@@ -7,6 +7,7 @@ import {
} from './color-utils.js';
import {
assertEffectParamsObject,
+ assertOptionalBoolean,
assertRequiredColor,
} from './validate-effect-param.js';
@@ -23,6 +24,7 @@ const DEFAULT_OFFSET = 0 as const;
const DEFAULT_AMPLITUDE = 24 as const;
const DEFAULT_WAVELENGTH = 160 as const;
const DEFAULT_PHASE = 0 as const;
+const DEFAULT_MASK_TO_SOURCE_ALPHA = false as const;
export const wavesSchema = {
direction: {
@@ -92,6 +94,11 @@ export const wavesSchema = {
description: 'Phase',
hiddenFromList: false,
},
+ maskToSourceAlpha: {
+ type: 'boolean',
+ default: DEFAULT_MASK_TO_SOURCE_ALPHA,
+ description: 'Mask to source alpha',
+ },
} as const satisfies SequenceSchema;
export type WavesDirection = (typeof WAVE_DIRECTIONS)[number];
@@ -115,6 +122,8 @@ export type WavesParams = {
readonly wavelength?: number;
/** Wave phase in degrees. Defaults to `0`. */
readonly phase?: number;
+ /** Masks the generated wave pattern to the source alpha channel. Defaults to `false`. */
+ readonly maskToSourceAlpha?: boolean;
};
type WavesResolved = {
@@ -127,6 +136,7 @@ type WavesResolved = {
amplitude: number;
wavelength: number;
phase: number;
+ maskToSourceAlpha: boolean;
};
type WavesState = {
@@ -150,6 +160,7 @@ type WavesState = {
readonly uAmplitude: WebGLUniformLocation | null;
readonly uWavelength: WebGLUniformLocation | null;
readonly uPhase: WebGLUniformLocation | null;
+ readonly uMaskToSourceAlpha: WebGLUniformLocation | null;
};
cachedPaletteKey: string;
palettePixelData: Uint8Array;
@@ -169,6 +180,7 @@ const resolve = (p: WavesParams): WavesResolved => {
amplitude: p.amplitude ?? DEFAULT_AMPLITUDE,
wavelength: p.wavelength ?? DEFAULT_WAVELENGTH,
phase: p.phase ?? DEFAULT_PHASE,
+ maskToSourceAlpha: p.maskToSourceAlpha ?? DEFAULT_MASK_TO_SOURCE_ALPHA,
};
};
@@ -241,6 +253,7 @@ const validateWavesParams = (params: WavesParams): void => {
assertOptionalFiniteNumber(params.amplitude, 'amplitude');
assertOptionalFiniteNumber(params.wavelength, 'wavelength');
assertOptionalFiniteNumber(params.phase, 'phase');
+ assertOptionalBoolean(params.maskToSourceAlpha, 'maskToSourceAlpha');
const thickness = params.thickness ?? DEFAULT_THICKNESS;
const gap = params.gap ?? DEFAULT_GAP;
@@ -282,6 +295,7 @@ uniform float uOffset;
uniform float uAmplitude;
uniform float uWavelength;
uniform float uPhase;
+uniform bool uMaskToSourceAlpha;
void main() {
vec4 texColor = texture(uSource, vUv);
@@ -317,6 +331,14 @@ void main() {
float lineAlpha = lineColor.a;
vec3 premultipliedLine = lineColor.rgb * lineAlpha;
+ if (uMaskToSourceAlpha) {
+ fragColor = vec4(
+ premultipliedLine * texColor.a + texColor.rgb * (1.0 - lineAlpha),
+ texColor.a
+ );
+ return;
+ }
+
fragColor = vec4(
premultipliedLine + texColor.rgb * (1.0 - lineAlpha),
lineAlpha + texColor.a * (1.0 - lineAlpha)
@@ -469,6 +491,7 @@ const setupWaves = (target: HTMLCanvasElement): WavesState => {
uAmplitude: gl.getUniformLocation(program, 'uAmplitude'),
uWavelength: gl.getUniformLocation(program, 'uWavelength'),
uPhase: gl.getUniformLocation(program, 'uPhase'),
+ uMaskToSourceAlpha: gl.getUniformLocation(program, 'uMaskToSourceAlpha'),
},
cachedPaletteKey: '',
palettePixelData: new Uint8Array(0),
@@ -510,7 +533,8 @@ export const waves = createEffect<WavesParams, WavesState>({
backend: 'webgl2',
calculateKey: (params) => {
const r = resolve(params);
- return `waves-${r.colors.join('|')}-${r.direction}-${r.thickness}-${r.spacing}-${r.angle}-${r.offset}-${r.amplitude}-${r.wavelength}-${r.phase}`;
+ const maskSuffix = r.maskToSourceAlpha ? '-mask-to-source-alpha' : '';
+ return `waves-${r.colors.join('|')}-${r.direction}-${r.thickness}-${r.spacing}-${r.angle}-${r.offset}-${r.amplitude}-${r.wavelength}-${r.phase}${maskSuffix}`;
},
setup: (target) => setupWaves(target),
apply: ({source, width, height, params, state, flipSourceY}) => {
@@ -571,6 +595,8 @@ export const waves = createEffect<WavesParams, WavesState>({
if (uniforms.uWavelength) gl.uniform1f(uniforms.uWavelength, r.wavelength);
if (uniforms.uPhase)
gl.uniform1f(uniforms.uPhase, (r.phase * Math.PI) / 180);
+ if (uniforms.uMaskToSourceAlpha)
+ gl.uniform1i(uniforms.uMaskToSourceAlpha, r.maskToSourceAlpha ? 1 : 0);
gl.bindVertexArray(vao);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
diff --git a/packages/effects/src/zigzag.ts b/packages/effects/src/zigzag.ts
index b69ab8569e..7fe5dc440f 100644
--- a/packages/effects/src/zigzag.ts
+++ b/packages/effects/src/zigzag.ts
@@ -7,6 +7,7 @@ import {
} from './color-utils.js';
import {
assertEffectParamsObject,
+ assertOptionalBoolean,
assertRequiredColor,
} from './validate-effect-param.js';
@@ -22,6 +23,7 @@ const DEFAULT_ANGLE = 0 as const;
const DEFAULT_OFFSET = 0 as const;
const DEFAULT_AMPLITUDE = 40 as const;
const DEFAULT_WAVELENGTH = 160 as const;
+const DEFAULT_MASK_TO_SOURCE_ALPHA = false as const;
export const zigzagSchema = {
direction: {
@@ -82,6 +84,11 @@ export const zigzagSchema = {
description: 'Wavelength',
hiddenFromList: false,
},
+ maskToSourceAlpha: {
+ type: 'boolean',
+ default: DEFAULT_MASK_TO_SOURCE_ALPHA,
+ description: 'Mask to source alpha',
+ },
} as const satisfies SequenceSchema;
export type ZigzagDirection = (typeof ZIGZAG_DIRECTIONS)[number];
@@ -103,6 +110,8 @@ export type ZigzagParams = {
readonly amplitude?: number;
/** Distance in pixels before the zig-zag repeats. */
readonly wavelength?: number;
+ /** Masks the generated zig-zag pattern to the source alpha channel. Defaults to `false`. */
+ readonly maskToSourceAlpha?: boolean;
};
type ZigzagResolved = {
@@ -114,6 +123,7 @@ type ZigzagResolved = {
offset: number;
amplitude: number;
wavelength: number;
+ maskToSourceAlpha: boolean;
};
type ZigzagState = {
@@ -136,6 +146,7 @@ type ZigzagState = {
readonly uOffset: WebGLUniformLocation | null;
readonly uAmplitude: WebGLUniformLocation | null;
readonly uWavelength: WebGLUniformLocation | null;
+ readonly uMaskToSourceAlpha: WebGLUniformLocation | null;
};
cachedPaletteKey: string;
palettePixelData: Uint8Array;
@@ -154,6 +165,7 @@ const resolve = (p: ZigzagParams): ZigzagResolved => {
offset: p.offset ?? DEFAULT_OFFSET,
amplitude: p.amplitude ?? DEFAULT_AMPLITUDE,
wavelength: p.wavelength ?? DEFAULT_WAVELENGTH,
+ maskToSourceAlpha: p.maskToSourceAlpha ?? DEFAULT_MASK_TO_SOURCE_ALPHA,
};
};
@@ -225,6 +237,7 @@ const validateZigzagParams = (params: ZigzagParams): void => {
assertOptionalFiniteNumber(params.offset, 'offset');
assertOptionalFiniteNumber(params.amplitude, 'amplitude');
assertOptionalFiniteNumber(params.wavelength, 'wavelength');
+ assertOptionalBoolean(params.maskToSourceAlpha, 'maskToSourceAlpha');
const thickness = params.thickness ?? DEFAULT_THICKNESS;
const gap = params.gap ?? DEFAULT_GAP;
@@ -265,6 +278,7 @@ uniform float uAngle;
uniform float uOffset;
uniform float uAmplitude;
uniform float uWavelength;
+uniform bool uMaskToSourceAlpha;
void main() {
vec4 texColor = texture(uSource, vUv);
@@ -299,6 +313,14 @@ void main() {
float lineAlpha = lineColor.a;
vec3 premultipliedLine = lineColor.rgb * lineAlpha;
+ if (uMaskToSourceAlpha) {
+ fragColor = vec4(
+ premultipliedLine * texColor.a + texColor.rgb * (1.0 - lineAlpha),
+ texColor.a
+ );
+ return;
+ }
+
fragColor = vec4(
premultipliedLine + texColor.rgb * (1.0 - lineAlpha),
lineAlpha + texColor.a * (1.0 - lineAlpha)
@@ -450,6 +472,7 @@ const setupZigzag = (target: HTMLCanvasElement): ZigzagState => {
uOffset: gl.getUniformLocation(program, 'uOffset'),
uAmplitude: gl.getUniformLocation(program, 'uAmplitude'),
uWavelength: gl.getUniformLocation(program, 'uWavelength'),
+ uMaskToSourceAlpha: gl.getUniformLocation(program, 'uMaskToSourceAlpha'),
},
cachedPaletteKey: '',
palettePixelData: new Uint8Array(0),
@@ -491,7 +514,8 @@ export const zigzag = createEffect<ZigzagParams, ZigzagState>({
backend: 'webgl2',
calculateKey: (params) => {
const r = resolve(params);
- return `zigzag-${r.colors.join('|')}-${r.direction}-${r.thickness}-${r.spacing}-${r.angle}-${r.offset}-${r.amplitude}-${r.wavelength}`;
+ const maskSuffix = r.maskToSourceAlpha ? '-mask-to-source-alpha' : '';
+ return `zigzag-${r.colors.join('|')}-${r.direction}-${r.thickness}-${r.spacing}-${r.angle}-${r.offset}-${r.amplitude}-${r.wavelength}${maskSuffix}`;
},
setup: (target) => setupZigzag(target),
apply: ({source, width, height, params, state, flipSourceY}) => {
@@ -550,6 +574,8 @@ export const zigzag = createEffect<ZigzagParams, ZigzagState>({
if (uniforms.uOffset) gl.uniform1f(uniforms.uOffset, r.offset);
if (uniforms.uAmplitude) gl.uniform1f(uniforms.uAmplitude, r.amplitude);
if (uniforms.uWavelength) gl.uniform1f(uniforms.uWavelength, r.wavelength);
+ if (uniforms.uMaskToSourceAlpha)
+ gl.uniform1i(uniforms.uMaskToSourceAlpha, r.maskToSourceAlpha ? 1 : 0);
gl.bindVertexArray(vao);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);