Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/effects`: Add `zigzag()` effect (#7952)

Jonny Burgerb82041f96bc7
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.ts
index 4085bfc638..71ff88d097 100644
--- a/packages/docs/components/effects-demos/registry.ts
+++ b/packages/docs/components/effects-demos/registry.ts
@@ -28,6 +28,7 @@ import {vignette} from '@remotion/effects/vignette';
import {wave} from '@remotion/effects/wave';
import {waves} from '@remotion/effects/waves';
import {whiteNoise} from '@remotion/effects/white-noise';
+import {zigzag} from '@remotion/effects/zigzag';
import {lightLeakEffectSchema} from '@remotion/light-leaks';
import {starburstEffectSchema} from '@remotion/starburst';
import {EffectsBarrelDistortionPreview} from '../effects/effects-barrel-distortion-preview';
@@ -65,6 +66,7 @@ import {EffectsVignettePreview} from '../effects/effects-vignette-preview';
import {EffectsWavePreview} from '../effects/effects-wave-preview';
import {EffectsWavesPreview} from '../effects/effects-waves-preview';
import {EffectsWhiteNoisePreview} from '../effects/effects-white-noise-preview';
+import {EffectsZigzagPreview} from '../effects/effects-zigzag-preview';
import type {EffectsDemoType} from './types';
const defaults = {
@@ -303,9 +305,19 @@ export const effectsDemos: EffectsDemoType[] = [
{
...defaults,
id: 'effects-waves',
+ effectName: 'waves',
+ effectImportPath: '@remotion/effects/waves',
comp: EffectsWavesPreview,
schema: waves().definition.schema,
},
+ {
+ ...defaults,
+ id: 'effects-zigzag',
+ effectName: 'zigzag',
+ effectImportPath: '@remotion/effects/zigzag',
+ comp: EffectsZigzagPreview,
+ schema: zigzag().definition.schema,
+ },
{
...defaults,
id: 'effects-halftone',
diff --git a/packages/docs/components/effects/effects-zigzag-preview.tsx b/packages/docs/components/effects/effects-zigzag-preview.tsx
new file mode 100644
index 0000000000..2bd9602a5c
--- /dev/null
+++ b/packages/docs/components/effects/effects-zigzag-preview.tsx
@@ -0,0 +1,33 @@
+import {zigzag} from '@remotion/effects/zigzag';
+import React from 'react';
+import {Solid, useVideoConfig} from 'remotion';
+
+export const EffectsZigzagPreview: React.FC<{
+ readonly direction: 'horizontal' | 'vertical';
+ readonly thickness: number;
+ readonly gap: number;
+ readonly angle: number;
+ readonly offset: number;
+ readonly amplitude: number;
+ readonly wavelength: number;
+}> = ({direction, thickness, gap, angle, offset, amplitude, wavelength}) => {
+ const {width, height} = useVideoConfig();
+
+ return (
+ <Solid
+ width={width}
+ height={height}
+ effects={[
+ zigzag({
+ direction,
+ thickness,
+ gap,
+ angle,
+ offset,
+ amplitude,
+ wavelength,
+ }),
+ ]}
+ />
+ );
+};
diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsx
index e4f81f67bb..907c78366b 100644
--- a/packages/docs/docs/effects/table-of-contents.tsx
+++ b/packages/docs/docs/effects/table-of-contents.tsx
@@ -264,6 +264,13 @@ const categories: {
name: 'waves()',
description: 'Wavy band pattern effect',
},
+ {
+ link: '/docs/effects/zigzag',
+ preview: '/img/effects-zigzag-preview.png',
+ alt: 'zigzag effect preview',
+ name: 'zigzag()',
+ description: 'Zig-zag band pattern effect',
+ },
{
link: '/docs/light-leaks/light-leak-effect',
preview: '/img/effects-light-leak-preview.png',
diff --git a/packages/docs/docs/effects/zigzag.mdx b/packages/docs/docs/effects/zigzag.mdx
new file mode 100644
index 0000000000..e542b7ecd9
--- /dev/null
+++ b/packages/docs/docs/effects/zigzag.mdx
@@ -0,0 +1,109 @@
+---
+image: /generated/articles-docs-effects-zigzag.png
+slug: /effects/zigzag
+title: zigzag()
+sidebar_label: zigzag()
+crumb: '@remotion/effects'
+---
+
+# zigzag()<AvailableFrom v="4.0.471" />
+
+_Part of the [`@remotion/effects`](/docs/effects/api) package._
+
+Adds repeating zig-zag bands to canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).
+
+It uses the same band controls as [`lines()`](/docs/effects/lines), and the same displacement controls as [`waves()`](/docs/effects/waves), but uses sharp triangular turns.
+
+## Preview
+
+<EffectsDemo type="effects-zigzag" />
+
+## Example
+
+```tsx twoslash title="MyComp.tsx"
+import {zigzag} from '@remotion/effects/zigzag';
+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={[
+ zigzag({
+ colors: ['#d7b8ff', 'transparent'],
+ direction: 'horizontal',
+ thickness: 40,
+ gap: 0,
+ angle: 0,
+ offset: frame * 2,
+ amplitude: 40,
+ wavelength: 160,
+ }),
+ ]}
+ />
+ </AbsoluteFill>
+ );
+};
+```
+
+## API
+
+Pass an object with the following properties. You can also call `zigzag()` without arguments.
+
+### `colors?`
+
+An array of color strings for the bands. Colors are assigned cyclically. Must contain at least 2 colors.
+
+Defaults to `['#dff4ff', '#7cc6ff']`.
+
+### `direction?`
+
+Base band direction before zig-zag displacement. Either `'horizontal'` or `'vertical'`. Defaults to `'horizontal'`.
+
+### `thickness?`
+
+Thickness of each band in pixels. Defaults to `40`.
+
+### `gap?`
+
+Transparent gap in pixels between each band. Defaults to `0`.
+
+With `gap: 0` (the default), bands 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.
+
+### `angle?`
+
+Rotates the 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 bands.
+
+### `amplitude?`
+
+Zig-zag displacement in pixels. Defaults to `40`.
+
+### `wavelength?`
+
+Distance in pixels before the zig-zag repeats. Defaults to `160`. Must be greater than `0`.
+
+### `disabled?`
+
+When `true`, the effect is skipped. Defaults to `false`.
+
+## Requirements
+
+`zigzag()` 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)
+- [`lines()`](/docs/effects/lines)
+- [`waves()`](/docs/effects/waves)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/zigzag.ts)
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 059b8972c1..297d8559bc 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -297,6 +297,7 @@ const sidebars: SidebarsConfig = {
'effects/vignette',
'effects/wave',
'effects/waves',
+ 'effects/zigzag',
'effects/white-noise',
'effects/xy-translate',
],
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index dc049cf245..14b15cceab 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -2006,6 +2006,15 @@ export const articles = [
noAi: false,
slug: 'effects/xy-translate',
},
+ {
+ id: 'effects/zigzag',
+ title: 'zigzag()',
+ relativePath: 'docs/effects/zigzag.mdx',
+ compId: 'articles-docs-effects-zigzag',
+ crumb: '@remotion/effects',
+ noAi: false,
+ slug: 'effects/zigzag',
+ },
{
id: 'electron',
title: 'Using Remotion in Electron',
diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsx
index d14f2b698c..2a0925c7b8 100644
--- a/packages/docs/src/remotion/Root.tsx
+++ b/packages/docs/src/remotion/Root.tsx
@@ -37,6 +37,7 @@ import {EffectsVignettePreview} from '../../components/effects/effects-vignette-
import {EffectsWavePreview} from '../../components/effects/effects-wave-preview';
import {EffectsWavesPreview} from '../../components/effects/effects-waves-preview';
import {EffectsWhiteNoisePreview} from '../../components/effects/effects-white-noise-preview';
+import {EffectsZigzagPreview} from '../../components/effects/effects-zigzag-preview';
import {articles} from '../data/articles';
import {AllTemplates} from './AllTemplates';
import {Article} from './Article';
@@ -382,6 +383,21 @@ export const RemotionRoot: React.FC = () => {
phase: 45,
}}
/>
+ <Still
+ id="effects-zigzag-preview"
+ component={EffectsZigzagPreview}
+ width={1280}
+ height={720}
+ defaultProps={{
+ direction: 'horizontal',
+ thickness: 40,
+ gap: 0,
+ angle: 0,
+ offset: 0,
+ amplitude: 40,
+ wavelength: 160,
+ }}
+ />
<Still
id="effects-shine-preview"
component={EffectsShinePreview}
diff --git a/packages/docs/static/generated/articles-docs-effects-zigzag.png b/packages/docs/static/generated/articles-docs-effects-zigzag.png
new file mode 100644
index 0000000000..274afdd391
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-zigzag.png differ
diff --git a/packages/docs/static/img/effects-zigzag-preview.png b/packages/docs/static/img/effects-zigzag-preview.png
new file mode 100644
index 0000000000..5b5a80e312
Binary files /dev/null and b/packages/docs/static/img/effects-zigzag-preview.png differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index f69d7da670..dada80bdfa 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -36,6 +36,7 @@ const effectEntrypoints = [
'src/vignette.ts',
'src/wave.ts',
'src/waves.ts',
+ 'src/zigzag.ts',
'src/white-noise.ts',
];
diff --git a/packages/effects/package.json b/packages/effects/package.json
index f3d7deaf77..abfc287705 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -184,6 +184,11 @@
"module": "./dist/esm/white-noise.mjs",
"import": "./dist/esm/white-noise.mjs"
},
+ "./zigzag": {
+ "types": "./dist/zigzag.d.ts",
+ "module": "./dist/esm/zigzag.mjs",
+ "import": "./dist/esm/zigzag.mjs"
+ },
"./package.json": "./package.json"
},
"typesVersions": {
@@ -275,6 +280,9 @@
"waves": [
"dist/waves.d.ts"
],
+ "zigzag": [
+ "dist/zigzag.d.ts"
+ ],
"white-noise": [
"dist/white-noise.d.ts"
]
diff --git a/packages/effects/src/index.ts b/packages/effects/src/index.ts
index cb0ff5c3b5..13d293cb00 100644
--- a/packages/effects/src/index.ts
+++ b/packages/effects/src/index.ts
@@ -1 +1 @@
-export {};
+export {zigzag, type ZigzagDirection, type ZigzagParams} from './zigzag.js';
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index 95b8d98566..880698edad 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -29,6 +29,7 @@ import {vignette} from '../vignette.js';
import {wave} from '../wave/index.js';
import {waves} from '../waves.js';
import {whiteNoise} from '../white-noise.js';
+import {zigzag} from '../zigzag.js';
test('@remotion/effects expose documentation links', () => {
expect(barrelDistortion().definition.documentationLink).toBe(
@@ -121,6 +122,9 @@ test('@remotion/effects expose documentation links', () => {
expect(waves().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/waves',
);
+ expect(zigzag().definition.documentationLink).toBe(
+ 'https://www.remotion.dev/docs/effects/zigzag',
+ );
expect(whiteNoise().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/white-noise',
);
@@ -158,6 +162,7 @@ test('@remotion/effects expose API names as Studio labels', () => {
expect(xyTranslate().definition.label).toBe('xyTranslate()');
expect(wave().definition.label).toBe('wave()');
expect(waves().definition.label).toBe('waves()');
+ expect(zigzag().definition.label).toBe('zigzag()');
expect(whiteNoise().definition.label).toBe('whiteNoise()');
});
@@ -220,8 +225,8 @@ test('fisheye() rejects non-positive zoom', () => {
});
test('fisheye() rejects invalid center', () => {
- // @ts-expect-error – wrong shape on purpose
- expect(() => fisheye({center: [0.5]})).toThrow(
+ const invalidCenter = [0.5] as unknown as [number, number];
+ expect(() => fisheye({center: invalidCenter})).toThrow(
'"center" must be a [number, number] tuple',
);
});
@@ -430,6 +435,69 @@ test('waves() parameters produce distinct effect keys', () => {
).toBe(10);
});
+test('zigzag() accepts default params', () => {
+ expect(() => zigzag()).not.toThrow();
+});
+
+test('zigzag() rejects invalid colors', () => {
+ expect(() => zigzag({colors: ['#dff4ff']})).toThrow(
+ '"colors" must be an array with at least 2 colors',
+ );
+ expect(() => zigzag({colors: ['#dff4ff', '' as unknown as string]})).toThrow(
+ '"colors[1]" must be a non-empty string',
+ );
+});
+
+test('zigzag() rejects invalid direction', () => {
+ expect(() =>
+ zigzag({direction: 'diagonal' as unknown as 'horizontal'}),
+ ).toThrow('"direction" must be "horizontal" or "vertical"');
+});
+
+test('zigzag() rejects non-positive wavelength', () => {
+ expect(() => zigzag({wavelength: 0})).toThrow(
+ '"wavelength" must be greater than 0',
+ );
+});
+
+test('zigzag() rejects negative amplitude', () => {
+ expect(() => zigzag({amplitude: -1})).toThrow(
+ '"amplitude" must be greater than or equal to 0',
+ );
+});
+
+test('zigzag() rejects non-positive thickness', () => {
+ expect(() => zigzag({thickness: 0})).toThrow(
+ '"thickness" must be greater than 0',
+ );
+});
+
+test('zigzag() parameters produce distinct effect keys', () => {
+ const defaults = zigzag();
+ const colored = zigzag({colors: ['#ffffff', 'transparent']});
+ const vertical = zigzag({direction: 'vertical'});
+ const thin = zigzag({thickness: 20});
+ const gapped = zigzag({gap: 24});
+ const angled = zigzag({angle: 45});
+ const shifted = zigzag({offset: 10});
+ const stronger = zigzag({amplitude: 30});
+ const longer = zigzag({wavelength: 220});
+
+ expect(
+ new Set([
+ defaults.effectKey,
+ colored.effectKey,
+ vertical.effectKey,
+ thin.effectKey,
+ gapped.effectKey,
+ angled.effectKey,
+ shifted.effectKey,
+ stronger.effectKey,
+ longer.effectKey,
+ ]).size,
+ ).toBe(9);
+});
+
test('whiteNoise() accepts default params', () => {
expect(() => whiteNoise()).not.toThrow();
});
diff --git a/packages/effects/src/zigzag.ts b/packages/effects/src/zigzag.ts
new file mode 100644
index 0000000000..28b365fb35
--- /dev/null
+++ b/packages/effects/src/zigzag.ts
@@ -0,0 +1,573 @@
+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 ZIGZAG_DIRECTIONS = ['horizontal', 'vertical'] as const;
+
+const DEFAULT_COLORS = ['#dff4ff', '#7cc6ff'] 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;
+const DEFAULT_AMPLITUDE = 40 as const;
+const DEFAULT_WAVELENGTH = 160 as const;
+
+export const zigzagSchema = {
+ 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',
+ },
+ amplitude: {
+ type: 'number',
+ min: 0,
+ max: 500,
+ step: 0.1,
+ default: DEFAULT_AMPLITUDE,
+ description: 'Amplitude',
+ },
+ wavelength: {
+ type: 'number',
+ min: 1,
+ max: 2000,
+ step: 1,
+ default: DEFAULT_WAVELENGTH,
+ description: 'Wavelength',
+ },
+} as const satisfies SequenceSchema;
+
+export type ZigzagDirection = (typeof ZIGZAG_DIRECTIONS)[number];
+
+export type ZigzagParams = {
+ /** Stripe colors, assigned cyclically. Same semantics as lines(). */
+ readonly colors?: readonly string[];
+ /** Base band direction before zig-zag displacement. Same as lines(). */
+ readonly direction?: ZigzagDirection;
+ /** Thickness of each colored band in pixels. Same as lines(). */
+ readonly thickness?: number;
+ /** Transparent gap in pixels between bands. Same as lines(). */
+ readonly gap?: number;
+ /** Rotates the full pattern in degrees. Same as lines(). */
+ readonly angle?: number;
+ /** Offset in pixels. Animate to scroll the bands. Same as lines(). */
+ readonly offset?: number;
+ /** Zig-zag displacement in pixels. */
+ readonly amplitude?: number;
+ /** Distance in pixels before the zig-zag repeats. */
+ readonly wavelength?: number;
+};
+
+type ZigzagResolved = {
+ colors: readonly string[];
+ direction: ZigzagDirection;
+ thickness: number;
+ spacing: number;
+ angle: number;
+ offset: number;
+ amplitude: number;
+ wavelength: number;
+};
+
+type ZigzagState = {
+ 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;
+ readonly uAmplitude: WebGLUniformLocation | null;
+ readonly uWavelength: WebGLUniformLocation | null;
+ };
+ cachedPaletteKey: string;
+ palettePixelData: Uint8Array;
+};
+
+const resolve = (p: ZigzagParams): ZigzagResolved => {
+ 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,
+ amplitude: p.amplitude ?? DEFAULT_AMPLITUDE,
+ wavelength: p.wavelength ?? DEFAULT_WAVELENGTH,
+ };
+};
+
+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' ||
+ !ZIGZAG_DIRECTIONS.includes(direction as ZigzagDirection)
+ ) {
+ throw new TypeError(
+ `"direction" must be ${formatEnum(ZIGZAG_DIRECTIONS)}, but got ${JSON.stringify(direction)}`,
+ );
+ }
+};
+
+const validateZigzagParams = (params: ZigzagParams): void => {
+ assertEffectParamsObject(params, 'Zigzag');
+ validateColors(params.colors);
+ validateDirection(params.direction);
+ assertOptionalFiniteNumber(params.thickness, 'thickness');
+ assertOptionalFiniteNumber(params.gap, 'gap');
+ assertOptionalFiniteNumber(params.angle, 'angle');
+ assertOptionalFiniteNumber(params.offset, 'offset');
+ assertOptionalFiniteNumber(params.amplitude, 'amplitude');
+ assertOptionalFiniteNumber(params.wavelength, 'wavelength');
+
+ const thickness = params.thickness ?? DEFAULT_THICKNESS;
+ const gap = params.gap ?? DEFAULT_GAP;
+ const amplitude = params.amplitude ?? DEFAULT_AMPLITUDE;
+ const wavelength = params.wavelength ?? DEFAULT_WAVELENGTH;
+
+ validatePositive(thickness, 'thickness');
+ validateNonNegative(gap, 'gap');
+ validateNonNegative(amplitude, 'amplitude');
+ validatePositive(wavelength, 'wavelength');
+};
+
+const ZIGZAG_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 ZIGZAG_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;
+uniform float uAmplitude;
+uniform float uWavelength;
+
+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 baseAxis = uDirection == 0 ? rotated.y : rotated.x;
+ float zigzagAxis = uDirection == 0 ? rotated.x : rotated.y;
+ float wavePhase = fract(zigzagAxis / max(uWavelength, 0.001));
+ float zigzagOffset = (1.0 - abs(wavePhase * 2.0 - 1.0) * 2.0) * uAmplitude;
+ float position = mod(baseAxis + zigzagOffset + 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(`Zigzag 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(`Zigzag 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 setupZigzag = (target: HTMLCanvasElement): ZigzagState => {
+ const gl = target.getContext('webgl2', {
+ premultipliedAlpha: true,
+ alpha: true,
+ preserveDrawingBuffer: true,
+ });
+ if (!gl) {
+ throw createWebGL2ContextError('zigzag effect');
+ }
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+
+ const program = createProgram(gl, ZIGZAG_VS, ZIGZAG_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'),
+ uAmplitude: gl.getUniformLocation(program, 'uAmplitude'),
+ uWavelength: gl.getUniformLocation(program, 'uWavelength'),
+ },
+ cachedPaletteKey: '',
+ palettePixelData: new Uint8Array(0),
+ };
+};
+
+const updatePalette = (
+ state: ZigzagState,
+ 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 zigzag = createEffect<ZigzagParams, ZigzagState>({
+ type: 'remotion/zigzag',
+ label: 'zigzag()',
+ documentationLink: 'https://www.remotion.dev/docs/effects/zigzag',
+ 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}`;
+ },
+ setup: (target) => setupZigzag(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);
+ if (uniforms.uAmplitude) gl.uniform1f(uniforms.uAmplitude, r.amplitude);
+ if (uniforms.uWavelength) gl.uniform1f(uniforms.uWavelength, r.wavelength);
+
+ 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,
+ }: ZigzagState) => {
+ gl.deleteTexture(sourceTexture);
+ gl.deleteTexture(paletteTexture);
+ gl.deleteBuffer(vbo);
+ gl.deleteProgram(program);
+ gl.deleteVertexArray(vao);
+ },
+ schema: zigzagSchema,
+ validateParams: validateZigzagParams,
+});