🎥 Make videos programmatically with React
Add bevelAlpha effect and animated lighting demo
Jonny Burger11e8aa86151e
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsxindex 4e211f313f..9adf6d57e4 100644--- a/packages/docs/components/demos/index.tsx+++ b/packages/docs/components/demos/index.tsx@@ -26,6 +26,7 @@ import {fractalNoiseDemo,turbulentDisplaceDemo,lensBlurDemo,+ bevelAlphaDemo,customPresentationDemo,customTimingDemo,dissolvePresentationDemo,@@ -165,6 +166,7 @@ const demos: DemoType[] = [fractalNoiseDemo,turbulentDisplaceDemo,lensBlurDemo,+ bevelAlphaDemo,animationMathDemo,roundedTextBoxDemo,springDemo,diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.tsindex df0e6fde5b..9c1be90ec3 100644--- a/packages/docs/components/demos/types.ts+++ b/packages/docs/components/demos/types.ts@@ -1,4 +1,5 @@import type {LogLevel} from 'remotion';+import {BevelAlphaDemo} from '../effects/effects-bevel-alpha-preview';import {FractalNoiseDemo} from '../effects/effects-fractal-noise-preview';import {LensBlurDemo} from '../effects/effects-lens-blur-preview';import {PageTurnDemo} from '../effects/effects-page-turn-preview';@@ -1827,3 +1828,16 @@ export const lensBlurDemo: DemoType = {logLevel: 'info',options: [],};++export const bevelAlphaDemo: DemoType = {+ comp: BevelAlphaDemo,+ compWidth: 1280,+ compHeight: 720,+ fps: 30,+ durationInFrames: 120,+ id: 'bevel-alpha',+ autoPlay: true,+ controls: true,+ logLevel: 'info',+ options: [],+};diff --git a/packages/docs/components/effects-demos/registry.ts b/packages/docs/components/effects-demos/registry.tsindex ba97238b86..b69b445992 100644--- a/packages/docs/components/effects-demos/registry.ts+++ b/packages/docs/components/effects-demos/registry.ts@@ -1,4 +1,5 @@import {barrelDistortion} from '@remotion/effects/barrel-distortion';+import {bevelAlpha} from '@remotion/effects/bevel-alpha';import {blur} from '@remotion/effects/blur';import {brightness} from '@remotion/effects/brightness';import {burlap} from '@remotion/effects/burlap';@@ -78,6 +79,7 @@ import {whiteNoise} from '@remotion/effects/white-noise';import {zigzag} from '@remotion/effects/zigzag';import {zoomBlur} from '@remotion/effects/zoom-blur';import {EffectsBarrelDistortionPreview} from '../effects/effects-barrel-distortion-preview';+import {EffectsBevelAlphaPreview} from '../effects/effects-bevel-alpha-preview';import {EffectsBlurPreview} from '../effects/effects-blur-preview';import {EffectsBrightnessPreview} from '../effects/effects-brightness-preview';import {EffectsBurlapPreview} from '../effects/effects-burlap-preview';@@ -208,6 +210,14 @@ const shrinkwrapDemoSchema = {const cylinderDemoSchema = cylinder().definition.schema;export const effectsDemos: EffectsDemoType[] = [+ {+ ...defaults,+ id: 'effects-bevel-alpha',+ effectName: 'bevelAlpha',+ effectImportPath: '@remotion/effects/bevel-alpha',+ comp: EffectsBevelAlphaPreview,+ schema: bevelAlpha().definition.schema,+ },{...defaults,id: 'effects-lens-blur',diff --git a/packages/docs/components/effects/effects-bevel-alpha-preview.tsx b/packages/docs/components/effects/effects-bevel-alpha-preview.tsxnew file mode 100644index 0000000000..a90420ae7d--- /dev/null+++ b/packages/docs/components/effects/effects-bevel-alpha-preview.tsx@@ -0,0 +1,91 @@+import {bevelAlpha, type BevelAlphaParams} from '@remotion/effects/bevel-alpha';+import {Video} from '@remotion/media';+import React from 'react';+import {+ AbsoluteFill,+ CanvasImage,+ HtmlInCanvas,+ Interactive,+ interpolate,+ staticFile,+ useCurrentFrame,+} from 'remotion';+import {useHtmlInCanvasDocsDemoBranch} from '../demos/useHtmlInCanvasDocsDemoBranch';++export const BevelAlphaTextSource: React.FC = () => (+ <Interactive.Div+ name="Bevel text"+ style={{+ width: '100%',+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontFamily: 'Arial, Helvetica, sans-serif',+ fontSize: 180,+ fontWeight: 900,+ lineHeight: 1,+ color: 'white',+ }}+ >+ BEVEL+ </Interactive.Div>+);++export const EffectsBevelAlphaPreview: React.FC<Required<BevelAlphaParams>> = ({+ edgeThickness,+ lightAngle,+ lightColor,+ lightIntensity,+}) => (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <CanvasImage+ name="Beveled text"+ src={staticFile('img/effects-bevel-alpha-text.png')}+ width={1280}+ height={720}+ fit="cover"+ effects={[+ bevelAlpha({edgeThickness, lightAngle, lightColor, lightIntensity}),+ ]}+ />+ </AbsoluteFill>+);++const BevelAlphaScene: React.FC = () => {+ const frame = useCurrentFrame();+ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas+ name="Moving bevel light"+ width={1280}+ height={720}+ effects={[+ bevelAlpha({+ edgeThickness: 14,+ lightAngle: interpolate(frame, [0, 120], [-60, 300]),+ lightIntensity: 0.9,+ lightColor: 'white',+ }),+ ]}+ >+ <BevelAlphaTextSource />+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};++export const BevelAlphaDemo: React.FC = () => {+ const branch = useHtmlInCanvasDocsDemoBranch('webgl2');+ if (branch === 'pending')+ return <AbsoluteFill style={{backgroundColor: 'black'}} />;+ if (branch === 'live') return <BevelAlphaScene />;+ return (+ <Video+ name="Bevel alpha preview"+ muted+ src="https://remotion.media/bevel-alpha-demo-b61514bb5b60.mp4"+ style={{width: '100%', height: '100%'}}+ />+ );+};diff --git a/packages/docs/docs/effects/bevel-alpha.mdx b/packages/docs/docs/effects/bevel-alpha.mdxnew file mode 100644index 0000000000..1b33ec65a4--- /dev/null+++ b/packages/docs/docs/effects/bevel-alpha.mdx@@ -0,0 +1,114 @@+---+image: /generated/articles-docs-effects-bevel-alpha.png+slug: /effects/bevel-alpha+title: bevelAlpha()+sidebar_label: bevelAlpha()+crumb: '@remotion/effects'+---++# bevelAlpha()<AvailableFrom v="4.0.537" />++_Part of the [`@remotion/effects`](/docs/effects/api) package._++Adds highlights and shadows along the alpha edges of text, logos, and shapes to give them a raised appearance. The original outline and transparency are preserved.++Use a source with transparency, such as text in [`<HtmlInCanvas>`](/docs/remotion/html-in-canvas) or a transparent PNG in [`<CanvasImage>`](/docs/canvasimage). A fully opaque image has no alpha edges to bevel.++## Preview++<Demo type="bevel-alpha" />++## Controls++<EffectsDemo type="effects-bevel-alpha" />++## Example++```tsx twoslash title="MyComp.tsx"+import {bevelAlpha} from '@remotion/effects/bevel-alpha';+import {AbsoluteFill, HtmlInCanvas, Interactive, interpolate, useCurrentFrame} from 'remotion';++export const MyComp: React.FC = () => {+ const frame = useCurrentFrame();+ return (+ <AbsoluteFill style={{backgroundColor: 'black'}}>+ <HtmlInCanvas+ width={1280}+ height={720}+ effects={[+ bevelAlpha({+ edgeThickness: 14,+ lightAngle: interpolate(frame, [0, 120], [-60, 300]),+ lightColor: 'white',+ lightIntensity: 0.9,+ }),+ ]}+ >+ <Interactive.Div+ name="Bevel text"+ style={{+ width: '100%',+ height: '100%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontFamily: 'Arial, Helvetica, sans-serif',+ fontSize: 180,+ fontWeight: 900,+ color: 'white',+ }}+ >+ BEVEL+ </Interactive.Div>+ </HtmlInCanvas>+ </AbsoluteFill>+ );+};+```++## API++Pass an object with the following properties. All numeric values must be finite.++### `edgeThickness?`++Width of the rounded bevel in pixels, from `0` to `200`. Defaults to `2`.++At `0`, the source is unchanged.++### `lightAngle?`++Direction of the light in degrees, measured clockwise from above. Defaults to `-60`.++`0` lights the top edges, `90` lights the right edges, `180` lights the bottom edges, and `270` lights the left edges. Animate this value to move the light around the source.++### `lightColor?`++CSS color added to the highlighted edges. Defaults to `'white'`.++The color's alpha controls the highlight strength. Shadows still darken the original source colors.++### `lightIntensity?`++Strength of highlights and shadows, from `0` to `1`. Defaults to `0.4`.++At `0`, the source is unchanged.++### `disabled?`++When `true`, the effect is skipped. Defaults to `false`.++## Requirements++`bevelAlpha()` uses WebGL2. See [Using WebGL and WebGPU during renders](/docs/webgl).++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering serverSideRendering player studio hideServers />++## See also++- [`dropShadow()`](/docs/effects/drop-shadow)+- [`outline()`](/docs/effects/outline)+- [`@remotion/effects`](/docs/effects/api)+- [Source code](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/bevel-alpha/index.ts)diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex ee00ebf6f8..0c88a4e77c 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -283,6 +283,7 @@ const sidebars: SidebarsConfig = {},items: ['effects/barrel-distortion',+ 'effects/bevel-alpha','effects/blur','effects/brightness','effects/burlap',diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex b953191769..3c03389dd6 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -3393,6 +3393,15 @@ export const articles = [noAi: false,slug: 'effects/barrel-distortion',},+ {+ id: 'effects/bevel-alpha',+ title: 'bevelAlpha()',+ relativePath: 'docs/effects/bevel-alpha.mdx',+ compId: 'articles-docs-effects-bevel-alpha',+ crumb: '@remotion/effects',+ noAi: false,+ slug: 'effects/bevel-alpha',+ },{id: 'effects/blur',title: 'blur()',diff --git a/packages/docs/src/remotion/Root.tsx b/packages/docs/src/remotion/Root.tsxindex bd9f34437c..873ac83000 100644--- a/packages/docs/src/remotion/Root.tsx+++ b/packages/docs/src/remotion/Root.tsx@@ -5,6 +5,11 @@ import {Composition, Folder, Still} from 'remotion';import {CylinderTextDemo} from '../../components/demos/CylinderTextDemo';import {MotionBlurHtmlInCanvasLiveDemo} from '../../components/demos/MotionBlurDemo';import {EffectsBarrelDistortionPreview} from '../../components/effects/effects-barrel-distortion-preview';+import {+ EffectsBevelAlphaPreview,+ BevelAlphaDemo,+ BevelAlphaTextSource,+} from '../../components/effects/effects-bevel-alpha-preview';import {EffectsBlurPreview} from '../../components/effects/effects-blur-preview';import {EffectsBrightnessPreview} from '../../components/effects/effects-brightness-preview';import {EffectsBurlapPreview} from '../../components/effects/effects-burlap-preview';@@ -447,6 +452,32 @@ export const RemotionRoot: React.FC = () => {feather: 0.18,}}/>+ <Still+ id="effects-bevel-alpha-text-source"+ component={BevelAlphaTextSource}+ width={1280}+ height={720}+ />+ <Still+ id="effects-bevel-alpha-preview"+ component={EffectsBevelAlphaPreview}+ width={1280}+ height={720}+ defaultProps={{+ edgeThickness: 14,+ lightAngle: -60,+ lightColor: 'white',+ lightIntensity: 0.9,+ }}+ />+ <Composition+ id="bevel-alpha-demo"+ component={BevelAlphaDemo}+ width={1280}+ height={720}+ fps={30}+ durationInFrames={120}+ /><Stillid="effects-lens-blur-preview"component={EffectsLensBlurPreview}diff --git a/packages/docs/static/generated/articles-docs-effects-bevel-alpha.png b/packages/docs/static/generated/articles-docs-effects-bevel-alpha.pngnew file mode 100644index 0000000000..f67e376a3aBinary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-bevel-alpha.png differdiff --git a/packages/docs/static/img/effects-bevel-alpha-preview.png b/packages/docs/static/img/effects-bevel-alpha-preview.pngnew file mode 100644index 0000000000..6152ad814bBinary files /dev/null and b/packages/docs/static/img/effects-bevel-alpha-preview.png differdiff --git a/packages/docs/static/img/effects-bevel-alpha-text.png b/packages/docs/static/img/effects-bevel-alpha-text.pngnew file mode 100644index 0000000000..e4243d3c4bBinary files /dev/null and b/packages/docs/static/img/effects-bevel-alpha-text.png differdiff --git a/packages/effects/THIRD_PARTY_LICENSES.md b/packages/effects/THIRD_PARTY_LICENSES.mdindex 16df195742..ea48371e67 100644--- a/packages/effects/THIRD_PARTY_LICENSES.md+++ b/packages/effects/THIRD_PARTY_LICENSES.md@@ -2,8 +2,8 @@## EffectCraft-The Fractal Noise, Turbulent Displace, and Lens Blur shaders are adapted from-the noise, distortion, and blur engines in+The Fractal Noise, Turbulent Displace, Lens Blur, and Bevel Alpha shaders are+adapted from the noise, distortion, blur, and perspective engines in[EffectCraft](https://github.com/storytold/effectcraft), revision`8f02f52a44a4b1ea807d8824b92301b96f896a06`. It is used under the MIT license.diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.tsindex 79d6ed0c1b..38a429280c 100644--- a/packages/effects/bundle.ts+++ b/packages/effects/bundle.ts@@ -8,6 +8,7 @@ if (process.env.NODE_ENV !== 'production') {const effectEntrypoints = ['src/index.ts','src/barrel-distortion.ts',+ 'src/bevel-alpha.ts','src/blur.ts','src/burlap.ts','src/checkerboard.ts',diff --git a/packages/effects/package.json b/packages/effects/package.jsonindex c5aba55882..3247dbc8ce 100644--- a/packages/effects/package.json+++ b/packages/effects/package.json@@ -39,6 +39,11 @@"module": "./dist/esm/barrel-distortion.mjs","import": "./dist/esm/barrel-distortion.mjs"},+ "./bevel-alpha": {+ "types": "./dist/bevel-alpha.d.ts",+ "module": "./dist/esm/bevel-alpha.mjs",+ "import": "./dist/esm/bevel-alpha.mjs"+ },"./blur": {"types": "./dist/blur.d.ts","module": "./dist/esm/blur.mjs",@@ -436,6 +441,9 @@"barrel-distortion": ["dist/barrel-distortion.d.ts"],+ "bevel-alpha": [+ "dist/bevel-alpha.d.ts"+ ],"blur": ["dist/blur.d.ts"],diff --git a/packages/effects/src/bevel-alpha.ts b/packages/effects/src/bevel-alpha.tsnew file mode 100644index 0000000000..7d553c1a8c--- /dev/null+++ b/packages/effects/src/bevel-alpha.ts@@ -0,0 +1 @@+export {bevelAlpha, type BevelAlphaParams} from './bevel-alpha/index.js';diff --git a/packages/effects/src/bevel-alpha/index.ts b/packages/effects/src/bevel-alpha/index.tsnew file mode 100644index 0000000000..733a64cece--- /dev/null+++ b/packages/effects/src/bevel-alpha/index.ts@@ -0,0 +1,387 @@+import type {InteractivitySchema} from 'remotion';+import {Internals} from 'remotion';+import {+ assertOptionalFiniteNumber,+ parseColorRgba,+ type ParsedColorRgba,+ validateNonNegative,+ validateUnitInterval,+} from '../color-utils.js';+import {+ assertEffectParamsObject,+ assertOptionalColor,+} from '../validate-effect-param.js';+import {+ BEVEL_ALPHA_VERTEX_SHADER,+ BEVEL_ALPHA_SHADE_SHADER,+ buildBevelAlphaBlurShader,+} from './shaders.js';++const {createEffect, createWebGL2ContextError} = Internals;+const DEFAULT_EDGE_THICKNESS = 2 as const;+const DEFAULT_LIGHT_ANGLE = -60 as const;+const DEFAULT_LIGHT_COLOR = 'white' as const;+const DEFAULT_LIGHT_INTENSITY = 0.4 as const;++const bevelAlphaSchema = {+ edgeThickness: {+ type: 'number',+ min: 0,+ max: 200,+ step: 0.1,+ default: DEFAULT_EDGE_THICKNESS,+ description: 'Edge thickness',+ hiddenFromList: false,+ },+ lightAngle: {+ type: 'rotation-degrees',+ step: 1,+ default: DEFAULT_LIGHT_ANGLE,+ description: 'Light angle',+ },+ lightColor: {+ type: 'color',+ default: DEFAULT_LIGHT_COLOR,+ description: 'Light color',+ },+ lightIntensity: {+ type: 'number',+ min: 0,+ max: 1,+ step: 0.01,+ default: DEFAULT_LIGHT_INTENSITY,+ description: 'Light intensity',+ hiddenFromList: false,+ },+} as const satisfies InteractivitySchema;++export type BevelAlphaParams = {+ /** Width of the rounded bevel in pixels, from 0 to 200. Defaults to `2`. */+ readonly edgeThickness?: number;+ /** Light direction in degrees, clockwise from above. Defaults to `-60`. */+ readonly lightAngle?: number;+ /** CSS color of the highlights. Defaults to `white`. */+ readonly lightColor?: string;+ /** Strength of highlights and shadows, from 0 to 1. Defaults to `0.4`. */+ readonly lightIntensity?: number;+};++type BevelAlphaResolved = Required<BevelAlphaParams>;+const resolve = (p: BevelAlphaParams): BevelAlphaResolved => ({+ edgeThickness: p.edgeThickness ?? DEFAULT_EDGE_THICKNESS,+ lightAngle: p.lightAngle ?? DEFAULT_LIGHT_ANGLE,+ lightColor: p.lightColor ?? DEFAULT_LIGHT_COLOR,+ lightIntensity: p.lightIntensity ?? DEFAULT_LIGHT_INTENSITY,+});++const validateBevelAlphaParams = (params: BevelAlphaParams): void => {+ assertEffectParamsObject(params, 'Bevel alpha');+ assertOptionalFiniteNumber(params.edgeThickness, 'edgeThickness');+ assertOptionalFiniteNumber(params.lightAngle, 'lightAngle');+ assertOptionalColor(params.lightColor, 'lightColor');+ assertOptionalFiniteNumber(params.lightIntensity, 'lightIntensity');+ const r = resolve(params);+ validateNonNegative(r.edgeThickness, 'edgeThickness');+ if (r.edgeThickness > 200)+ throw new TypeError('"edgeThickness" must be at most 200');+ validateUnitInterval(r.lightIntensity, 'lightIntensity');+};++type BlurPass = {+ readonly program: WebGLProgram;+ readonly uSource: WebGLUniformLocation | null;+ readonly uResolution: WebGLUniformLocation | null;+ readonly uRadius: WebGLUniformLocation | null;+};+type BevelAlphaState = {+ readonly gl: WebGL2RenderingContext;+ readonly horizontal: BlurPass;+ readonly vertical: BlurPass;+ readonly program: WebGLProgram;+ readonly vao: WebGLVertexArrayObject;+ readonly vbo: WebGLBuffer;+ readonly texture: WebGLTexture;+ readonly intermediate: WebGLTexture;+ readonly heightTexture: WebGLTexture;+ readonly framebuffer: WebGLFramebuffer;+ readonly uSource: WebGLUniformLocation | null;+ readonly uHeight: WebGLUniformLocation | null;+ readonly uResolution: WebGLUniformLocation | null;+ readonly uEdgeThickness: WebGLUniformLocation | null;+ readonly uLightDirection: WebGLUniformLocation | null;+ readonly uLightColor: WebGLUniformLocation | null;+ readonly uLightIntensity: WebGLUniformLocation | null;+ readonly colorCtx: CanvasRenderingContext2D;+ cachedColor: string;+ cachedColorRgba: ParsedColorRgba;+ width: number;+ height: number;+};++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(`BevelAlpha 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(`BevelAlpha program link failed: ${log ?? '(no log)'}`);+ }++ return program;+};++const setupBevelAlpha = (target: HTMLCanvasElement): BevelAlphaState => {+ const gl = target.getContext('webgl2', {+ premultipliedAlpha: true,+ alpha: true,+ preserveDrawingBuffer: true,+ });+ if (!gl) throw createWebGL2ContextError('bevel alpha effect');+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);+ // Dithering would corrupt the low byte of the packed height field.+ gl.disable(gl.DITHER);+ const vs = compileShader(gl, gl.VERTEX_SHADER, BEVEL_ALPHA_VERTEX_SHADER);+ const programs = [+ buildBevelAlphaBlurShader('horizontal'),+ buildBevelAlphaBlurShader('vertical'),+ BEVEL_ALPHA_SHADE_SHADER,+ ].map((source) => {+ const fs = compileShader(gl, gl.FRAGMENT_SHADER, source);+ const shaderProgram = linkProgram(gl, vs, fs);+ gl.deleteShader(fs);+ return shaderProgram;+ });+ gl.deleteShader(vs);+ const [horizontalProgram, verticalProgram, program] = programs;+ const passes = [horizontalProgram, verticalProgram].map((p) => ({+ program: p,+ uSource: gl.getUniformLocation(p, 'uSource'),+ uResolution: gl.getUniformLocation(p, 'uResolution'),+ uRadius: gl.getUniformLocation(p, 'uRadius'),+ }));+ const vao = gl.createVertexArray();+ const vbo = gl.createBuffer();+ const framebuffer = gl.createFramebuffer();+ if (!vao || !vbo || !framebuffer)+ throw new Error('Could not allocate bevel alpha WebGL resources');+ gl.bindVertexArray(vao);+ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);+ gl.bufferData(+ gl.ARRAY_BUFFER,+ new Float32Array([-1, -1, 0, 0, 1, -1, 1, 0, -1, 1, 0, 1, 1, 1, 1, 1]),+ gl.STATIC_DRAW,+ );+ gl.enableVertexAttribArray(0);+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 16, 0);+ gl.enableVertexAttribArray(1);+ gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 16, 8);+ gl.bindVertexArray(null);+ const textures = [gl.LINEAR, gl.NEAREST, gl.NEAREST].map((filter) => {+ const texture = gl.createTexture();+ if (!texture) throw new Error('Could not allocate bevel alpha 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);+ return texture;+ });+ gl.bindTexture(gl.TEXTURE_2D, null);+ const colorCanvas = document.createElement('canvas');+ colorCanvas.width = 1;+ colorCanvas.height = 1;+ const colorCtx = colorCanvas.getContext('2d', {willReadFrequently: true});+ if (!colorCtx)+ throw new Error('Failed to acquire 2D context for color parsing');+ return {+ gl,+ horizontal: passes[0],+ vertical: passes[1],+ program,+ vao,+ vbo,+ framebuffer,+ texture: textures[0],+ intermediate: textures[1],+ heightTexture: textures[2],+ uSource: gl.getUniformLocation(program, 'uSource'),+ uHeight: gl.getUniformLocation(program, 'uHeight'),+ uResolution: gl.getUniformLocation(program, 'uResolution'),+ uEdgeThickness: gl.getUniformLocation(program, 'uEdgeThickness'),+ uLightDirection: gl.getUniformLocation(program, 'uLightDirection'),+ uLightColor: gl.getUniformLocation(program, 'uLightColor'),+ uLightIntensity: gl.getUniformLocation(program, 'uLightIntensity'),+ colorCtx,+ cachedColor: '',+ cachedColorRgba: [255, 255, 255, 255],+ width: 0,+ height: 0,+ };+};++export const bevelAlpha = createEffect<BevelAlphaParams, BevelAlphaState>({+ type: 'remotion/bevel-alpha',+ label: 'bevelAlpha()',+ documentationLink: 'https://www.remotion.dev/docs/effects/bevel-alpha',+ backend: 'webgl2',+ calculateKey: (params) => `bevel-alpha-${JSON.stringify(resolve(params))}`,+ setup: setupBevelAlpha,+ apply: ({source, width, height, params, state, flipSourceY}) => {+ const r = resolve(params);+ const {+ gl,+ texture,+ intermediate,+ heightTexture,+ program,+ vao,+ framebuffer,+ } = state;+ if (state.cachedColor !== r.lightColor) {+ state.cachedColor = r.lightColor;+ state.cachedColorRgba = parseColorRgba(state.colorCtx, r.lightColor);+ }++ gl.viewport(0, 0, width, height);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flipSourceY);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ source as TexImageSource,+ );+ if (state.width !== width || state.height !== height) {+ for (const output of [intermediate, heightTexture]) {+ gl.bindTexture(gl.TEXTURE_2D, output);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ width,+ height,+ 0,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ null,+ );+ }++ state.width = width;+ state.height = height;+ }++ gl.bindVertexArray(vao);+ if (r.edgeThickness > 0 && r.lightIntensity > 0) {+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);+ for (const [pass, input, output] of [+ [state.horizontal, texture, intermediate],+ [state.vertical, intermediate, heightTexture],+ ] as const) {+ gl.framebufferTexture2D(+ gl.FRAMEBUFFER,+ gl.COLOR_ATTACHMENT0,+ gl.TEXTURE_2D,+ output,+ 0,+ );+ if (+ gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE+ )+ throw new Error('Bevel alpha framebuffer is incomplete');+ gl.bindTexture(gl.TEXTURE_2D, input);+ gl.useProgram(pass.program);+ gl.uniform1i(pass.uSource, 0);+ gl.uniform2f(pass.uResolution, width, height);+ // Gaussian shader radius covers three standard deviations; sigma=t/2.+ gl.uniform1f(pass.uRadius, r.edgeThickness * 1.5);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ }+ }++ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.activeTexture(gl.TEXTURE1);+ gl.bindTexture(gl.TEXTURE_2D, heightTexture);+ gl.useProgram(program);+ gl.uniform1i(state.uSource, 0);+ gl.uniform1i(state.uHeight, 1);+ gl.uniform2f(state.uResolution, width, height);+ gl.uniform1f(state.uEdgeThickness, r.edgeThickness);+ const angle = ((r.lightAngle % 360) * Math.PI) / 180;+ gl.uniform3f(+ state.uLightDirection,+ Math.sin(angle) * Math.SQRT1_2,+ -Math.cos(angle) * Math.SQRT1_2,+ Math.SQRT1_2,+ );+ const [red, green, blue, alpha] = state.cachedColorRgba;+ gl.uniform3f(+ state.uLightColor,+ ((red / 255) * alpha) / 255,+ ((green / 255) * alpha) / 255,+ ((blue / 255) * alpha) / 255,+ );+ gl.uniform1f(state.uLightIntensity, r.lightIntensity);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ gl.bindVertexArray(null);+ gl.bindTexture(gl.TEXTURE_2D, null);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, null);+ gl.useProgram(null);+ },+ cleanup: (state) => {+ const {gl} = state;+ for (const texture of [+ state.texture,+ state.intermediate,+ state.heightTexture,+ ])+ gl.deleteTexture(texture);+ for (const program of [+ state.horizontal.program,+ state.vertical.program,+ state.program,+ ])+ gl.deleteProgram(program);+ gl.deleteFramebuffer(state.framebuffer);+ gl.deleteBuffer(state.vbo);+ gl.deleteVertexArray(state.vao);+ },+ schema: bevelAlphaSchema,+ validateParams: validateBevelAlphaParams,+});diff --git a/packages/effects/src/bevel-alpha/shaders.ts b/packages/effects/src/bevel-alpha/shaders.tsnew file mode 100644index 0000000000..addae758f0--- /dev/null+++ b/packages/effects/src/bevel-alpha/shaders.ts@@ -0,0 +1,102 @@+// Alpha-derived normals and shading adapted from EffectCraft's perspective.rs+// (MIT). See ../../THIRD_PARTY_LICENSES.md.+export const BEVEL_ALPHA_VERTEX_SHADER = /* glsl */ `#version 300 es+layout(location = 0) in vec2 aPos;+layout(location = 1) in vec2 aUv;+out vec2 vUv;+void main() {+ vUv = aUv;+ gl_Position = vec4(aPos, 0.0, 1.0);+}+`;++const HEIGHT_ENCODING = /* glsl */ `+// Store a 16-bit height in two 8-bit channels. This avoids banded normals+// without requiring floating-point render targets or WebGL extensions.+vec4 encodeHeight(float height) {+ float value = floor(clamp(height, 0.0, 1.0) * 65535.0 + 0.5);+ return vec4(floor(value / 256.0), mod(value, 256.0), 0.0, 255.0) / 255.0;+}+float decodeHeight(vec4 value) {+ return dot(value.rg, vec2(65280.0, 255.0)) / 65535.0;+}+`;++export const buildBevelAlphaBlurShader = (+ direction: 'horizontal' | 'vertical',+) => /* glsl */ `#version 300 es+precision highp float;+in vec2 vUv;+out vec4 fragColor;+uniform sampler2D uSource;+uniform vec2 uResolution;+uniform float uRadius;+${HEIGHT_ENCODING}+float readHeight(vec2 uv) {+ ${+ direction === 'horizontal'+ ? 'return texture(uSource, uv).a;'+ : `+ // Decode before interpolating: packed channel values cannot be filtered.+ vec2 pixel = uv * uResolution - 0.5;+ ivec2 lower = ivec2(int(gl_FragCoord.x), int(floor(pixel.y)));+ ivec2 maximum = ivec2(uResolution) - 1;+ float a = decodeHeight(texelFetch(uSource, clamp(lower, ivec2(0), maximum), 0));+ float b = decodeHeight(texelFetch(uSource, clamp(lower + ivec2(0, 1), ivec2(0), maximum), 0));+ return mix(a, b, fract(pixel.y));`+ }+}+void main() {+ float radius = max(uRadius, 0.0001);+ int halfKernel = int(clamp(ceil(radius), 4.0, 64.0));+ float sigma = radius / 3.0;+ float sum = 0.0;+ float total = 0.0;+ for (int i = -64; i <= 64; i++) {+ if (abs(i) > halfKernel) continue;+ float offset = float(i) * radius / float(halfKernel);+ float weight = exp(-0.5 * offset * offset / (sigma * sigma));+ vec2 uv = vUv + ${direction === 'horizontal' ? 'vec2(offset, 0.0)' : 'vec2(0.0, offset)'} / uResolution;+ sum += readHeight(uv) * weight;+ total += weight;+ }+ fragColor = encodeHeight(sum / total);+}+`;++export const BEVEL_ALPHA_SHADE_SHADER = /* glsl */ `#version 300 es+precision highp float;+in vec2 vUv;+out vec4 fragColor;+uniform sampler2D uSource;+uniform sampler2D uHeight;+uniform vec2 uResolution;+uniform float uEdgeThickness;+uniform vec3 uLightDirection;+uniform vec3 uLightColor;+uniform float uLightIntensity;+${HEIGHT_ENCODING}+float heightAt(ivec2 pixel) {+ return decodeHeight(texelFetch(uHeight, clamp(pixel, ivec2(0), ivec2(uResolution) - 1), 0));+}+void main() {+ vec4 source = texelFetch(uSource, ivec2(gl_FragCoord.xy), 0);+ if (uEdgeThickness == 0.0 || uLightIntensity == 0.0 || source.a == 0.0) {+ fragColor = source;+ return;+ }+ ivec2 pixel = ivec2(gl_FragCoord.xy);+ float dx = (heightAt(pixel + ivec2(1, 0)) - heightAt(pixel - ivec2(1, 0))) * 0.5;+ // Screen-space Y points down; texture-space Y points up.+ float dy = (heightAt(pixel - ivec2(0, 1)) - heightAt(pixel + ivec2(0, 1))) * 0.5;+ vec3 normal = normalize(vec3(-dx * uEdgeThickness * 1.25, -dy * uEdgeThickness * 1.25, 1.0));+ float shade = (dot(normal, uLightDirection) - uLightDirection.z) * uLightIntensity * 2.0;+ vec3 color = source.rgb;+ if (shade > 0.0) {+ color += uLightColor * shade * source.a;+ } else {+ color *= max(1.0 + shade, 0.0);+ }+ fragColor = vec4(clamp(color, vec3(0.0), vec3(source.a)), source.a);+}+`;diff --git a/packages/studio-shared/src/effect-catalog.ts b/packages/studio-shared/src/effect-catalog.tsindex 07067a3723..bcdac019c4 100644--- a/packages/studio-shared/src/effect-catalog.ts+++ b/packages/studio-shared/src/effect-catalog.ts@@ -618,6 +618,17 @@ export const EFFECT_CATALOG: readonly EffectCatalogItem[] = [config: {},},},+ {+ id: 'effects-bevel-alpha',+ category: 'Stylize',+ label: 'bevelAlpha()',+ description: 'Light and shade the edges of text and shapes',+ effect: {+ name: 'bevelAlpha',+ importPath: '@remotion/effects/bevel-alpha',+ config: {},+ },+ },{id: 'effects-emboss',category: 'Stylize',