Skip to content

🎥 Make videos programmatically with React

Add halftone gradient effect

Cursor Agent82c24b639243
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsx
index 1a21f4b2e3..b5bf1e2836 100644
--- a/packages/docs/components/demos/index.tsx
+++ b/packages/docs/components/demos/index.tsx
@@ -26,6 +26,7 @@ import {
effectsGlowDemo,
effectsGrayscaleDemo,
effectsHalftoneDemo,
+ effectsHalftoneGradientDemo,
effectsHueDemo,
effectsInvertDemo,
effectsLightLeakDemo,
@@ -113,6 +114,7 @@ const demos: DemoType[] = [
effectsChromaticAberrationDemo,
effectsWaveDemo,
effectsHalftoneDemo,
+ effectsHalftoneGradientDemo,
effectsStarburstDemo,
effectsLightLeakDemo,
arrowDemo,
diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.ts
index f987824394..2a7233f4f1 100644
--- a/packages/docs/components/demos/types.ts
+++ b/packages/docs/components/demos/types.ts
@@ -7,6 +7,7 @@ import {EffectsContrastPreview} from '../effects/effects-contrast-preview';
import {EffectsDuotonePreview} from '../effects/effects-duotone-preview';
import {EffectsGlowPreview} from '../effects/effects-glow-preview';
import {EffectsGrayscalePreview} from '../effects/effects-grayscale-preview';
+import {EffectsHalftoneGradientPreview} from '../effects/effects-halftone-gradient-preview';
import {EffectsHalftonePreview} from '../effects/effects-halftone-preview';
import {EffectsHuePreview} from '../effects/effects-hue-preview';
import {EffectsInvertPreview} from '../effects/effects-invert-preview';
@@ -2164,6 +2165,73 @@ export const effectsHalftoneDemo: DemoType = {
],
};
+export const effectsHalftoneGradientDemo: DemoType = {
+ comp: EffectsHalftoneGradientPreview,
+ compHeight: 720,
+ compWidth: 1280,
+ durationInFrames: 1,
+ fps: 30,
+ id: 'effects-halftone-gradient',
+ autoPlay: false,
+ controls: false,
+ logLevel: 'info',
+ options: [
+ {
+ name: 'firstStopDotSize',
+ type: 'numeric',
+ min: 0,
+ max: 80,
+ step: 1,
+ default: 0,
+ optional: 'no',
+ },
+ {
+ name: 'secondStopDotSize',
+ type: 'numeric',
+ min: 0,
+ max: 80,
+ step: 1,
+ default: 40,
+ optional: 'no',
+ },
+ {
+ name: 'gridSize',
+ type: 'numeric',
+ min: 1,
+ max: 80,
+ step: 1,
+ default: 24,
+ optional: 'no',
+ },
+ {
+ name: 'rotation',
+ type: 'numeric',
+ min: -180,
+ max: 180,
+ step: 1,
+ default: 0,
+ optional: 'no',
+ },
+ {
+ name: 'colorMode',
+ type: 'enum',
+ values: ['solid', 'source'],
+ default: 'solid',
+ optional: 'no',
+ },
+ {
+ name: 'dotColor',
+ type: 'color',
+ default: '#ffffff',
+ optional: 'no',
+ showIf: {
+ option: 'colorMode',
+ value: 'solid',
+ },
+ },
+ ],
+};
+
export const effectsStarburstDemo: DemoType = {
comp: EffectsStarburstPreview,
compHeight: 720,
diff --git a/packages/docs/components/effects/effects-halftone-gradient-preview.tsx b/packages/docs/components/effects/effects-halftone-gradient-preview.tsx
new file mode 100644
index 0000000000..e57c3fbc46
--- /dev/null
+++ b/packages/docs/components/effects/effects-halftone-gradient-preview.tsx
@@ -0,0 +1,50 @@
+import type {HalftoneGradientColorMode} from '@remotion/effects/halftone-gradient';
+import {halftoneGradient} from '@remotion/effects/halftone-gradient';
+import React from 'react';
+import {CanvasImage} from 'remotion';
+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
+
+const fullSize: React.CSSProperties = {
+ width: '100%',
+ height: '100%',
+};
+
+export const EffectsHalftoneGradientPreview: React.FC<{
+ readonly firstStopDotSize: number;
+ readonly secondStopDotSize: number;
+ readonly gridSize: number;
+ readonly rotation: number;
+ readonly colorMode: HalftoneGradientColorMode;
+ readonly dotColor: string;
+}> = ({
+ firstStopDotSize,
+ secondStopDotSize,
+ gridSize,
+ rotation,
+ colorMode,
+ dotColor,
+}) => {
+ const colorParams =
+ colorMode === 'source'
+ ? ({colorMode: 'source'} as const)
+ : ({colorMode: 'solid', dotColor} as const);
+
+ return (
+ <CanvasImage
+ src={EFFECTS_PREVIEW_IMAGE_SRC}
+ width={1280}
+ height={720}
+ fit="cover"
+ style={fullSize}
+ effects={[
+ halftoneGradient({
+ firstStopDotSize,
+ secondStopDotSize,
+ gridSize,
+ rotation,
+ ...colorParams,
+ }),
+ ]}
+ />
+ );
+};
diff --git a/packages/docs/docs/effects/halftone-gradient.mdx b/packages/docs/docs/effects/halftone-gradient.mdx
new file mode 100644
index 0000000000..c5b28b82cd
--- /dev/null
+++ b/packages/docs/docs/effects/halftone-gradient.mdx
@@ -0,0 +1,126 @@
+---
+image: /generated/articles-docs-effects-halftone-gradient.png
+slug: /effects/halftone-gradient
+title: halftoneGradient()
+sidebar_label: halftoneGradient()
+crumb: '@remotion/effects'
+---
+
+# halftoneGradient()<AvailableFrom v="4.0.468" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+A halftone effect that renders a grid of dots whose size changes across a linear gradient.
+
+Use it for dot-pattern wipes, overlays, and backgrounds on canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).
+
+## Preview
+
+<Demo type="effects-halftone-gradient" />
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {AbsoluteFill} from 'remotion';
+import {Video} from '@remotion/media';
+import {halftoneGradient} from '@remotion/effects/halftone-gradient';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Video
+ src="https://remotion.media/video.mp4"
+ effects={[
+ halftoneGradient({
+ firstStopDotSize: 0,
+ secondStopDotSize: 42,
+ gridSize: 24,
+ rotation: 20,
+ dotColor: '#111111',
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+To use colors from the previous effect in the chain, set `colorMode` to `'source'`:
+
+```tsx twoslash title="MyComp.tsx"
+import {AbsoluteFill} from 'remotion';
+import {Video} from '@remotion/media';
+import {halftoneGradient} from '@remotion/effects/halftone-gradient';
+
+export const MyComp: React.FC = () => {
+ return (
+ <AbsoluteFill>
+ <Video
+ src="https://remotion.media/video.mp4"
+ effects={[
+ halftoneGradient({
+ firstStopDotSize: 8,
+ secondStopDotSize: 44,
+ gridSize: 24,
+ rotation: -25,
+ colorMode: 'source',
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+## API
+
+Pass an object with the following properties. You can also call `halftoneGradient()` without arguments.
+
+### `firstStopDotSize?`
+
+Dot diameter in pixels on the first side of the gradient. Defaults to `0`. Must be at least `0`.
+
+Set this to `0` for no dots at the first side.
+
+### `secondStopDotSize?`
+
+Dot diameter in pixels on the opposite side of the gradient. Defaults to `40`. Must be at least `0`.
+
+Set both dot sizes to `0` for no coverage. Set both large enough to overlap neighboring cells for full coverage.
+
+### `gridSize?`
+
+Distance between adjacent dot centers in pixels. Defaults to `24`. Must be greater than `0`.
+
+### `rotation?`
+
+Rotation of the dot grid and linear gradient in degrees. Defaults to `0`.
+
+### `colorMode?`
+
+Controls how dots are colored. Defaults to `'solid'`.
+
+Allowed values are `'solid'` and `'source'`.
+
+When set to `'solid'`, each dot uses `dotColor`. When set to `'source'`, each dot uses the sampled source color at the grid cell.
+
+If `colorMode` is `'source'`, don't pass `dotColor`.
+
+### `dotColor?`
+
+Color of the dots when `colorMode` is `'solid'`. Defaults to `'black'`.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Requirements
+
+`halftoneGradient()` uses a WebGL2 backend. During renders, enable WebGL via [`Config.setChromiumOpenGlRenderer()`](/docs/config#setchromiumopenglrenderer) (for example `'angle'`). See [Using WebGL during renders](/docs/remotion/html-in-canvas#using-webgl-during-renders).
+
+## See also
+
+- [`@remotion/effects`](/docs/effects/api)
+- [`halftone()`](/docs/effects/halftone)
+- [HTML-in-canvas guide](/docs/html-in-canvas)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/halftone-gradient.ts)
diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsx
index 6c9aba4f07..fc9f72a7d2 100644
--- a/packages/docs/docs/effects/table-of-contents.tsx
+++ b/packages/docs/docs/effects/table-of-contents.tsx
@@ -165,6 +165,13 @@ const categories: {
name: 'halftone()',
description: 'Halftone dot grid effect',
},
+ {
+ link: '/docs/effects/halftone-gradient',
+ preview: '/img/effects-halftone-gradient-preview.jpg',
+ alt: 'halftone gradient effect preview',
+ name: 'halftoneGradient()',
+ description: 'Linear dot size gradient',
+ },
{
link: '/docs/starburst/starburst-effect',
preview: '/img/effects-starburst-preview.jpg',
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 0cb2fde325..053bf8313f 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -277,6 +277,7 @@ const sidebars: SidebarsConfig = {
'effects/glow',
'effects/grayscale',
'effects/halftone',
+ 'effects/halftone-gradient',
'effects/hue',
'effects/invert',
'effects/mirror',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index c4cf1cda44..290370cbef 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1790,6 +1790,15 @@ export const articles = [
noAi: false,
slug: 'effects/grayscale',
},
+ {
+ id: 'effects/halftone-gradient',
+ title: 'halftoneGradient()',
+ relativePath: 'docs/effects/halftone-gradient.mdx',
+ compId: 'articles-docs-effects-halftone-gradient',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/halftone-gradient',
+ },
{
id: 'effects/halftone',
title: 'halftone()',
diff --git a/packages/docs/static/generated/articles-docs-effects-halftone-gradient.png b/packages/docs/static/generated/articles-docs-effects-halftone-gradient.png
new file mode 100644
index 0000000000..8ce257eb9a
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-halftone-gradient.png differ
diff --git a/packages/docs/static/img/effects-halftone-gradient-preview.jpg b/packages/docs/static/img/effects-halftone-gradient-preview.jpg
new file mode 100644
index 0000000000..054ab0205e
Binary files /dev/null and b/packages/docs/static/img/effects-halftone-gradient-preview.jpg differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index ac6a6e62ed..8a1f223f5f 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -15,6 +15,7 @@ const effectEntrypoints = [
'src/duotone.ts',
'src/glow.ts',
'src/grayscale.ts',
+ 'src/halftone-gradient.ts',
'src/halftone.ts',
'src/hue.ts',
'src/invert.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index 689dc0a316..6e44882bc0 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -72,6 +72,11 @@
"module": "./dist/esm/halftone.mjs",
"import": "./dist/esm/halftone.mjs"
},
+ "./halftone-gradient": {
+ "types": "./dist/halftone-gradient.d.ts",
+ "module": "./dist/esm/halftone-gradient.mjs",
+ "import": "./dist/esm/halftone-gradient.mjs"
+ },
"./grayscale": {
"types": "./dist/grayscale.d.ts",
"module": "./dist/esm/grayscale.mjs",
@@ -155,6 +160,9 @@
"halftone": [
"dist/halftone.d.ts"
],
+ "halftone-gradient": [
+ "dist/halftone-gradient.d.ts"
+ ],
"grayscale": [
"dist/grayscale.d.ts"
],
diff --git a/packages/effects/src/halftone-gradient.ts b/packages/effects/src/halftone-gradient.ts
new file mode 100644
index 0000000000..ee0611ddfa
--- /dev/null
+++ b/packages/effects/src/halftone-gradient.ts
@@ -0,0 +1,515 @@
+import type {SequenceSchema} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ assertOptionalFiniteNumber,
+ parseColorRgba,
+ type ParsedColorRgba,
+} from './color-utils.js';
+import {
+ assertEffectParamsObject,
+ assertOptionalColor,
+} from './validate-effect-param.js';
+
+const {createEffect, createWebGL2ContextError} = Internals;
+
+const HALFTONE_GRADIENT_COLOR_MODES = ['solid', 'source'] as const;
+
+const DEFAULT_FIRST_STOP_DOT_SIZE = 0;
+const DEFAULT_SECOND_STOP_DOT_SIZE = 40;
+const DEFAULT_GRID_SIZE = 24;
+const DEFAULT_ROTATION = 0;
+const DEFAULT_DOT_COLOR = 'black';
+
+export const halftoneGradientSchema = {
+ firstStopDotSize: {
+ type: 'number',
+ min: 0,
+ max: 400,
+ step: 1,
+ default: DEFAULT_FIRST_STOP_DOT_SIZE,
+ description: 'First stop dot size',
+ },
+ secondStopDotSize: {
+ type: 'number',
+ min: 0,
+ max: 400,
+ step: 1,
+ default: DEFAULT_SECOND_STOP_DOT_SIZE,
+ description: 'Second stop dot size',
+ },
+ gridSize: {
+ type: 'number',
+ min: 1,
+ max: 400,
+ step: 1,
+ default: DEFAULT_GRID_SIZE,
+ description: 'Grid size',
+ },
+ rotation: {
+ type: 'number',
+ min: -180,
+ max: 180,
+ step: 1,
+ default: DEFAULT_ROTATION,
+ description: 'Rotation',
+ },
+ colorMode: {
+ type: 'enum',
+ default: 'solid' as const,
+ description: 'Color mode',
+ variants: {
+ solid: {
+ dotColor: {
+ type: 'color',
+ default: DEFAULT_DOT_COLOR,
+ description: 'Dot color',
+ },
+ },
+ source: {},
+ },
+ },
+} as const satisfies SequenceSchema;
+
+export type HalftoneGradientColorMode =
+ (typeof HALFTONE_GRADIENT_COLOR_MODES)[number];
+
+type HalftoneGradientCommonParams = {
+ /**
+ * Dot diameter at the first side of the gradient.
+ */
+ readonly firstStopDotSize?: number;
+ /**
+ * Dot diameter at the opposite side of the gradient.
+ */
+ readonly secondStopDotSize?: number;
+ /**
+ * Distance between adjacent dot centers.
+ */
+ readonly gridSize?: number;
+ /**
+ * Rotation of the dot grid and the linear gradient in degrees.
+ */
+ readonly rotation?: number;
+};
+
+export type HalftoneGradientParams = HalftoneGradientCommonParams &
+ (
+ | {
+ readonly colorMode?: 'solid';
+ /** Dot color. Defaults to black. */
+ readonly dotColor?: string;
+ }
+ | {
+ readonly colorMode: 'source';
+ }
+ );
+
+type HalftoneGradientResolved = {
+ firstStopDotSize: number;
+ secondStopDotSize: number;
+ gridSize: number;
+ rotation: number;
+ colorMode: HalftoneGradientColorMode;
+ dotColor: string;
+};
+
+const formatEnum = (variants: readonly string[]): string => {
+ if (variants.length === 2) {
+ return `"${variants[0]}" or "${variants[1]}"`;
+ }
+
+ return `${variants
+ .slice(0, -1)
+ .map((variant) => `"${variant}"`)
+ .join(', ')} or "${variants[variants.length - 1]}"`;
+};
+
+const assertOptionalEnum = <T extends string>(
+ value: unknown,
+ name: string,
+ variants: readonly T[],
+): void => {
+ if (value === undefined) {
+ return;
+ }
+
+ if (typeof value !== 'string' || !variants.includes(value as T)) {
+ throw new TypeError(`"${name}" must be ${formatEnum(variants)}`);
+ }
+};
+
+const resolve = (p: HalftoneGradientParams): HalftoneGradientResolved => ({
+ firstStopDotSize: p.firstStopDotSize ?? DEFAULT_FIRST_STOP_DOT_SIZE,
+ secondStopDotSize: p.secondStopDotSize ?? DEFAULT_SECOND_STOP_DOT_SIZE,
+ gridSize: p.gridSize ?? DEFAULT_GRID_SIZE,
+ rotation: p.rotation ?? DEFAULT_ROTATION,
+ colorMode: p.colorMode ?? 'solid',
+ dotColor:
+ 'dotColor' in p ? (p.dotColor ?? DEFAULT_DOT_COLOR) : DEFAULT_DOT_COLOR,
+});
+
+const validateNonNegative = (value: number, name: string): void => {
+ if (value < 0) {
+ throw new TypeError(
+ `"${name}" must be >= 0, but got ${JSON.stringify(value)}`,
+ );
+ }
+};
+
+const validatePositive = (value: number, name: string): void => {
+ if (value <= 0) {
+ throw new TypeError(
+ `"${name}" must be greater than 0, but got ${JSON.stringify(value)}`,
+ );
+ }
+};
+
+const validateHalftoneGradientParams = (
+ params: HalftoneGradientParams,
+): void => {
+ assertEffectParamsObject(params, 'Halftone gradient');
+ assertOptionalFiniteNumber(params.firstStopDotSize, 'firstStopDotSize');
+ assertOptionalFiniteNumber(params.secondStopDotSize, 'secondStopDotSize');
+ assertOptionalFiniteNumber(params.gridSize, 'gridSize');
+ assertOptionalFiniteNumber(params.rotation, 'rotation');
+ assertOptionalEnum(
+ params.colorMode,
+ 'colorMode',
+ HALFTONE_GRADIENT_COLOR_MODES,
+ );
+
+ if (params.colorMode === 'source' && 'dotColor' in params) {
+ throw new TypeError(
+ '"dotColor" can only be set when "colorMode" is "solid"',
+ );
+ }
+
+ assertOptionalColor(
+ 'dotColor' in params ? params.dotColor : undefined,
+ 'dotColor',
+ );
+
+ if (params.firstStopDotSize !== undefined) {
+ validateNonNegative(params.firstStopDotSize, 'firstStopDotSize');
+ }
+
+ if (params.secondStopDotSize !== undefined) {
+ validateNonNegative(params.secondStopDotSize, 'secondStopDotSize');
+ }
+
+ if (params.gridSize !== undefined) {
+ validatePositive(params.gridSize, 'gridSize');
+ }
+};
+
+const HALFTONE_GRADIENT_VS = /* glsl */ `#version 300 es
+in vec2 aPos;
+in vec2 aUv;
+out vec2 vUv;
+void main() {
+ vUv = aUv;
+ gl_Position = vec4(aPos, 0.0, 1.0);
+}
+`;
+
+const HALFTONE_GRADIENT_FS = /* glsl */ `#version 300 es
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D uSource;
+uniform vec2 uResolution;
+uniform float uFirstStopDotSize;
+uniform float uSecondStopDotSize;
+uniform float uGridSize;
+uniform float uRotation;
+uniform vec4 uColor;
+uniform bool uUseSourceColor;
+
+vec2 rotatePoint(vec2 point, float angle) {
+ float cosR = cos(angle);
+ float sinR = sin(angle);
+ return vec2(
+ point.x * cosR + point.y * sinR,
+ -point.x * sinR + point.y * cosR
+ );
+}
+
+vec2 unrotatePoint(vec2 point, float angle) {
+ float cosR = cos(angle);
+ float sinR = sin(angle);
+ return vec2(
+ point.x * cosR - point.y * sinR,
+ point.x * sinR + point.y * cosR
+ );
+}
+
+float gradientProgress(vec2 point, vec2 direction) {
+ float halfExtent = dot(abs(direction), uResolution * 0.5);
+ if (halfExtent <= 0.0) {
+ return 0.0;
+ }
+
+ return clamp(dot(point, direction) / (halfExtent * 2.0) + 0.5, 0.0, 1.0);
+}
+
+void main() {
+ vec2 fragPos = vUv * uResolution;
+ vec2 center = uResolution * 0.5;
+ vec2 relative = fragPos - center;
+
+ vec2 gridPos = rotatePoint(relative, uRotation);
+ float gridSize = max(uGridSize, 0.001);
+ vec2 cellIndex = floor(gridPos / gridSize + 0.5);
+ vec2 gridCenter = cellIndex * gridSize;
+ vec2 canvasCenter = center + unrotatePoint(gridCenter, uRotation);
+
+ vec2 direction = vec2(cos(uRotation), sin(uRotation));
+ float progress = gradientProgress(canvasCenter - center, direction);
+ float dotSize = mix(uFirstStopDotSize, uSecondStopDotSize, progress);
+
+ if (dotSize <= 0.01) {
+ fragColor = vec4(0.0);
+ return;
+ }
+
+ vec2 diff = gridPos - gridCenter;
+ float radius = dotSize * 0.5;
+ float coverage = 1.0 - smoothstep(radius - 0.75, radius + 0.75, length(diff));
+
+ vec2 sampleUv = clamp(canvasCenter / uResolution, vec2(0.0), vec2(1.0));
+ vec4 texColor = texture(uSource, sampleUv);
+ fragColor = (uUseSourceColor ? texColor : uColor) * coverage;
+}
+`;
+
+type HalftoneGradientState = {
+ gl: WebGL2RenderingContext;
+ program: WebGLProgram;
+ vao: WebGLVertexArrayObject;
+ vbo: WebGLBuffer;
+ texture: WebGLTexture;
+ uSource: WebGLUniformLocation | null;
+ uResolution: WebGLUniformLocation | null;
+ uFirstStopDotSize: WebGLUniformLocation | null;
+ uSecondStopDotSize: WebGLUniformLocation | null;
+ uGridSize: WebGLUniformLocation | null;
+ uRotation: WebGLUniformLocation | null;
+ uColor: WebGLUniformLocation | null;
+ uUseSourceColor: WebGLUniformLocation | null;
+ colorCtx: CanvasRenderingContext2D;
+ cachedColorStr: string;
+ cachedColorRgba: ParsedColorRgba;
+};
+
+const compileShader = (
+ gl: WebGL2RenderingContext,
+ type: number,
+ source: string,
+): WebGLShader => {
+ const shader = gl.createShader(type);
+ if (!shader) {
+ throw new Error('Failed to create WebGL shader');
+ }
+
+ gl.shaderSource(shader, source);
+ gl.compileShader(shader);
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+ const log = gl.getShaderInfoLog(shader);
+ gl.deleteShader(shader);
+ throw new Error(
+ `Halftone gradient shader compile failed: ${log ?? '(no log)'}`,
+ );
+ }
+
+ return shader;
+};
+
+const linkProgram = (
+ gl: WebGL2RenderingContext,
+ vs: WebGLShader,
+ fs: WebGLShader,
+): WebGLProgram => {
+ const program = gl.createProgram();
+ if (!program) {
+ throw new Error('Failed to create WebGL program');
+ }
+
+ gl.attachShader(program, vs);
+ gl.attachShader(program, fs);
+ gl.linkProgram(program);
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+ const log = gl.getProgramInfoLog(program);
+ gl.deleteProgram(program);
+ throw new Error(
+ `Halftone gradient program link failed: ${log ?? '(no log)'}`,
+ );
+ }
+
+ return program;
+};
+
+export const halftoneGradient = createEffect<
+ HalftoneGradientParams,
+ HalftoneGradientState
+>({
+ type: 'remotion/halftone-gradient',
+ label: 'halftoneGradient()',
+ documentationLink: 'https://www.remotion.dev/docs/effects/halftone-gradient',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ return `halftone-gradient-${r.firstStopDotSize}-${r.secondStopDotSize}-${r.gridSize}-${r.rotation}-${r.colorMode}-${r.dotColor}`;
+ },
+ setup: (target) => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('halftone gradient effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ const vs = compileShader(gl, gl.VERTEX_SHADER, HALFTONE_GRADIENT_VS);
+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, HALFTONE_GRADIENT_FS);
+ const program = linkProgram(gl, vs, fs);
+ gl.deleteShader(vs);
+ gl.deleteShader(fs);
+
+ const vao = gl.createVertexArray();
+ if (!vao) {
+ throw new Error('Failed to create WebGL vertex array');
+ }
+
+ gl.bindVertexArray(vao);
+
+ const data = new Float32Array([
+ -1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1,
+ ]);
+
+ const vbo = gl.createBuffer();
+ if (!vbo) {
+ throw new Error('Failed to create WebGL buffer');
+ }
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
+ gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
+
+ const aPos = gl.getAttribLocation(program, 'aPos');
+ const aUv = gl.getAttribLocation(program, 'aUv');
+ gl.enableVertexAttribArray(aPos);
+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 16, 0);
+ gl.enableVertexAttribArray(aUv);
+ gl.vertexAttribPointer(aUv, 2, gl.FLOAT, false, 16, 8);
+
+ gl.bindVertexArray(null);
+
+ const texture = gl.createTexture();
+ if (!texture) {
+ throw new Error('Failed to create WebGL texture');
+ }
+
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+
+ const colorCanvas = document.createElement('canvas');
+ colorCanvas.width = 1;
+ colorCanvas.height = 1;
+ const colorCtx = colorCanvas.getContext('2d', {willReadFrequently: true});
+ if (!colorCtx) {
+ throw new Error('Failed to acquire 2D context for color parsing');
+ }
+
+ return {
+ gl,
+ program,
+ vao,
+ vbo,
+ texture,
+ uSource: gl.getUniformLocation(program, 'uSource'),
+ uResolution: gl.getUniformLocation(program, 'uResolution'),
+ uFirstStopDotSize: gl.getUniformLocation(program, 'uFirstStopDotSize'),
+ uSecondStopDotSize: gl.getUniformLocation(program, 'uSecondStopDotSize'),
+ uGridSize: gl.getUniformLocation(program, 'uGridSize'),
+ uRotation: gl.getUniformLocation(program, 'uRotation'),
+ uColor: gl.getUniformLocation(program, 'uColor'),
+ uUseSourceColor: gl.getUniformLocation(program, 'uUseSourceColor'),
+ colorCtx,
+ cachedColorStr: '',
+ cachedColorRgba: [0, 0, 0, 255],
+ };
+ },
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+ const {gl, program, vao, texture} = state;
+
+ if (state.cachedColorStr !== r.dotColor) {
+ state.cachedColorStr = r.dotColor;
+ state.cachedColorRgba = parseColorRgba(state.colorCtx, r.dotColor);
+ }
+
+ const [cr, cg, cb, ca] = state.cachedColorRgba;
+ const caNormalized = ca / 255;
+
+ gl.viewport(0, 0, width, height);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.useProgram(program);
+ gl.bindVertexArray(vao);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, texture);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ source as TexImageSource,
+ );
+
+ if (state.uSource) gl.uniform1i(state.uSource, 0);
+ if (state.uResolution) gl.uniform2f(state.uResolution, width, height);
+ if (state.uFirstStopDotSize)
+ gl.uniform1f(state.uFirstStopDotSize, r.firstStopDotSize);
+ if (state.uSecondStopDotSize)
+ gl.uniform1f(state.uSecondStopDotSize, r.secondStopDotSize);
+ if (state.uGridSize) gl.uniform1f(state.uGridSize, r.gridSize);
+ if (state.uRotation)
+ gl.uniform1f(state.uRotation, (r.rotation * Math.PI) / 180);
+ if (state.uColor)
+ gl.uniform4f(
+ state.uColor,
+ (cr / 255) * caNormalized,
+ (cg / 255) * caNormalized,
+ (cb / 255) * caNormalized,
+ caNormalized,
+ );
+ if (state.uUseSourceColor)
+ gl.uniform1i(state.uUseSourceColor, r.colorMode === 'source' ? 1 : 0);
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+
+ gl.bindVertexArray(null);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.useProgram(null);
+ },
+ cleanup: ({gl, program, vao, vbo, texture}) => {
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+ gl.deleteTexture(texture);
+ },
+ schema: halftoneGradientSchema,
+ validateParams: validateHalftoneGradientParams,
+});
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index 29611f334d..fe81fcde64 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -7,6 +7,7 @@ import {contrast} from '../contrast.js';
import {duotone} from '../duotone.js';
import {glow} from '../glow/index.js';
import {grayscale} from '../grayscale.js';
+import {halftoneGradient} from '../halftone-gradient.js';
import {halftone} from '../halftone.js';
import {hue} from '../hue.js';
import {invert} from '../invert.js';
@@ -47,6 +48,9 @@ test('@remotion/effects expose documentation links', () => {
expect(halftone().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/halftone',
);
+ expect(halftoneGradient().definition.documentationLink).toBe(
+ 'https://www.remotion.dev/docs/effects/halftone-gradient',
+ );
expect(hue().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/hue',
);
@@ -91,6 +95,7 @@ test('@remotion/effects expose API names as Studio labels', () => {
expect(duotone().definition.label).toBe('duotone()');
expect(grayscale().definition.label).toBe('grayscale()');
expect(halftone().definition.label).toBe('halftone()');
+ expect(halftoneGradient().definition.label).toBe('halftoneGradient()');
expect(hue().definition.label).toBe('hue()');
expect(invert().definition.label).toBe('invert()');
expect(mirror().definition.label).toBe('mirror()');
@@ -616,6 +621,72 @@ test('halftone() rejects dotColor for source color mode', () => {
).toThrow('"dotColor" can only be set when "colorMode" is "solid"');
});
+test('halftoneGradient() accepts default params', () => {
+ expect(() => halftoneGradient()).not.toThrow();
+});
+
+test('halftoneGradient() rejects first stop dot size below range', () => {
+ expect(() => halftoneGradient({firstStopDotSize: -1})).toThrow(
+ '"firstStopDotSize" must be >= 0',
+ );
+});
+
+test('halftoneGradient() rejects second stop dot size below range', () => {
+ expect(() => halftoneGradient({secondStopDotSize: -1})).toThrow(
+ '"secondStopDotSize" must be >= 0',
+ );
+});
+
+test('halftoneGradient() rejects non-positive grid size', () => {
+ expect(() => halftoneGradient({gridSize: 0})).toThrow(
+ '"gridSize" must be greater than 0',
+ );
+});
+
+test('halftoneGradient() rejects color outside the enum', () => {
+ expect(() =>
+ halftoneGradient({
+ colorMode: 'cmyk' as Exclude<
+ Parameters<typeof halftoneGradient>[0],
+ undefined
+ >['colorMode'],
+ }),
+ ).toThrow('"colorMode" must be "solid" or "source"');
+});
+
+test('halftoneGradient() rejects empty dotColor strings', () => {
+ expect(() => halftoneGradient({dotColor: ''})).toThrow(
+ '"dotColor" must be a non-empty string, but got ""',
+ );
+});
+
+test('halftoneGradient() rejects dotColor for source color mode', () => {
+ expect(() =>
+ halftoneGradient({
+ colorMode: 'source',
+ dotColor: 'black',
+ } as Parameters<typeof halftoneGradient>[0]),
+ ).toThrow('"dotColor" can only be set when "colorMode" is "solid"');
+});
+
+test('halftoneGradient() parameters produce distinct effect keys', () => {
+ const defaultGradient = halftoneGradient();
+ const shiftedFirstStop = halftoneGradient({firstStopDotSize: 8});
+ const shiftedSecondStop = halftoneGradient({secondStopDotSize: 20});
+ const rotated = halftoneGradient({rotation: 45});
+ const sourceColor = halftoneGradient({colorMode: 'source'});
+
+ expect(
+ new Set([
+ defaultGradient.effectKey,
+ shiftedFirstStop.effectKey,
+ shiftedSecondStop.effectKey,
+ rotated.effectKey,
+ sourceColor.effectKey,
+ ]).size,
+ ).toBe(5);
+});
+
test('invert() accepts default params', () => {
expect(() => invert()).not.toThrow();
});