Skip to content

🎥 Make videos programmatically with React

`@remotion/effects`: Add lines effect (#7795)

Jonny Burgerd60dc7d24864
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsx
index 0c8724ad91..a4e50d0273 100644
--- a/packages/docs/components/demos/index.tsx
+++ b/packages/docs/components/demos/index.tsx
@@ -32,6 +32,7 @@ import {
effectsDotGridDemo,
effectsInvertDemo,
effectsLightLeakDemo,
+ effectsLinesDemo,
effectsMirrorDemo,
effectsNoiseDemo,
effectsSaturationDemo,
@@ -114,6 +115,7 @@ const demos: DemoType[] = [
effectsMirrorDemo,
effectsNoiseDemo,
effectsScanlinesDemo,
+ effectsLinesDemo,
effectsScaleDemo,
effectsXyTranslateDemo,
effectsUvTranslateDemo,
diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.ts
index 9097d7f770..b78dfe7376 100644
--- a/packages/docs/components/demos/types.ts
+++ b/packages/docs/components/demos/types.ts
@@ -14,6 +14,7 @@ import {EffectsHalftonePreview} from '../effects/effects-halftone-preview';
import {EffectsHuePreview} from '../effects/effects-hue-preview';
import {EffectsInvertPreview} from '../effects/effects-invert-preview';
import {EffectsLightLeakPreview} from '../effects/effects-light-leak-preview';
+import {EffectsLinesPreview} from '../effects/effects-lines-preview';
import {EffectsMirrorPreview} from '../effects/effects-mirror-preview';
import {EffectsNoisePreview} from '../effects/effects-noise-preview';
import {EffectsSaturationPreview} from '../effects/effects-saturation-preview';
@@ -2115,6 +2116,63 @@ export const effectsScanlinesDemo: DemoType = {
],
};
+export const effectsLinesDemo: DemoType = {
+ comp: EffectsLinesPreview,
+ compHeight: 720,
+ compWidth: 1280,
+ durationInFrames: 1,
+ fps: 30,
+ id: 'effects-lines',
+ autoPlay: false,
+ controls: false,
+ logLevel: 'info',
+ options: [
+ {
+ name: 'direction',
+ type: 'enum',
+ values: ['horizontal', 'vertical'],
+ default: 'horizontal',
+ optional: 'no',
+ },
+ {
+ name: 'thickness',
+ type: 'numeric',
+ min: 0.1,
+ max: 400,
+ step: 0.1,
+ default: 40,
+ optional: 'no',
+ },
+ {
+ name: 'gap',
+ type: 'numeric',
+ min: 0,
+ max: 400,
+ step: 0.1,
+ default: 0,
+ optional: 'no',
+ },
+ {
+ name: 'angle',
+ type: 'numeric',
+ min: -180,
+ max: 180,
+ step: 1,
+ default: 20,
+ optional: 'no',
+ },
+ {
+ name: 'offset',
+ type: 'numeric',
+ min: -400,
+ max: 400,
+ step: 1,
+ default: 0,
+ optional: 'no',
+ },
+ ],
+};
+
export const effectsVignetteDemo: DemoType = {
comp: EffectsVignettePreview,
compHeight: 720,
diff --git a/packages/docs/components/effects/effects-lines-preview.tsx b/packages/docs/components/effects/effects-lines-preview.tsx
new file mode 100644
index 0000000000..d14f9d3c55
--- /dev/null
+++ b/packages/docs/components/effects/effects-lines-preview.tsx
@@ -0,0 +1,22 @@
+import {lines} from '@remotion/effects/lines';
+import React from 'react';
+import {CanvasImage} from 'remotion';
+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
+
+export const EffectsLinesPreview: React.FC<{
+ readonly direction: 'horizontal' | 'vertical';
+ readonly thickness: number;
+ readonly gap: number;
+ readonly angle: number;
+ readonly offset: number;
+}> = ({direction, thickness, gap, angle, offset}) => {
+ return (
+ <CanvasImage
+ src={EFFECTS_PREVIEW_IMAGE_SRC}
+ width={1280}
+ height={720}
+ fit="cover"
+ effects={[lines({direction, thickness, gap, angle, offset})]}
+ />
+ );
+};
diff --git a/packages/docs/docs/effects/lines.mdx b/packages/docs/docs/effects/lines.mdx
new file mode 100644
index 0000000000..36794f28f0
--- /dev/null
+++ b/packages/docs/docs/effects/lines.mdx
@@ -0,0 +1,106 @@
+---
+image: /generated/articles-docs-effects-lines.png
+slug: /effects/lines
+title: lines()
+sidebar_label: lines()
+crumb: '@remotion/effects'
+---
+
+# lines()<AvailableFrom v="4.0.470" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+Adds an alternating line pattern to canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).
+
+Each line color is composited over the source. Transparent colors leave the source unchanged.
+
+## Preview
+
+<Demo type="effects-lines" />
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {lines} from '@remotion/effects/lines';
+import {Video} from '@remotion/media';
+import {AbsoluteFill, useCurrentFrame} from 'remotion';
+
+export const MyComp: React.FC = () => {
+ const frame = useCurrentFrame();
+
+ return (
+ <AbsoluteFill>
+ <Video
+ src="https://remotion.media/video.mp4"
+ effects={[
+ lines({
+ colors: ['#dff4ff', 'transparent'],
+ direction: 'horizontal',
+ thickness: 40,
+ gap: 24,
+ angle: 20,
+ offset: frame * 2,
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+## API
+
+Pass an object with the following properties. You can also call `lines()` without arguments.
+
+### `colors?`
+
+An array of color strings for the line stripes. Colors are assigned cyclically. Must contain at least 2 colors.
+
+Defaults to `['#dff4ff', 'transparent']`.
+
+### `direction?`
+
+Direction of the unrotated lines. Either `'horizontal'` or `'vertical'`. Defaults to `'horizontal'`.
+
+### `thickness?`
+
+Thickness of each stripe in pixels. Defaults to `40`.
+
+### `gap?`
+
+Transparent gap in pixels between each stripe. Defaults to `0`.
+
+With `gap: 0` (the default), stripes are packed solid with no gap between them — colors are directly adjacent to each other.
+With `gap > 0`, a transparent band appears between each stripe, allowing the source content to show through.
+
+For example, with `colors: ['red', 'blue']` and `gap: 10`:
+- 40px red stripe
+- 10px transparent (source image visible)
+- 40px blue stripe
+- 10px transparent (source image visible)
+- …and so on
+
+### `angle?`
+
+Rotates the line pattern in degrees. Defaults to `0`.
+
+### `offset?`
+
+Offset in pixels. Defaults to `0`.
+
+Animate this value with [`useCurrentFrame()`](/docs/use-current-frame) to scroll the lines.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Requirements
+
+`lines()` 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)
+- [`scanlines()`](/docs/effects/scanlines)
+- [`dotGrid()`](/docs/effects/dot-grid)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/lines.ts)
diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsx
index 3bcdf5e269..1a9ae5eee8 100644
--- a/packages/docs/docs/effects/table-of-contents.tsx
+++ b/packages/docs/docs/effects/table-of-contents.tsx
@@ -193,6 +193,13 @@ const categories: {
name: 'lightLeak()',
description: 'Light leak overlay effect',
},
+ {
+ link: '/docs/effects/lines',
+ preview: '/img/effects-lines-preview.png',
+ alt: 'lines effect preview',
+ name: 'lines()',
+ description: 'Alternating line overlay effect',
+ },
{
link: '/docs/effects/noise',
preview: '/img/effects-noise-preview.png',
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 6c160aefda..f3d71329d1 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -282,6 +282,7 @@ const sidebars: SidebarsConfig = {
'effects/hue',
'effects/dot-grid',
'effects/invert',
+ 'effects/lines',
'effects/mirror',
'effects/noise',
'effects/saturation',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 98d688d2fc..cd57fedc41 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1763,15 +1763,6 @@ export const articles = [
noAi: false,
slug: 'effects/contrast',
},
- {
- id: 'effects/drop-shadow',
- title: 'dropShadow()',
- relativePath: 'docs/effects/drop-shadow.mdx',
- compId: 'articles-docs-effects-drop-shadow',
- crumb: '@remotion/effects',
- noAi: false,
- slug: 'effects/drop-shadow',
- },
{
id: 'effects/dot-grid',
title: 'dotGrid()',
@@ -1781,6 +1772,15 @@ export const articles = [
noAi: false,
slug: 'effects/dot-grid',
},
+ {
+ id: 'effects/drop-shadow',
+ title: 'dropShadow()',
+ relativePath: 'docs/effects/drop-shadow.mdx',
+ compId: 'articles-docs-effects-drop-shadow',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/drop-shadow',
+ },
{
id: 'effects/duotone',
title: 'duotone()',
@@ -1853,6 +1853,15 @@ export const articles = [
noAi: false,
slug: 'effects/invert',
},
+ {
+ id: 'effects/lines',
+ title: 'lines()',
+ relativePath: 'docs/effects/lines.mdx',
+ compId: 'articles-docs-effects-lines',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/lines',
+ },
{
id: 'effects/mirror',
title: 'mirror()',
diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsx
index 660b0d9576..967e994aa4 100644
--- a/packages/docs/src/remotion/Root.tsx
+++ b/packages/docs/src/remotion/Root.tsx
@@ -17,6 +17,7 @@ import {EffectsHalftonePreview} from '../../components/effects/effects-halftone-
import {EffectsHuePreview} from '../../components/effects/effects-hue-preview';
import {EffectsInvertPreview} from '../../components/effects/effects-invert-preview';
import {EffectsLightLeakPreview} from '../../components/effects/effects-light-leak-preview';
+import {EffectsLinesPreview} from '../../components/effects/effects-lines-preview';
import {EffectsMirrorPreview} from '../../components/effects/effects-mirror-preview';
import {EffectsNoisePreview} from '../../components/effects/effects-noise-preview';
import {EffectsSaturationPreview} from '../../components/effects/effects-saturation-preview';
@@ -315,6 +316,19 @@ export const RemotionRoot: React.FC = () => {
premultiply: false,
}}
/>
+ <Still
+ id="effects-lines-preview"
+ component={EffectsLinesPreview}
+ width={1280}
+ height={720}
+ defaultProps={{
+ direction: 'horizontal',
+ thickness: 40,
+ gap: 0,
+ angle: 20,
+ offset: 0,
+ }}
+ />
<Still
id="effects-shine-preview"
component={EffectsShinePreview}
diff --git a/packages/docs/static/generated/articles-docs-effects-lines.png b/packages/docs/static/generated/articles-docs-effects-lines.png
new file mode 100644
index 0000000000..35cb1c656c
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-lines.png differ
diff --git a/packages/docs/static/img/effects-lines-preview.png b/packages/docs/static/img/effects-lines-preview.png
new file mode 100644
index 0000000000..505e66f246
Binary files /dev/null and b/packages/docs/static/img/effects-lines-preview.png differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index efe8e82429..21a89397c4 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -21,6 +21,7 @@ const effectEntrypoints = [
'src/hue.ts',
'src/dot-grid.ts',
'src/invert.ts',
+ 'src/lines.ts',
'src/mirror.ts',
'src/noise.ts',
'src/saturation.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index ffbe121118..14c075e37b 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -99,6 +99,11 @@
"module": "./dist/esm/invert.mjs",
"import": "./dist/esm/invert.mjs"
},
+ "./lines": {
+ "types": "./dist/lines.d.ts",
+ "module": "./dist/esm/lines.mjs",
+ "import": "./dist/esm/lines.mjs"
+ },
"./dot-grid": {
"types": "./dist/dot-grid.d.ts",
"module": "./dist/esm/dot-grid.mjs",
@@ -202,6 +207,9 @@
"invert": [
"dist/invert.d.ts"
],
+ "lines": [
+ "dist/lines.d.ts"
+ ],
"dot-grid": [
"dist/dot-grid.d.ts"
],
diff --git a/packages/effects/src/lines.ts b/packages/effects/src/lines.ts
new file mode 100644
index 0000000000..06f8c6338d
--- /dev/null
+++ b/packages/effects/src/lines.ts
@@ -0,0 +1,522 @@
+import type {SequenceSchema} from 'remotion';
+import {Internals} from 'remotion';
+import {
+ assertOptionalFiniteNumber,
+ parseColorRgba,
+ type ParsedColorRgba,
+} from './color-utils.js';
+import {
+ assertEffectParamsObject,
+ assertRequiredColor,
+} from './validate-effect-param.js';
+
+const {createEffect, createWebGL2ContextError} = Internals;
+
+const LINE_DIRECTIONS = ['horizontal', 'vertical'] as const;
+
+const DEFAULT_COLORS = ['#dff4ff', 'transparent'] as const;
+const DEFAULT_DIRECTION = 'horizontal' as const;
+const DEFAULT_THICKNESS = 40 as const;
+const DEFAULT_GAP = 0 as const;
+const DEFAULT_ANGLE = 0 as const;
+const DEFAULT_OFFSET = 0 as const;
+
+export const linesSchema = {
+ direction: {
+ type: 'enum',
+ variants: {
+ horizontal: {},
+ vertical: {},
+ },
+ default: DEFAULT_DIRECTION,
+ description: 'Direction',
+ },
+ thickness: {
+ type: 'number',
+ min: 0.1,
+ max: 400,
+ step: 0.1,
+ default: DEFAULT_THICKNESS,
+ description: 'Thickness',
+ },
+ gap: {
+ type: 'number',
+ min: 0,
+ max: 400,
+ step: 0.1,
+ default: DEFAULT_GAP,
+ description: 'Gap',
+ },
+ angle: {
+ type: 'number',
+ min: -180,
+ max: 180,
+ step: 1,
+ default: DEFAULT_ANGLE,
+ description: 'Angle',
+ },
+ offset: {
+ type: 'number',
+ step: 0.1,
+ default: DEFAULT_OFFSET,
+ description: 'Offset',
+ },
+} as const satisfies SequenceSchema;
+
+export type LinesDirection = (typeof LINE_DIRECTIONS)[number];
+
+export type LinesParams = {
+ /** Stripe colors, assigned cyclically. Defaults to light blue and transparent. */
+ readonly colors?: readonly string[];
+ /** Line direction. Defaults to `horizontal`. */
+ readonly direction?: LinesDirection;
+ /** Thickness of each stripe in pixels. Defaults to `40`. */
+ readonly thickness?: number;
+ /** Transparent gap in pixels between each stripe. Defaults to `0` (stripes are packed solid). */
+ readonly gap?: number;
+ /** Rotates the line pattern in degrees. Defaults to `0`. */
+ readonly angle?: number;
+ /** Offset in pixels. Animate this value to scroll the lines. Defaults to `0`. */
+ readonly offset?: number;
+};
+
+type LinesResolved = {
+ colors: readonly string[];
+ direction: LinesDirection;
+ thickness: number;
+ spacing: number;
+ angle: number;
+ offset: number;
+};
+
+type LinesState = {
+ readonly gl: WebGL2RenderingContext;
+ readonly program: WebGLProgram;
+ readonly vao: WebGLVertexArrayObject;
+ readonly vbo: WebGLBuffer;
+ readonly sourceTexture: WebGLTexture;
+ readonly paletteTexture: WebGLTexture;
+ readonly colorCtx: CanvasRenderingContext2D;
+ readonly uniforms: {
+ readonly uSource: WebGLUniformLocation | null;
+ readonly uPalette: WebGLUniformLocation | null;
+ readonly uResolution: WebGLUniformLocation | null;
+ readonly uNumColors: WebGLUniformLocation | null;
+ readonly uDirection: WebGLUniformLocation | null;
+ readonly uThickness: WebGLUniformLocation | null;
+ readonly uSpacing: WebGLUniformLocation | null;
+ readonly uAngle: WebGLUniformLocation | null;
+ readonly uOffset: WebGLUniformLocation | null;
+ };
+ cachedPaletteKey: string;
+ palettePixelData: Uint8Array;
+};
+
+const resolve = (p: LinesParams): LinesResolved => {
+ const thickness = p.thickness ?? DEFAULT_THICKNESS;
+ const gap = p.gap ?? DEFAULT_GAP;
+
+ return {
+ colors: p.colors ?? DEFAULT_COLORS,
+ direction: p.direction ?? DEFAULT_DIRECTION,
+ thickness,
+ spacing: thickness + gap,
+ angle: p.angle ?? DEFAULT_ANGLE,
+ offset: p.offset ?? DEFAULT_OFFSET,
+ };
+};
+
+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 validatePositive = (value: number, name: string): void => {
+ if (value <= 0) {
+ throw new TypeError(
+ `"${name}" must be greater than 0, but got ${JSON.stringify(value)}`,
+ );
+ }
+};
+
+const validateNonNegative = (value: number, name: string): void => {
+ if (value < 0) {
+ throw new TypeError(
+ `"${name}" must be greater than or equal to 0, but got ${JSON.stringify(value)}`,
+ );
+ }
+};
+
+const validateColors = (colors: unknown): void => {
+ if (colors === undefined) {
+ return;
+ }
+
+ if (!Array.isArray(colors) || colors.length < 2) {
+ throw new TypeError(
+ `"colors" must be an array with at least 2 colors, but got ${JSON.stringify(colors)}`,
+ );
+ }
+
+ for (let i = 0; i < colors.length; i++) {
+ assertRequiredColor(colors[i], `colors[${i}]`);
+ }
+};
+
+const validateDirection = (direction: unknown): void => {
+ if (direction === undefined) {
+ return;
+ }
+
+ if (
+ typeof direction !== 'string' ||
+ !LINE_DIRECTIONS.includes(direction as LinesDirection)
+ ) {
+ throw new TypeError(
+ `"direction" must be ${formatEnum(LINE_DIRECTIONS)}, but got ${JSON.stringify(direction)}`,
+ );
+ }
+};
+
+const validateLinesParams = (params: LinesParams): void => {
+ assertEffectParamsObject(params, 'Lines');
+ validateColors(params.colors);
+ validateDirection(params.direction);
+ assertOptionalFiniteNumber(params.thickness, 'thickness');
+ assertOptionalFiniteNumber(params.gap, 'gap');
+ assertOptionalFiniteNumber(params.angle, 'angle');
+ assertOptionalFiniteNumber(params.offset, 'offset');
+
+ const thickness = params.thickness ?? DEFAULT_THICKNESS;
+ const gap = params.gap ?? DEFAULT_GAP;
+ validatePositive(thickness, 'thickness');
+ validateNonNegative(gap, 'gap');
+};
+
+const LINES_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 LINES_FS = /* glsl */ `#version 300 es
+precision highp float;
+
+in vec2 vUv;
+out vec4 fragColor;
+
+uniform sampler2D uSource;
+uniform sampler2D uPalette;
+uniform vec2 uResolution;
+uniform float uNumColors;
+uniform int uDirection;
+uniform float uThickness;
+uniform float uSpacing;
+uniform float uAngle;
+uniform float uOffset;
+
+void main() {
+ vec4 texColor = texture(uSource, vUv);
+ float thickness = max(uThickness, 0.001);
+float spacing = max(uSpacing, 0.001);
+float cycle = spacing * uNumColors;
+vec2 centered = vUv * uResolution - uResolution * 0.5;
+float s = sin(uAngle);
+float c = cos(uAngle);
+ vec2 rotated = vec2(
+ centered.x * c - centered.y * s,
+ centered.x * s + centered.y * c
+ );
+ float axis = uDirection == 0 ? rotated.y : rotated.x;
+ float position = mod(axis + uOffset, cycle);
+ if (position < 0.0) {
+ position += cycle;
+ }
+
+ float colorIndex = floor(position / spacing);
+ float inStripe = mod(position, spacing);
+ if (inStripe > thickness) {
+ fragColor = texColor;
+ return;
+ }
+
+ float texCoord = (colorIndex + 0.5) / uNumColors;
+ vec4 lineColor = texture(uPalette, vec2(texCoord, 0.5));
+ float lineAlpha = lineColor.a;
+ vec3 premultipliedLine = lineColor.rgb * lineAlpha;
+
+ fragColor = vec4(
+ premultipliedLine + texColor.rgb * (1.0 - lineAlpha),
+ lineAlpha + texColor.a * (1.0 - lineAlpha)
+ );
+}
+`;
+
+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(`Lines 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(`Lines program link failed: ${log ?? '(no log)'}`);
+ }
+
+ return program;
+};
+
+const createProgram = (
+ gl: WebGL2RenderingContext,
+ vertexSource: string,
+ fragmentSource: string,
+): WebGLProgram => {
+ const vs = compileShader(gl, gl.VERTEX_SHADER, vertexSource);
+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSource);
+ const program = linkProgram(gl, vs, fs);
+ gl.deleteShader(vs);
+ gl.deleteShader(fs);
+ return program;
+};
+
+const createTexture = (
+ gl: WebGL2RenderingContext,
+ filter: number,
+): WebGLTexture => {
+ 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_MIN_FILTER, filter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
+ 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.bindTexture(gl.TEXTURE_2D, null);
+ return texture;
+};
+
+const setupLines = (target: HTMLCanvasElement): LinesState => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('lines effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ const program = createProgram(gl, LINES_VS, LINES_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 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,
+ sourceTexture: createTexture(gl, gl.LINEAR),
+ paletteTexture: createTexture(gl, gl.NEAREST),
+ colorCtx,
+ uniforms: {
+ uSource: gl.getUniformLocation(program, 'uSource'),
+ uPalette: gl.getUniformLocation(program, 'uPalette'),
+ uResolution: gl.getUniformLocation(program, 'uResolution'),
+ uNumColors: gl.getUniformLocation(program, 'uNumColors'),
+ uDirection: gl.getUniformLocation(program, 'uDirection'),
+ uThickness: gl.getUniformLocation(program, 'uThickness'),
+ uSpacing: gl.getUniformLocation(program, 'uSpacing'),
+ uAngle: gl.getUniformLocation(program, 'uAngle'),
+ uOffset: gl.getUniformLocation(program, 'uOffset'),
+ },
+ cachedPaletteKey: '',
+ palettePixelData: new Uint8Array(0),
+ };
+};
+
+const updatePalette = (
+ state: LinesState,
+ colors: readonly string[],
+): boolean => {
+ const paletteKey = colors.join('|');
+ const paletteDirty = state.cachedPaletteKey !== paletteKey;
+ if (!paletteDirty) {
+ return false;
+ }
+
+ state.cachedPaletteKey = paletteKey;
+ const len = colors.length * 4;
+ if (state.palettePixelData.length !== len) {
+ state.palettePixelData = new Uint8Array(len);
+ }
+
+ const {palettePixelData} = state;
+ for (let i = 0; i < colors.length; i++) {
+ const color: ParsedColorRgba = parseColorRgba(state.colorCtx, colors[i]);
+ palettePixelData[i * 4] = color[0];
+ palettePixelData[i * 4 + 1] = color[1];
+ palettePixelData[i * 4 + 2] = color[2];
+ palettePixelData[i * 4 + 3] = color[3];
+ }
+
+ return true;
+};
+
+export const lines = createEffect<LinesParams, LinesState>({
+ type: 'remotion/lines',
+ label: 'lines()',
+ documentationLink: 'https://www.remotion.dev/docs/effects/lines',
+ backend: 'webgl2',
+ calculateKey: (params) => {
+ const r = resolve(params);
+ return `lines-${r.colors.join('|')}-${r.direction}-${r.thickness}-${r.spacing}-${r.angle}-${r.offset}`;
+ },
+ setup: (target) => setupLines(target),
+ apply: ({source, width, height, params, state, flipSourceY}) => {
+ const r = resolve(params);
+ const paletteDirty = updatePalette(state, r.colors);
+ const {gl, program, sourceTexture, paletteTexture, uniforms, vao} = state;
+
+ gl.viewport(0, 0, width, height);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, sourceTexture);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ source as TexImageSource,
+ );
+
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, paletteTexture);
+ if (paletteDirty) {
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ r.colors.length,
+ 1,
+ 0,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ state.palettePixelData,
+ );
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ }
+
+ gl.useProgram(program);
+ if (uniforms.uSource) gl.uniform1i(uniforms.uSource, 0);
+ if (uniforms.uPalette) gl.uniform1i(uniforms.uPalette, 1);
+ if (uniforms.uResolution) gl.uniform2f(uniforms.uResolution, width, height);
+ if (uniforms.uNumColors) gl.uniform1f(uniforms.uNumColors, r.colors.length);
+ if (uniforms.uDirection)
+ gl.uniform1i(uniforms.uDirection, r.direction === 'horizontal' ? 0 : 1);
+ if (uniforms.uThickness) gl.uniform1f(uniforms.uThickness, r.thickness);
+ if (uniforms.uSpacing) gl.uniform1f(uniforms.uSpacing, r.spacing);
+ if (uniforms.uAngle)
+ gl.uniform1f(uniforms.uAngle, (r.angle * Math.PI) / 180);
+ if (uniforms.uOffset) gl.uniform1f(uniforms.uOffset, r.offset);
+
+ gl.bindVertexArray(vao);
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ gl.bindVertexArray(null);
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ gl.useProgram(null);
+ },
+ cleanup: ({gl, program, vao, vbo, sourceTexture, paletteTexture}) => {
+ gl.deleteTexture(sourceTexture);
+ gl.deleteTexture(paletteTexture);
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+ },
+ schema: linesSchema,
+ validateParams: validateLinesParams,
+});
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index b85c47b36a..be331f378f 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -13,6 +13,7 @@ import {halftoneLinearGradient} from '../halftone-linear-gradient.js';
import {halftone} from '../halftone.js';
import {hue} from '../hue.js';
import {invert} from '../invert.js';
+import {lines} from '../lines.js';
import {mirror} from '../mirror.js';
import {noise} from '../noise.js';
import {saturation} from '../saturation.js';
@@ -65,6 +66,9 @@ test('@remotion/effects expose documentation links', () => {
expect(invert().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/invert',
);
+ expect(lines().definition.documentationLink).toBe(
+ 'https://www.remotion.dev/docs/effects/lines',
+ );
expect(dotGrid().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/dot-grid',
);
@@ -121,6 +125,7 @@ test('@remotion/effects expose API names as Studio labels', () => {
);
expect(hue().definition.label).toBe('hue()');
expect(invert().definition.label).toBe('invert()');
+ expect(lines().definition.label).toBe('lines()');
expect(dotGrid().definition.label).toBe('dotGrid()');
expect(mirror().definition.label).toBe('mirror()');
expect(noise().definition.label).toBe('noise()');
@@ -1056,6 +1061,87 @@ test('scanlines() parameters produce distinct effect keys', () => {
).toBe(6);
});
+test('lines() accepts default params', () => {
+ expect(() => lines()).not.toThrow();
+});
+
+test('lines() accepts custom colors', () => {
+ expect(() => lines({colors: ['#dff4ff', 'transparent']})).not.toThrow();
+});
+
+test('lines() rejects invalid colors', () => {
+ expect(() => lines({colors: ['#dff4ff']})).toThrow(
+ '"colors" must be an array with at least 2 colors',
+ );
+ expect(() => lines({colors: ['#dff4ff', '' as unknown as string]})).toThrow(
+ '"colors[1]" must be a non-empty string',
+ );
+});
+
+test('lines() rejects invalid direction', () => {
+ expect(() =>
+ lines({direction: 'diagonal' as unknown as 'horizontal'}),
+ ).toThrow('"direction" must be "horizontal" or "vertical"');
+});
+
+test('lines() rejects non-finite thickness', () => {
+ expect(() => lines({thickness: Number.NaN})).toThrow(
+ '"thickness" must be a finite number',
+ );
+});
+
+test('lines() rejects non-positive thickness', () => {
+ expect(() => lines({thickness: 0})).toThrow(
+ '"thickness" must be greater than 0',
+ );
+});
+
+test('lines() rejects non-finite gap', () => {
+ expect(() => lines({gap: Number.NaN})).toThrow(
+ '"gap" must be a finite number',
+ );
+});
+
+test('lines() rejects negative gap', () => {
+ expect(() => lines({gap: -1})).toThrow(
+ '"gap" must be greater than or equal to 0',
+ );
+});
+
+test('lines() rejects non-finite angle', () => {
+ expect(() => lines({angle: Number.NaN})).toThrow(
+ '"angle" must be a finite number',
+ );
+});
+
+test('lines() rejects non-finite offset', () => {
+ expect(() => lines({offset: Number.NaN})).toThrow(
+ '"offset" must be a finite number',
+ );
+});
+
+test('lines() parameters produce distinct effect keys', () => {
+ const defaultLines = lines();
+ const colored = lines({colors: ['#ffffff', 'transparent']});
+ const vertical = lines({direction: 'vertical'});
+ const thin = lines({thickness: 20});
+ const gapped = lines({gap: 24});
+ const angled = lines({angle: 45});
+ const shifted = lines({offset: 10});
+
+ expect(
+ new Set([
+ defaultLines.effectKey,
+ colored.effectKey,
+ vertical.effectKey,
+ thin.effectKey,
+ gapped.effectKey,
+ angled.effectKey,
+ shifted.effectKey,
+ ]).size,
+ ).toBe(7);
+});
+
test('hue() accepts default params', () => {
expect(() => hue()).not.toThrow();
});