🎥 Make videos programmatically with React
@remotion/effects: Add waves() pattern (#7913)
Jonny Burger57114ade43bd
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.tsindex 5940eac9c3..4085bfc638 100644--- a/packages/docs/components/effects-demos/registry.ts+++ b/packages/docs/components/effects-demos/registry.ts@@ -26,6 +26,7 @@ import {tint} from '@remotion/effects/tint';import {uvTranslate, xyTranslate} from '@remotion/effects/translate';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 {lightLeakEffectSchema} from '@remotion/light-leaks';import {starburstEffectSchema} from '@remotion/starburst';@@ -62,6 +63,7 @@ import {} from '../effects/effects-translate-preview';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 type {EffectsDemoType} from './types';@@ -298,6 +300,12 @@ export const effectsDemos: EffectsDemoType[] = [comp: EffectsWavePreview,schema: wave().definition.schema,},+ {+ ...defaults,+ id: 'effects-waves',+ comp: EffectsWavesPreview,+ schema: waves().definition.schema,+ },{...defaults,id: 'effects-halftone',diff --git a/packages/docs/components/effects/effects-waves-preview.tsx b/packages/docs/components/effects/effects-waves-preview.tsxnew file mode 100644index 0000000000..ac0c2d6415--- /dev/null+++ b/packages/docs/components/effects/effects-waves-preview.tsx@@ -0,0 +1,37 @@+import type {WavesDirection} from '@remotion/effects/waves';+import {waves} from '@remotion/effects/waves';+import React from 'react';+import {CanvasImage} from 'remotion';+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';++export const EffectsWavesPreview: React.FC<{+ readonly direction: WavesDirection;+ readonly thickness: number;+ readonly gap: number;+ readonly angle: number;+ readonly offset: number;+ readonly amplitude: number;+ readonly wavelength: number;+ readonly phase: number;+}> = ({direction, thickness, gap, angle, offset, amplitude, wavelength, phase}) => {+ return (+ <CanvasImage+ src={EFFECTS_PREVIEW_IMAGE_SRC}+ width={1280}+ height={720}+ fit="cover"+ effects={[+ waves({+ direction,+ thickness,+ gap,+ angle,+ offset,+ amplitude,+ wavelength,+ phase,+ }),+ ]}+ />+ );+};diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsxindex 6ef470c464..ecbf9990da 100644--- a/packages/docs/docs/effects/table-of-contents.tsx+++ b/packages/docs/docs/effects/table-of-contents.tsx@@ -203,6 +203,13 @@ const categories: {name: 'lines()',description: 'Alternating line overlay effect',},+ {+ link: '/docs/effects/waves',+ preview: '/img/effects-waves-preview.png',+ alt: 'waves effect preview',+ name: 'waves()',+ description: 'Wavy band overlay effect',+ },{link: '/docs/effects/scanlines',preview: '/img/effects-scanlines-preview.png',diff --git a/packages/docs/docs/effects/waves.mdx b/packages/docs/docs/effects/waves.mdxnew file mode 100644index 0000000000..4cac947fbf--- /dev/null+++ b/packages/docs/docs/effects/waves.mdx@@ -0,0 +1,113 @@+---+image: /generated/articles-docs-effects-waves.png+slug: /effects/waves+title: waves()+sidebar_label: waves()+crumb: '@remotion/effects'+---++# waves()<AvailableFrom v="4.0.471" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++Adds repeating wavy bands to canvas-based components such as [`<Video>`](/docs/media/video), [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) and [`<Solid>`](/docs/solid).++Colors are composited over the source. Transparent colors leave the source unchanged.++## Preview++<EffectsDemo type="effects-waves" />++## Example++```tsx twoslash title="MyComp.tsx"+import {waves} from '@remotion/effects/waves';+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={[+ waves({+ colors: ['#dff4ff', 'transparent'],+ direction: 'horizontal',+ thickness: 40,+ gap: 0,+ angle: 0,+ offset: frame * 2,+ amplitude: 24,+ wavelength: 160,+ phase: frame * 2,+ }),+ ]}+ />+ </AbsoluteFill>+ );+};+```++## API++Pass an object with the following properties. You can also call `waves()` without arguments.++### `colors?`++An array of color strings for the bands. Colors are assigned cyclically. Must contain at least 2 colors.++Defaults to `['#dff4ff', 'transparent']`.++### `direction?`++Base band direction before wave 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`.++### `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 through the bands.++### `amplitude?`++Wave displacement in pixels. Defaults to `24`.++### `wavelength?`++Distance in pixels before the wave repeats. Defaults to `160`. Must be greater than `0`.++### `phase?`++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.++### `disabled?`++When `true`, the effect is skipped. Defaults to `false`.++## Requirements++`waves()` 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)+- [`wave()`](/docs/effects/wave)+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/waves.ts)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 930056bb52..059b8972c1 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -296,6 +296,7 @@ const sidebars: SidebarsConfig = {'effects/uv-translate','effects/vignette','effects/wave',+ 'effects/waves','effects/white-noise','effects/xy-translate',],diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex d728b9ed86..dc049cf245 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -1979,6 +1979,15 @@ export const articles = [noAi: false,slug: 'effects/wave',},+ {+ id: 'effects/waves',+ title: 'waves()',+ relativePath: 'docs/effects/waves.mdx',+ compId: 'articles-docs-effects-waves',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/waves',+ },{id: 'effects/white-noise',title: 'whiteNoise()',diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsxindex 64a3829500..d14f2b698c 100644--- a/packages/docs/src/remotion/Root.tsx+++ b/packages/docs/src/remotion/Root.tsx@@ -35,6 +35,7 @@ import {} from '../../components/effects/effects-translate-preview';import {EffectsVignettePreview} from '../../components/effects/effects-vignette-preview';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 {articles} from '../data/articles';import {AllTemplates} from './AllTemplates';@@ -365,6 +366,22 @@ export const RemotionRoot: React.FC = () => {offset: 0,}}/>+ <Still+ id="effects-waves-preview"+ component={EffectsWavesPreview}+ width={1280}+ height={720}+ defaultProps={{+ direction: 'horizontal',+ thickness: 40,+ gap: 0,+ angle: 0,+ offset: 0,+ amplitude: 24,+ wavelength: 160,+ phase: 45,+ }}+ /><Stillid="effects-shine-preview"component={EffectsShinePreview}diff --git a/packages/docs/static/generated/articles-docs-effects-waves.png b/packages/docs/static/generated/articles-docs-effects-waves.pngnew file mode 100644index 0000000000..3320ad4003Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-waves.png differdiff --git a/packages/docs/static/img/effects-waves-preview.png b/packages/docs/static/img/effects-waves-preview.pngnew file mode 100644index 0000000000..01bbb45eaeBinary files /dev/null and b/packages/docs/static/img/effects-waves-preview.png differdiff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex 3062a00432..f69d7da670 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -35,6 +35,7 @@ const effectEntrypoints = ['src/translate.ts','src/vignette.ts','src/wave.ts',+ 'src/waves.ts','src/white-noise.ts',];diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex ebf3c7a0af..f3d7deaf77 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -174,6 +174,11 @@"module": "./dist/esm/wave.mjs","import": "./dist/esm/wave.mjs"},+ "./waves": {+ "types": "./dist/waves.d.ts",+ "module": "./dist/esm/waves.mjs",+ "import": "./dist/esm/waves.mjs"+ },"./white-noise": {"types": "./dist/white-noise.d.ts","module": "./dist/esm/white-noise.mjs",@@ -267,6 +272,9 @@"wave": ["dist/wave.d.ts"],+ "waves": [+ "dist/waves.d.ts"+ ],"white-noise": ["dist/white-noise.d.ts"]diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.tsindex 520669b691..95b8d98566 100644--- a/packages/effects/src/test/effect-params.test.ts+++ b/packages/effects/src/test/effect-params.test.ts@@ -27,6 +27,7 @@ import {tint} from '../tint.js';import {uvTranslate, xyTranslate} from '../translate.js';import {vignette} from '../vignette.js';import {wave} from '../wave/index.js';+import {waves} from '../waves.js';import {whiteNoise} from '../white-noise.js';test('@remotion/effects expose documentation links', () => {@@ -117,6 +118,9 @@ test('@remotion/effects expose documentation links', () => {expect(wave().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/wave',);+ expect(waves().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/waves',+ );expect(whiteNoise().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/white-noise',);@@ -153,6 +157,7 @@ test('@remotion/effects expose API names as Studio labels', () => {expect(vignette().definition.label).toBe('vignette()');expect(xyTranslate().definition.label).toBe('xyTranslate()');expect(wave().definition.label).toBe('wave()');+ expect(waves().definition.label).toBe('waves()');expect(whiteNoise().definition.label).toBe('whiteNoise()');});@@ -360,6 +365,71 @@ test('wave() direction produces distinct effect keys', () => {expect(horizontal.effectKey).not.toBe(vertical.effectKey);});+test('waves() accepts default params', () => {+ expect(() => waves()).not.toThrow();+});++test('waves() rejects invalid colors', () => {+ expect(() => waves({colors: ['#dff4ff']})).toThrow(+ '"colors" must be an array with at least 2 colors',+ );+ expect(() => waves({colors: ['#dff4ff', '' as unknown as string]})).toThrow(+ '"colors[1]" must be a non-empty string',+ );+});++test('waves() rejects invalid direction', () => {+ expect(() =>+ waves({direction: 'diagonal' as unknown as 'horizontal'}),+ ).toThrow('"direction" must be "horizontal" or "vertical"');+});++test('waves() rejects non-positive wavelength', () => {+ expect(() => waves({wavelength: 0})).toThrow(+ '"wavelength" must be greater than 0',+ );+});++test('waves() rejects negative amplitude', () => {+ expect(() => waves({amplitude: -1})).toThrow(+ '"amplitude" must be greater than or equal to 0',+ );+});++test('waves() rejects non-positive thickness', () => {+ expect(() => waves({thickness: 0})).toThrow(+ '"thickness" must be greater than 0',+ );+});++test('waves() parameters produce distinct effect keys', () => {+ const defaults = waves();+ const colored = waves({colors: ['#ffffff', 'transparent']});+ const vertical = waves({direction: 'vertical'});+ const thin = waves({thickness: 20});+ const gapped = waves({gap: 24});+ const angled = waves({angle: 45});+ const shifted = waves({offset: 10});+ const stronger = waves({amplitude: 30});+ const longer = waves({wavelength: 220});+ const phased = waves({phase: 90});++ expect(+ new Set([+ defaults.effectKey,+ colored.effectKey,+ vertical.effectKey,+ thin.effectKey,+ gapped.effectKey,+ angled.effectKey,+ shifted.effectKey,+ stronger.effectKey,+ longer.effectKey,+ phased.effectKey,+ ]).size,+ ).toBe(10);+});+test('whiteNoise() accepts default params', () => {expect(() => whiteNoise()).not.toThrow();});diff --git a/packages/effects/src/waves.ts b/packages/effects/src/waves.tsnew file mode 100644index 0000000000..145b276f2f--- /dev/null+++ b/packages/effects/src/waves.ts@@ -0,0 +1,586 @@+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 WAVE_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;+const DEFAULT_AMPLITUDE = 24 as const;+const DEFAULT_WAVELENGTH = 160 as const;+const DEFAULT_PHASE = 0 as const;++export const wavesSchema = {+ 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',+ },+ phase: {+ type: 'number',+ min: -360,+ max: 360,+ step: 1,+ default: DEFAULT_PHASE,+ description: 'Phase',+ },+} as const satisfies SequenceSchema;++export type WavesDirection = (typeof WAVE_DIRECTIONS)[number];++export type WavesParams = {+ /** Stripe colors, assigned cyclically. Defaults to light blue and transparent. */+ readonly colors?: readonly string[];+ /** Base band direction. Defaults to `horizontal`. */+ readonly direction?: WavesDirection;+ /** Thickness of each stripe in pixels. Defaults to `40`. */+ readonly thickness?: number;+ /** Transparent gap in pixels between each stripe. Defaults to `0`. */+ readonly gap?: number;+ /** Rotates the pattern in degrees. Defaults to `0`. */+ readonly angle?: number;+ /** Offset in pixels. Animate to scroll through the bands. Defaults to `0`. */+ readonly offset?: number;+ /** Wave displacement in pixels. Defaults to `24`. */+ readonly amplitude?: number;+ /** Distance in pixels before the wave repeats. Defaults to `160`. */+ readonly wavelength?: number;+ /** Wave phase in degrees. Defaults to `0`. */+ readonly phase?: number;+};++type WavesResolved = {+ colors: readonly string[];+ direction: WavesDirection;+ thickness: number;+ spacing: number;+ angle: number;+ offset: number;+ amplitude: number;+ wavelength: number;+ phase: number;+};++type WavesState = {+ 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;+ readonly uPhase: WebGLUniformLocation | null;+ };+ cachedPaletteKey: string;+ palettePixelData: Uint8Array;+};++const resolve = (p: WavesParams): WavesResolved => {+ 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,+ phase: p.phase ?? DEFAULT_PHASE,+ };+};++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' ||+ !WAVE_DIRECTIONS.includes(direction as WavesDirection)+ ) {+ throw new TypeError(+ `"direction" must be ${formatEnum(WAVE_DIRECTIONS)}, but got ${JSON.stringify(direction)}`,+ );+ }+};++const validateWavesParams = (params: WavesParams): void => {+ assertEffectParamsObject(params, 'Waves');+ 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');+ assertOptionalFiniteNumber(params.phase, 'phase');++ 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 WAVES_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 WAVES_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;+uniform float uPhase;++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 waveAxis = uDirection == 0 ? rotated.x : rotated.y;+ float waveOffset =+ sin((waveAxis / max(uWavelength, 0.001)) * 6.283185307179586 + uPhase) *+ uAmplitude;+ float position = mod(baseAxis + waveOffset + 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(`Waves 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(`Waves 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 setupWaves = (target: HTMLCanvasElement): WavesState => {+ const gl = target.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!gl) {+ throw createWebGL2ContextError('waves effect');+ }++ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);++ const program = createProgram(gl, WAVES_VS, WAVES_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'),+ uPhase: gl.getUniformLocation(program, 'uPhase'),+ },+ cachedPaletteKey: '',+ palettePixelData: new Uint8Array(0),+ };+};++const updatePalette = (+ state: WavesState,+ 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 waves = createEffect<WavesParams, WavesState>({+ type: 'remotion/waves',+ label: 'waves()',+ documentationLink: 'https://www.remotion.dev/docs/effects/waves',+ 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}`;+ },+ setup: (target) => setupWaves(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);+ if (uniforms.uPhase)+ gl.uniform1f(uniforms.uPhase, (r.phase * Math.PI) / 180);++ 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: wavesSchema,+ validateParams: validateWavesParams,+});