🎥 Make videos programmatically with React
Add tear effect with configurable rip direction
JonnyBurger7c15ed4c6e03
diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.tsindex 13cfc39d4f..3bc9abc268 100644--- a/packages/docs/components/effects-demos/registry.ts+++ b/packages/docs/components/effects-demos/registry.ts@@ -55,6 +55,7 @@ import {shrinkwrap} from '@remotion/effects/shrinkwrap';import {skew} from '@remotion/effects/skew';import {speckle} from '@remotion/effects/speckle';import {starburst} from '@remotion/effects/starburst';+import {tear} from '@remotion/effects/tear';import {thermalVision} from '@remotion/effects/thermal-vision';import {tile} from '@remotion/effects/tile';import {tint} from '@remotion/effects/tint';@@ -148,6 +149,7 @@ import {EffectsStarburstPreview,STARBURST_PREVIEW_PARAMS,} from '../effects/effects-starburst-preview';+import {EffectsTearPreview} from '../effects/effects-tear-preview';import {EffectsThermalVisionPreview} from '../effects/effects-thermal-vision-preview';import {EffectsTilePreview} from '../effects/effects-tile-preview';import {EffectsTintPreview} from '../effects/effects-tint-preview';@@ -298,6 +300,14 @@ export const effectsDemos: EffectsDemoType[] = [comp: EffectsVibrancePreview,schema: vibrance().definition.schema,},+ {+ ...defaults,+ id: 'effects-tear',+ effectName: 'tear',+ effectImportPath: '@remotion/effects/tear',+ comp: EffectsTearPreview,+ schema: tear().definition.schema,+ },{...defaults,id: 'effects-venetian-blinds',diff --git a/packages/docs/components/effects/effects-tear-preview.tsx b/packages/docs/components/effects/effects-tear-preview.tsxnew file mode 100644index 0000000000..06b9ed09e3--- /dev/null+++ b/packages/docs/components/effects/effects-tear-preview.tsx@@ -0,0 +1,25 @@+import {scale} from '@remotion/effects/scale';+import {tear} from '@remotion/effects/tear';+import React from 'react';+import {CanvasImage} from 'remotion';+import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';++export const EffectsTearPreview: React.FC<{+ readonly angle: number;+ readonly progress: number;+ readonly rotation: number;+ readonly jaggedness: number;+}> = ({progress, rotation, jaggedness, angle}) => {+ return (+ <CanvasImage+ src={EFFECTS_PREVIEW_IMAGE_SRC}+ width={1280}+ height={720}+ fit="cover"+ effects={[+ scale({scale: 0.7}),+ tear({progress, rotation, jaggedness, angle}),+ ]}+ />+ );+};diff --git a/packages/docs/docs/effects/tear.mdx b/packages/docs/docs/effects/tear.mdxnew file mode 100644index 0000000000..432a4c5912--- /dev/null+++ b/packages/docs/docs/effects/tear.mdx@@ -0,0 +1,81 @@+---+image: /generated/articles-docs-effects-tear.png+slug: /effects/tear+title: tear()+sidebar_label: tear()+crumb: '@remotion/effects'+---++# tear()<AvailableFrom v="4.0.523" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++Tears a canvas-based component along a zigzag seam in any direction. The two pieces rotate outward as the tear advances, leaving a transparent opening. The area ahead of the tear stays intact. By default, the rip travels from top to bottom.++## Preview++<EffectsDemo type="effects-tear" />++## Example++```tsx twoslash title="MyComp.tsx"+import {AbsoluteFill, interpolate, useCurrentFrame} from 'remotion';+import {Video} from '@remotion/media';+import {tear} from '@remotion/effects/tear';++export const MyComp: React.FC = () => {+ const frame = useCurrentFrame();+ const progress = interpolate(frame, [0, 60], [0, 1], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ });++ return (+ <AbsoluteFill>+ <Video+ src="https://remotion.media/video.mp4"+ effects={[tear({progress, rotation: 20, jaggedness: 20})]}+ />+ </AbsoluteFill>+ );+};+```++## API++Pass an object with the following properties. You can also call `tear()` without arguments.++### `progress?`++Non-negative tear progress. At `0`, the source is intact; at `1`, the tear reaches the opposite edge. Above `1`, the pieces keep moving apart perpendicular to the rip, each by half the width of the canvas projected onto that axis per additional unit of progress. Their rotation stays at its value at `1`. Defaults to `0.5`.++### `angle?`++Rip direction in degrees. Defaults to `0` (top to bottom). Use `90` for left to right, `180` for bottom to top, or `270` for right to left. Any finite angle is supported, including negative angles and angles above `360`.++The image keeps its original orientation; only the rip direction changes.++### `rotation?`++Maximum outward rotation of each piece in degrees at full progress. Must be between `0` and `90`. Defaults to `20`. The rotation increases with `progress`, with a bend near the tear tip joining the separated pieces to the intact area. The bend is wider for larger rotations and wider canvases. At `0`, the source stays unchanged until `progress` exceeds `1`.++Content that rotates outside the canvas is clipped.++### `jaggedness?`++Amplitude of the zigzag seam in pixels, perpendicular to the rip direction. Must be non-negative. Defaults to `20`. Use `0` for a straight tear. The amplitude is limited to 45% of the canvas width projected perpendicular to the rip.++### `disabled?`++When `true`, the effect is skipped. Defaults to `false`.++## Requirements++`tear()` uses a WebGL2 backend. See [Using WebGL and WebGPU during renders](/docs/webgl).++## See also++- [`@remotion/effects`](/docs/effects/api)+- [`roughenEdges()`](/docs/effects/roughen-edges)+- [HTML-in-canvas guide](/docs/html-in-canvas)+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/tear.ts)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 07c745d9c8..057e3f9a98 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -330,6 +330,7 @@ const sidebars: SidebarsConfig = {'effects/skew','effects/speckle','effects/starburst',+ 'effects/tear','effects/thermal-vision','effects/tile','effects/tint',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex f6cc3609e5..46d16e4809 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -2366,6 +2366,15 @@ export const articles = [noAi: false,slug: 'effects/starburst',},+ {+ id: 'effects/tear',+ title: 'tear()',+ relativePath: 'docs/effects/tear.mdx',+ compId: 'articles-docs-effects-tear',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/tear',+ },{id: 'effects/thermal-vision',title: 'thermalVision()',diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsxindex 17a66e65d0..f2fbaf2e5b 100644--- a/packages/docs/src/remotion/Root.tsx+++ b/packages/docs/src/remotion/Root.tsx@@ -89,6 +89,7 @@ import {EffectsStarburstPreview,STARBURST_PREVIEW_PARAMS,} from '../../components/effects/effects-starburst-preview';+import {EffectsTearPreview} from '../../components/effects/effects-tear-preview';import {EffectsThermalVisionPreview} from '../../components/effects/effects-thermal-vision-preview';import {EffectsTilePreview} from '../../components/effects/effects-tile-preview';import {EffectsTintPreview} from '../../components/effects/effects-tint-preview';@@ -356,6 +357,18 @@ export const RemotionRoot: React.FC = () => {height={720}defaultProps={{amount: 0.8}}/>+ <Still+ id="effects-tear-preview"+ component={EffectsTearPreview}+ width={1280}+ height={720}+ defaultProps={{+ progress: 0.75,+ rotation: 20,+ jaggedness: 20,+ angle: 0,+ }}+ /><Stillid="effects-venetian-blinds-preview"component={EffectsVenetianBlindsPreview}diff --git a/packages/docs/static/generated/articles-docs-effects-tear.png b/packages/docs/static/generated/articles-docs-effects-tear.pngnew file mode 100644index 0000000000..47ed80fcf9Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-tear.png differdiff --git a/packages/docs/static/img/effects-tear-preview.png b/packages/docs/static/img/effects-tear-preview.pngnew file mode 100644index 0000000000..1f4f1b44bbBinary files /dev/null and b/packages/docs/static/img/effects-tear-preview.png differdiff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex be501e1cb5..43e4cfaa8f 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -64,6 +64,7 @@ const effectEntrypoints = ['src/skew.ts','src/speckle.ts','src/starburst.ts',+ 'src/tear.ts','src/thermal-vision.ts','src/tile.ts','src/tint.ts',diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex 76360d1b97..11eeea3925 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -319,6 +319,11 @@"module": "./dist/esm/starburst.mjs","import": "./dist/esm/starburst.mjs"},+ "./tear": {+ "types": "./dist/tear.d.ts",+ "module": "./dist/esm/tear.mjs",+ "import": "./dist/esm/tear.mjs"+ },"./thermal-vision": {"types": "./dist/thermal-vision.d.ts","module": "./dist/esm/thermal-vision.mjs",@@ -564,6 +569,9 @@"starburst": ["dist/starburst.d.ts"],+ "tear": [+ "dist/tear.d.ts"+ ],"thermal-vision": ["dist/thermal-vision.d.ts"],diff --git a/packages/effects/src/tear.ts b/packages/effects/src/tear.tsnew file mode 100644index 0000000000..5f205ebe08--- /dev/null+++ b/packages/effects/src/tear.ts@@ -0,0 +1,352 @@+import {Internals, type InteractivitySchema} from 'remotion';+import {assertOptionalFiniteNumber} from './color-utils.js';+import {assertEffectParamsObject} from './validate-effect-param.js';++const {createEffect, createWebGL2ContextError} = Internals;++const DEFAULT_PROGRESS = 0.5 as const;+const DEFAULT_ANGLE = 0 as const;+const DEFAULT_ROTATION = 20 as const;+const DEFAULT_JAGGEDNESS = 20 as const;+const MESH_ROWS = 192;++const tearSchema = {+ progress: {+ type: 'number',+ min: 0,+ step: 0.01,+ default: DEFAULT_PROGRESS,+ description: 'Progress',+ hiddenFromList: false,+ },+ angle: {+ type: 'number',+ step: 1,+ default: DEFAULT_ANGLE,+ description: 'Angle',+ hiddenFromList: false,+ },+ rotation: {+ type: 'number',+ min: 0,+ max: 90,+ step: 1,+ default: DEFAULT_ROTATION,+ description: 'Rotation',+ hiddenFromList: false,+ },+ jaggedness: {+ type: 'number',+ min: 0,+ max: 100,+ step: 1,+ default: DEFAULT_JAGGEDNESS,+ description: 'Jaggedness',+ hiddenFromList: false,+ },+} as const satisfies InteractivitySchema;++export type TearParams = {+ /** Tear progress: 0 is intact, 1 reaches the opposite edge, and values above 1 move the pieces farther apart. Defaults to 0.5. */+ readonly progress?: number;+ /** Rip direction in degrees: 0 top-to-bottom, 90 left-to-right. Defaults to 0. */+ readonly angle?: number;+ /** Maximum outward rotation in degrees, between 0 and 90. Defaults to 20. */+ readonly rotation?: number;+ /** Zigzag amplitude in pixels. Use 0 for a straight seam. Defaults to 20. */+ readonly jaggedness?: number;+};++const resolve = (p: TearParams) => ({+ progress: p.progress ?? DEFAULT_PROGRESS,+ angle: p.angle ?? DEFAULT_ANGLE,+ rotation: p.rotation ?? DEFAULT_ROTATION,+ jaggedness: p.jaggedness ?? DEFAULT_JAGGEDNESS,+});++const validateTearParams = (params: TearParams): void => {+ assertEffectParamsObject(params, 'Tear');+ assertOptionalFiniteNumber(params.progress, 'progress');+ assertOptionalFiniteNumber(params.angle, 'angle');+ assertOptionalFiniteNumber(params.rotation, 'rotation');+ assertOptionalFiniteNumber(params.jaggedness, 'jaggedness');+ const r = resolve(params);+ if (r.progress < 0) {+ throw new Error('"progress" must be >= 0');+ }++ if (r.rotation < 0 || r.rotation > 90) {+ throw new Error('"rotation" must be between 0 and 90');+ }++ if (r.jaggedness < 0) {+ throw new Error('"jaggedness" must be >= 0');+ }+};++type TearState = {+ readonly gl: WebGL2RenderingContext;+ readonly program: WebGLProgram;+ readonly vao: WebGLVertexArrayObject;+ readonly vbo: WebGLBuffer;+ readonly texture: WebGLTexture;+ readonly uSource: WebGLUniformLocation | null;+ readonly uAngle: WebGLUniformLocation | null;+ readonly uProgress: WebGLUniformLocation | null;+ readonly uRotation: WebGLUniformLocation | null;+ readonly uJaggedness: WebGLUniformLocation | null;+ readonly uSide: WebGLUniformLocation | null;+ readonly uResolution: WebGLUniformLocation | null;+};++const VERTEX_SHADER = /* glsl */ `#version 300 es+in vec2 aPos;+out vec2 vUv;+uniform vec2 uResolution;+uniform float uAngle;+uniform float uProgress;+uniform float uRotation;+uniform float uJaggedness;+uniform float uSide;++float seam(float y, float width) {+ // Six zigzags, with matching edges on both pieces. Limit the amplitude+ // to keep the tear inside the source, even on very narrow canvases.+ float zigzag = 1.0 - 4.0 * abs(fract(y * 6.0 + 0.25) - 0.5);+ return width * 0.5 + zigzag * min(uJaggedness, width * 0.45);+}++void main() {+ // Work in a rectangle aligned with the rip, large enough to cover the+ // original canvas at every angle. Rotate UVs back to the source so the+ // image itself keeps its orientation.+ float direction = radians(uAngle);+ float dc = cos(direction);+ float ds = sin(direction);+ mat2 toCanvas = mat2(dc, -ds, ds, dc);+ vec2 extent = vec2(+ abs(dc) * uResolution.x + abs(ds) * uResolution.y,+ abs(ds) * uResolution.x + abs(dc) * uResolution.y+ );+ float outerEdge = uSide < 0.0 ? 0.0 : extent.x;+ vec2 source = vec2(mix(outerEdge, seam(aPos.y, extent.x), aPos.x), aPos.y * extent.y);+ vec2 sourceCanvas = toCanvas * (source - extent * 0.5) + uResolution * 0.5;+ vUv = vec2(sourceCanvas.x / uResolution.x, 1.0 - sourceCanvas.y / uResolution.y);++ float tearProgress = min(uProgress, 1.0);+ float tipY = tearProgress * extent.y;+ // Keep the motion independent of the jagged edge. Following the seam+ // with the pivot would rock the entire image at every zigzag.+ vec2 pivot = vec2(extent.x * 0.5, tipY);+ // The short bend near the tip joins the rotating portion continuously+ // to the untouched area below it. Work in pixels to preserve angles+ // at different aspect ratios.+ float fullAngle = radians(uRotation) * tearProgress;+ // Widen the bend for larger rotations / wider sheets so neighboring+ // rows cannot fold over each other at the outside edges.+ float bendHeight = max(extent.y * 0.15, fullAngle * extent.x * 1.5);+ float bend = smoothstep(0.0, bendHeight, tipY - source.y);+ float angle = uSide * fullAngle * bend;+ float c = cos(angle);+ float s = sin(angle);+ vec2 delta = source - pivot;+ vec2 position = pivot + vec2(c * delta.x - s * delta.y, s * delta.x + c * delta.y);+ // After the tear reaches the bottom, keep the rotation stable and+ // move each piece outward by half a canvas width per unit of progress.+ position.x += uSide * max(uProgress - 1.0, 0.0) * extent.x * 0.5;+ position = toCanvas * (position - extent * 0.5) + uResolution * 0.5;+ gl_Position = vec4(position.x / uResolution.x * 2.0 - 1.0, 1.0 - position.y / uResolution.y * 2.0, 0.0, 1.0);+}+`;++const FRAGMENT_SHADER = /* glsl */ `#version 300 es+precision highp float;+in vec2 vUv;+out vec4 fragColor;+uniform sampler2D uSource;++void main() {+ // The rotated mesh extends beyond the original image. Those parts+ // must remain transparent instead of smearing clamped border pixels.+ if (any(lessThan(vUv, vec2(0.0))) || any(greaterThan(vUv, vec2(1.0)))) {+ discard;+ }+ fragColor = texture(uSource, vUv);+}+`;++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(`Tear 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(`Tear program link failed: ${log ?? '(no log)'}`);+ }++ return program;+};++const createTearState = (gl: WebGL2RenderingContext): TearState => {+ const vs = compileShader(gl, gl.VERTEX_SHADER, VERTEX_SHADER);+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, FRAGMENT_SHADER);+ 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((MESH_ROWS + 1) * 4);+ for (let row = 0; row <= MESH_ROWS; row++) {+ data.set([0, row / MESH_ROWS, 1, row / MESH_ROWS], row * 4);+ }++ 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');+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 8, 0);++ 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);++ return {+ gl,+ program,+ vao,+ vbo,+ texture,+ uSource: gl.getUniformLocation(program, 'uSource'),+ uResolution: gl.getUniformLocation(program, 'uResolution'),+ uAngle: gl.getUniformLocation(program, 'uAngle'),+ uProgress: gl.getUniformLocation(program, 'uProgress'),+ uRotation: gl.getUniformLocation(program, 'uRotation'),+ uJaggedness: gl.getUniformLocation(program, 'uJaggedness'),+ uSide: gl.getUniformLocation(program, 'uSide'),+ };+};++export const tear = createEffect<TearParams, TearState>({+ type: 'dev.remotion.effects.tear',+ label: 'tear()',+ documentationLink: 'https://www.remotion.dev/docs/effects/tear',+ backend: 'webgl2',++ calculateKey: (params) => {+ const r = resolve(params);+ return `tear-${r.progress}-${r.rotation}-${r.jaggedness}-${r.angle}`;+ },+ setup: (target) => {+ const gl = target.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!gl) {+ throw createWebGL2ContextError('tear effect');+ }++ return createTearState(gl);+ },+ apply: ({source, width, height, params, state, flipSourceY}) => {+ const r = resolve(params);++ state.gl.viewport(0, 0, width, height);+ state.gl.bindFramebuffer(state.gl.FRAMEBUFFER, null);+ state.gl.clearColor(0, 0, 0, 0);+ state.gl.clear(state.gl.COLOR_BUFFER_BIT);++ state.gl.useProgram(state.program);+ state.gl.bindVertexArray(state.vao);+ state.gl.activeTexture(state.gl.TEXTURE0);+ state.gl.bindTexture(state.gl.TEXTURE_2D, state.texture);+ state.gl.pixelStorei(state.gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);+ state.gl.pixelStorei(state.gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);+ state.gl.texImage2D(+ state.gl.TEXTURE_2D,+ 0,+ state.gl.RGBA,+ state.gl.RGBA,+ state.gl.UNSIGNED_BYTE,+ source as TexImageSource,+ );++ if (state.uSource) state.gl.uniform1i(state.uSource, 0);+ if (state.uAngle) state.gl.uniform1f(state.uAngle, r.angle % 360);+ if (state.uProgress) state.gl.uniform1f(state.uProgress, r.progress);+ if (state.uRotation) state.gl.uniform1f(state.uRotation, r.rotation);+ if (state.uJaggedness) state.gl.uniform1f(state.uJaggedness, r.jaggedness);+ if (state.uResolution) state.gl.uniform2f(state.uResolution, width, height);++ for (const side of [-1, 1]) {+ if (state.uSide) state.gl.uniform1f(state.uSide, side);+ state.gl.drawArrays(state.gl.TRIANGLE_STRIP, 0, (MESH_ROWS + 1) * 2);+ }++ state.gl.bindVertexArray(null);+ state.gl.bindTexture(state.gl.TEXTURE_2D, null);+ state.gl.useProgram(null);+ },+ cleanup: ({gl, program, vao, vbo, texture}) => {+ gl.deleteTexture(texture);+ gl.deleteBuffer(vbo);+ gl.deleteProgram(program);+ gl.deleteVertexArray(vao);+ },++ schema: tearSchema,+ validateParams: validateTearParams,+});diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.tsindex affb1b7983..1d804b9488 100644--- a/packages/effects/src/test/effect-params.test.ts+++ b/packages/effects/src/test/effect-params.test.ts@@ -66,6 +66,7 @@ import {shrinkwrap} from '../shrinkwrap.js';import {skew} from '../skew.js';import {speckle} from '../speckle.js';import {starburst} from '../starburst.js';+import {tear, type TearParams} from '../tear.js';import {thermalVision} from '../thermal-vision.js';import {tile} from '../tile.js';import {tint} from '../tint.js';@@ -104,6 +105,9 @@ test('public UV coordinates convert to shader UV coordinates', () => {});test('@remotion/effects expose documentation links', () => {+ expect(tear().definition.documentationLink).toBe(+ 'https://www.remotion.dev/docs/effects/tear',+ );expect(barrelDistortion().definition.documentationLink).toBe('https://www.remotion.dev/docs/effects/barrel-distortion',);@@ -4347,3 +4351,36 @@ test('liquidContours() parameters produce distinct effect keys', () => {effects.length,);});++test('tear() resolves defaults and includes every parameter in its effect key', () => {+ expect(tear().effectKey).toBe(+ tear({progress: 0.5, rotation: 20, jaggedness: 20}).effectKey,+ );+ const effects = [+ tear(),+ tear({progress: 0.75}),+ tear({progress: 2}),+ tear({angle: 45}),+ tear({rotation: 30}),+ tear({jaggedness: 0}),+ ];+ expect(new Set(effects.map((effect) => effect.effectKey)).size).toBe(6);+});++test('tear() rejects invalid parameters', () => {+ const cases: [TearParams, string][] = [+ [{progress: -0.1}, '"progress" must be >= 0'],+ [{rotation: -1}, '"rotation" must be between 0 and 90'],+ [{rotation: 91}, '"rotation" must be between 0 and 90'],+ [{jaggedness: -1}, '"jaggedness" must be >= 0'],+ ];+ for (const name of ['progress', 'rotation', 'jaggedness', 'angle'] as const) {+ for (const value of [NaN, Infinity, -Infinity]) {+ cases.push([{[name]: value}, `"${name}" must be a finite number`]);+ }+ }++ for (const [params, message] of cases) {+ expect(() => tear(params)).toThrow(message);+ }+});diff --git a/packages/effects/src/visual-test/effects-visual.test.ts b/packages/effects/src/visual-test/effects-visual.test.tsindex 62efdab099..700807ee31 100644--- a/packages/effects/src/visual-test/effects-visual.test.ts+++ b/packages/effects/src/visual-test/effects-visual.test.ts@@ -12,6 +12,7 @@ import {pixelDissolve} from '../pixel-dissolve.js';import {saturation} from '../saturation.js';import {scale} from '../scale.js';import {shadowsHighlights} from '../shadows-highlights.js';+import {tear} from '../tear.js';import {tile} from '../tile.js';import {vibrance} from '../vibrance.js';import {vignette} from '../vignette.js';@@ -796,3 +797,161 @@ test('pixelDissolve() smoothly fades to full transparency with feather', async (const doneAlpha = await maxAlphaForPixelDissolveProgress(1);expect(doneAlpha).toBe(0);});++test('tear() progresses downward, rotates both sides outward, and preserves alpha through a stack', async () => {+ const width = 320;+ const height = 240;+ const source = document.createElement('canvas');+ source.width = width;+ source.height = height;+ const context = source.getContext('2d')!;+ context.fillStyle = 'rgba(200, 80, 40, 0.5)';+ context.fillRect(0, 0, width, height);+ // Markers on each side make the rotation observable in the rendered pixels.+ context.fillStyle = '#ff0000';+ context.fillRect(118, 32, 8, 8);+ context.fillStyle = '#00ff00';+ context.fillRect(194, 32, 8, 8);+ context.fillStyle = 'rgba(40, 80, 200, 0.5)';+ context.fillRect(0, 124, width, 8);+ const render = async (+ progress: number,+ rotation: number,+ jaggedness: number,+ ) => {+ const canvas = await renderEffectChainToCanvas({+ source,+ width,+ height,+ effects: descriptorsToMemoizedEffects([+ tear({progress: 0}),+ tear({progress, rotation, jaggedness}),+ tear({progress: 0}),+ ]),+ });+ return canvas.getContext('2d')!;+ };++ const intact = await render(0, 20, 12);+ expect([...intact.getImageData(160, 20, 1, 1).data]).toEqual([+ ...context.getImageData(160, 20, 1, 1).data,+ ]);+ const half = await render(0.5, 20, 0);+ expect(half.getImageData(160, 20, 1, 1).data[3]).toBe(0);+ expect([...half.getImageData(160, 180, 1, 1).data]).toEqual([+ ...context.getImageData(160, 180, 1, 1).data,+ ]);+ expect([...half.getImageData(0, 124, width, 8).data]).toEqual([+ ...context.getImageData(0, 124, width, 8).data,+ ]);+ // The markers rotate about the tip (160, 120) by -10 and +10 degrees.+ expect([...half.getImageData(108, 43, 1, 1).data]).toEqual([255, 0, 0, 255]);+ expect([...half.getImageData(212, 43, 1, 1).data]).toEqual([0, 255, 0, 255]);+ // Changing the edge shape must not move the image content. These two+ // progress values put the tear tip at opposite zigzag extremes.+ for (const progress of [0.625, 17 / 24]) {+ const markerPositions: number[][] = [];+ for (const jaggedness of [0, 24]) {+ const rendered = await render(progress, 20, jaggedness);+ const {data} = rendered.getImageData(0, 0, width, height);+ let sumX = 0;+ let sumY = 0;+ let count = 0;+ for (let index = 0; index < data.length; index += 4) {+ if (data[index] > 250 && data[index + 1] < 5 && data[index + 3] > 250) {+ sumX += (index / 4) % width;+ sumY += Math.floor(index / 4 / width);+ count++;+ }+ }++ expect(count).toBeGreaterThan(30);+ markerPositions.push([sumX / count, sumY / count]);+ }++ expect(+ Math.abs(markerPositions[0][0] - markerPositions[1][0]),+ ).toBeLessThan(0.25);+ expect(+ Math.abs(markerPositions[0][1] - markerPositions[1][1]),+ ).toBeLessThan(0.25);+ }++ const complete = await render(1, 20, 12);+ expect(complete.getImageData(160, 180, 1, 1).data[3]).toBe(0);+ expect(complete.getImageData(40, 120, 1, 1).data[3]).toBe(128);+ const expanded = await render(2, 20, 12);+ expect(expanded.getImageData(40, 120, 1, 1).data[3]).toBe(0);+ const offscreen = await render(3, 20, 12);+ const pixels = offscreen.getImageData(0, 0, width, height).data;+ let maxAlpha = 0;+ for (let index = 3; index < pixels.length; index += 4) {+ maxAlpha = Math.max(maxAlpha, pixels[index]);+ }++ expect(maxAlpha).toBe(0);+ const noRotation = await render(1, 0, 12);+ expect([...noRotation.getImageData(160, 20, 1, 1).data]).toEqual([+ ...context.getImageData(160, 20, 1, 1).data,+ ]);+});++test('tear() supports any direction without rotating the source image', async () => {+ const width = 320;+ const height = 240;+ const source = document.createElement('canvas');+ source.width = width;+ source.height = height;+ const context = source.getContext('2d')!;+ context.fillStyle = '#ff0000';+ context.fillRect(0, 0, width, height / 2);+ context.fillStyle = '#0000ff';+ context.fillRect(0, height / 2, width, height / 2);+ const directions = [+ {angle: 0, open: [160, 20], intact: [160, 220]},+ {angle: 90, open: [20, 120], intact: [300, 120]},+ {angle: 180, open: [160, 220], intact: [160, 20]},+ {angle: 270, open: [300, 120], intact: [20, 120]},+ {angle: 45, open: [80, 40], intact: [240, 200]},+ {angle: -90, open: [300, 120], intact: [20, 120]},+ {angle: 450, open: [20, 120], intact: [300, 120]},+ ];+ for (const {angle, open, intact} of directions) {+ for (const progress of [0, 0.5, 3]) {+ const canvas = await renderEffectChainToCanvas({+ source,+ width,+ height,+ effects: descriptorsToMemoizedEffects([+ tear({angle, progress, jaggedness: 0}),+ ]),+ });+ const output = canvas.getContext('2d')!;+ if (progress === 0) {+ for (const [x, y] of [+ [5, 5],+ [315, 5],+ [5, 235],+ [315, 235],+ ]) {+ expect([...output.getImageData(x, y, 1, 1).data]).toEqual([+ ...context.getImageData(x, y, 1, 1).data,+ ]);+ }+ } else if (progress === 0.5) {+ expect(output.getImageData(open[0], open[1], 1, 1).data[3]).toBe(0);+ expect([+ ...output.getImageData(intact[0], intact[1], 1, 1).data,+ ]).toEqual([...context.getImageData(intact[0], intact[1], 1, 1).data]);+ } else {+ const pixels = output.getImageData(0, 0, width, height).data;+ let maxAlpha = 0;+ for (let index = 3; index < pixels.length; index += 4) {+ maxAlpha = Math.max(maxAlpha, pixels[index]);+ }++ expect(maxAlpha).toBe(0);+ }+ }+ }+});diff --git a/packages/example/src/EffectsTestbed/Tear.tsx b/packages/example/src/EffectsTestbed/Tear.tsxnew file mode 100644index 0000000000..96efccba83--- /dev/null+++ b/packages/example/src/EffectsTestbed/Tear.tsx@@ -0,0 +1,58 @@+import {scale} from '@remotion/effects/scale';+import {tear} from '@remotion/effects/tear';+import React from 'react';+import {+ AbsoluteFill,+ CanvasImage,+ interpolate,+ staticFile,+ useCurrentFrame,+} from 'remotion';++export const TearTest: React.FC = () => {+ const frame = useCurrentFrame();++ return (+ <AbsoluteFill+ style={{+ backgroundColor: '#eee8df',+ alignItems: 'center',+ justifyContent: 'center',+ fontFamily: 'sans-serif',+ color: '#242424',+ }}+ >+ <div style={{position: 'absolute', top: 24, fontSize: 28}}>tear()</div>+ <CanvasImage+ src={staticFile('1.jpg')}+ width={960}+ height={540}+ fit="cover"+ effects={[+ scale({+ scale: 0.5,+ }),+ tear({+ angle: 78,+ progress: interpolate(frame, [15, 105, 149], [0, 1, 2], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ }),+ rotation: 7,+ jaggedness: 24,+ }),+ ]}+ />+ <div+ style={{+ position: 'absolute',+ bottom: 28,+ fontSize: 20,+ fontVariantNumeric: 'tabular-nums',+ }}+ >+ Frame: {frame}+ </div>+ </AbsoluteFill>+ );+};diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex 082ce70040..c8b86fc5f2 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -237,6 +237,7 @@ import {HalftoneGradient} from './EffectsTestbed/HalftoneGradient';import {NoiseDisplacementText} from './EffectsTestbed/NoiseDisplacementText';import {PaletteMapEffect} from './EffectsTestbed/PaletteMapEffect';import {RadialProgressiveBlurTest} from './EffectsTestbed/RadialProgressiveBlur';+import {TearTest} from './EffectsTestbed/Tear';import {VideoEffectsFastRefresh} from './EffectsTestbed/VideoEffectsFastRefresh';import {Empty} from './Empty';import {@@ -2269,6 +2270,14 @@ export const Index: React.FC = () => {/></Folder><Folder name="Effects">+ <Composition+ id="tear-test"+ component={TearTest}+ width={1280}+ height={720}+ fps={30}+ durationInFrames={150}+ /><RiveEffectsTestbed /><GifEffectsTestbed /><AnimatedImageEffects />diff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.tsindex 062fe9f731..debe9edd92 100644--- a/packages/studio-shared/src/effect-catalog.ts+++ b/packages/studio-shared/src/effect-catalog.ts@@ -381,6 +381,13 @@ export const EFFECT_CATALOG: readonly EffectCatalogItem[] = [config: {},},},+ {+ id: 'effects-tear',+ category: 'Reveal',+ label: 'tear()',+ description: 'Progressive zigzag tear with outward rotation',+ effect: {name: 'tear', importPath: '@remotion/effects/tear', config: {}},+ },{id: 'effects-venetian-blinds',category: 'Reveal',