🎥 Make videos programmatically with React
@remotion/three overview
Jonny Burger56f0c06c911d
diff --git a/packages/docs/components/3DPhone/Phone.tsx b/packages/docs/components/3DPhone/Phone.tsxnew file mode 100644index 0000000000..27e6662d2e--- /dev/null+++ b/packages/docs/components/3DPhone/Phone.tsx@@ -0,0 +1,113 @@+import {useThree} from '@react-three/fiber';+import React, {useEffect, useMemo} from 'react';+import {interpolate, spring, useCurrentFrame, useVideoConfig} from 'remotion';+import {VideoTexture} from 'three';+import {+ CAMERA_DISTANCE,+ getPhoneLayout,+ PHONE_COLOR,+ PHONE_CURVE_SEGMENTS,+ PHONE_SHININESS,+} from './helpers/constants';+import {roundedRect} from './helpers/rounded-rectangle';+import {RoundedBox} from './RoundedBox';++export const Phone: React.FC<{+ videoTexture: VideoTexture | null;+ aspectRatio: number;+ baseScale: number;+}> = ({aspectRatio, videoTexture, baseScale}) => {+ const frame = useCurrentFrame();+ const {fps, durationInFrames} = useVideoConfig();++ const layout = useMemo(+ () => getPhoneLayout(aspectRatio, baseScale),+ [aspectRatio, baseScale]+ );++ // Place a camera and set the distance to the object.+ // Then make it look at the object.+ const camera = useThree((state) => state.camera);+ useEffect(() => {+ camera.position.set(0, 0, CAMERA_DISTANCE);+ camera.near = 0.2;+ camera.far = Math.max(5000, CAMERA_DISTANCE * 2);+ camera.lookAt(0, 0, 0);+ }, [camera]);++ // Make the video fill the phone texture+ useEffect(() => {+ if (videoTexture) {+ videoTexture.repeat.y = 1 / layout.screen.height;+ videoTexture.repeat.x = 1 / layout.screen.width;+ }+ }, [aspectRatio, layout.screen.height, layout.screen.width, videoTexture]);++ // During the whole scene, the phone is rotating.+ // 2 * Math.PI is a full rotation.+ const constantRotation = interpolate(+ frame,+ [0, durationInFrames],+ [0, Math.PI * 6]+ );++ // When the composition starts, there is some extra+ // rotation and translation.+ const entranceAnimation = spring({+ frame,+ fps,+ config: {+ damping: 200,+ mass: 3,+ },+ });++ // Calculate the entrance rotation,+ // doing one full spin+ const entranceRotation = interpolate(+ entranceAnimation,+ [0, 1],+ [-Math.PI, Math.PI]+ );++ // Calculating the total rotation of the phone+ const rotateY = entranceRotation + constantRotation;++ // Calculating the translation of the phone at the beginning.+ // The start position of the phone is set to 4 "units"+ const translateY = interpolate(entranceAnimation, [0, 1], [-4, 0]);++ // Calculate a rounded rectangle for the phone screen+ const screenGeometry = useMemo(() => {+ return roundedRect({+ width: layout.screen.width,+ height: layout.screen.height,+ radius: layout.screen.radius,+ });+ }, [layout.screen.height, layout.screen.radius, layout.screen.width]);++ return (+ <group+ scale={entranceAnimation}+ rotation={[0, rotateY, 0]}+ position={[0, translateY, 0]}+ >+ <RoundedBox+ radius={layout.phone.radius}+ depth={layout.phone.thickness}+ curveSegments={PHONE_CURVE_SEGMENTS}+ position={layout.phone.position}+ width={layout.phone.width}+ height={layout.phone.height}+ >+ <meshPhongMaterial color={PHONE_COLOR} shininess={PHONE_SHININESS} />+ </RoundedBox>+ <mesh position={layout.screen.position}>+ <shapeGeometry args={[screenGeometry]} />+ {videoTexture ? (+ <meshBasicMaterial morphTargets map={videoTexture} />+ ) : null}+ </mesh>+ </group>+ );+};diff --git a/packages/docs/components/3DPhone/RoundedBox.tsx b/packages/docs/components/3DPhone/RoundedBox.tsxnew file mode 100644index 0000000000..798186f01f--- /dev/null+++ b/packages/docs/components/3DPhone/RoundedBox.tsx@@ -0,0 +1,43 @@+import React, {useMemo} from 'react';+import {roundedRect} from './helpers/rounded-rectangle';++type Props = {+ width: number;+ height: number;+ radius: number;+ curveSegments: number;+ depth: number;+} & Omit<JSX.IntrinsicElements['mesh'], 'args'>;++export const RoundedBox: React.FC<Props> = ({+ width,+ height,+ radius,+ curveSegments: curveSegments,+ children,+ depth,+ ...otherProps+}) => {+ const shape = useMemo(+ () => roundedRect({width, height, radius}),+ [height, radius, width]+ );++ const params = useMemo(+ () => ({+ depth,+ bevelEnabled: true,+ bevelSize: 0,+ bevelThickness: 0,+ curveSegments,+ }),+ [curveSegments, depth]+ );++ return (+ <mesh {...otherProps}>+ <extrudeBufferGeometry attach="geometry" args={[shape, params]} />+ {children}+ </mesh>+ );+};diff --git a/packages/docs/components/3DPhone/Scene.tsx b/packages/docs/components/3DPhone/Scene.tsxnew file mode 100644index 0000000000..f44b5797ea--- /dev/null+++ b/packages/docs/components/3DPhone/Scene.tsx@@ -0,0 +1,43 @@+import { getVideoMetadata, VideoMetadata } from "@remotion/media-utils";+import { ThreeCanvas, useVideoTexture } from "@remotion/three";+import React, { useEffect, useRef, useState } from "react";+import { AbsoluteFill, useVideoConfig, Video } from "remotion";+import { Phone } from "./Phone";++const videoStyle: React.CSSProperties = {+ position: "absolute",+ opacity: 0,+};++export const Scene: React.FC<{+ videoSrc: string;+ baseScale: number;+}> = ({ baseScale, videoSrc }) => {+ const videoRef = useRef<HTMLVideoElement>(null);+ const { width, height } = useVideoConfig();+ const [videoData, setVideoData] = useState<VideoMetadata | null>(null);++ useEffect(() => {+ getVideoMetadata(videoSrc)+ .then((data) => setVideoData(data))+ .catch((err) => console.log(err));+ }, [videoSrc]);++ const texture = useVideoTexture(videoRef);+ return (+ <AbsoluteFill>+ <Video ref={videoRef} src={videoSrc} style={videoStyle} />+ {videoData ? (+ <ThreeCanvas width={width} height={height}>+ <ambientLight intensity={1.5} color={0xffffff} />+ <pointLight position={[10, 10, 0]} />+ <Phone+ baseScale={baseScale}+ videoTexture={texture}+ aspectRatio={videoData.aspectRatio}+ />+ </ThreeCanvas>+ ) : null}+ </AbsoluteFill>+ );+};diff --git a/packages/docs/components/3DPhone/assets/phone.mp4 b/packages/docs/components/3DPhone/assets/phone.mp4new file mode 100644index 0000000000..d805b460ddBinary files /dev/null and b/packages/docs/components/3DPhone/assets/phone.mp4 differdiff --git a/packages/docs/components/3DPhone/helpers/constants.ts b/packages/docs/components/3DPhone/helpers/constants.tsnew file mode 100644index 0000000000..7d1fc14852--- /dev/null+++ b/packages/docs/components/3DPhone/helpers/constants.ts@@ -0,0 +1,101 @@+import {Vector3} from '@react-three/fiber';++// The distance from which the camera is pointing to the phone.+export const CAMERA_DISTANCE = 2.5;++// A small number to avoid z-index flickering+export const Z_FLICKER_PREVENTION = 0.001;++// Shininess of the phone+export const PHONE_SHININESS = 30;++// In how many segments the phone rounded corners+// are divided. Increase number for smoother phone+export const PHONE_CURVE_SEGMENTS = 8;++// The color of the phone, like a hex color but as a number+// e.g. "#41a7f5" -> 0x41a7f5+export const PHONE_COLOR = 0x41a7f5;++// Calculate phone size. Whichever side is smaller gets+// normalized to the base scale.+const getPhoneHeight = (aspectRatio: number, baseScale: number): number => {+ if (aspectRatio > 1) {+ return baseScale;+ }+ return baseScale / aspectRatio;+};++const getPhoneWidth = (aspectRatio: number, baseScale: number): number => {+ if (aspectRatio < 1) {+ return baseScale;+ }+ return baseScale * aspectRatio;+};++type Layout = {+ position: Vector3;+ height: number;+ width: number;+ radius: number;+};++type PhoneLayout = {+ phone: Layout & {+ thickness: number;+ bevel: number;+ };+ screen: Layout;+};++export const getPhoneLayout = (+ // I recommend building the phone layout based+ // on the aspect ratio of the phone+ aspectRatio: number,+ // This value can be increased or decreased to tweak the+ // base value of the phone.+ baseScale: number+): PhoneLayout => {+ // The depth of the phone body+ const phoneThickness = baseScale * 0.15;++ // How big the border of the phone is.+ const phoneBevel = baseScale * 0.04;++ // The inner radius of the phone, aka the screen radius+ const screenRadius = baseScale * 0.07;++ const phoneHeight = getPhoneHeight(aspectRatio, baseScale);+ const phoneWidth = getPhoneWidth(aspectRatio, baseScale);+ const phonePosition: Vector3 = [-phoneWidth / 2, -phoneHeight / 2, 0];+ const screenWidth = phoneWidth - phoneBevel * 2;+ const screenHeight = phoneHeight - phoneBevel * 2;+ const screenPosition: Vector3 = [+ -screenWidth / 2,+ -screenHeight / 2,+ phoneThickness + Z_FLICKER_PREVENTION,+ ];++ // Define the outer radius of the phone.+ // It looks better if the outer radius is a bit bigger than the screen radios,+ // formula taken from https://twitter.com/joshwcomeau/status/134978208002102886+ const phoneRadius =+ screenRadius + (getPhoneWidth(aspectRatio, baseScale) - screenWidth) / 2;++ return {+ phone: {+ position: phonePosition,+ height: phoneHeight,+ width: phoneWidth,+ radius: phoneRadius,+ thickness: phoneThickness,+ bevel: phoneBevel,+ },+ screen: {+ position: screenPosition,+ height: screenHeight,+ width: screenWidth,+ radius: screenRadius,+ },+ };+};diff --git a/packages/docs/components/3DPhone/helpers/rounded-rectangle.ts b/packages/docs/components/3DPhone/helpers/rounded-rectangle.tsnew file mode 100644index 0000000000..52e24dc6c3--- /dev/null+++ b/packages/docs/components/3DPhone/helpers/rounded-rectangle.ts@@ -0,0 +1,23 @@+import {Shape} from 'three';++export function roundedRect({+ width,+ height,+ radius,+}: {+ width: number;+ height: number;+ radius: number;+}): Shape {+ const roundedRectShape = new Shape();+ roundedRectShape.moveTo(0, radius);+ roundedRectShape.lineTo(0, height - radius);+ roundedRectShape.quadraticCurveTo(0, height, radius, height);+ roundedRectShape.lineTo(width - radius, height);+ roundedRectShape.quadraticCurveTo(width, height, width, height - radius);+ roundedRectShape.lineTo(width, radius);+ roundedRectShape.quadraticCurveTo(width, 0, width - radius, 0);+ roundedRectShape.lineTo(radius, 0);+ roundedRectShape.quadraticCurveTo(0, 0, 0, radius);+ return roundedRectShape;+}diff --git a/packages/docs/components/3DPhonePlayer.tsx b/packages/docs/components/3DPhonePlayer.tsxnew file mode 100644index 0000000000..d2eb30fad1--- /dev/null+++ b/packages/docs/components/3DPhonePlayer.tsx@@ -0,0 +1,26 @@+import { Player } from "@remotion/player";+import React from "react";+import phone from "./3DPhone/assets/phone.mp4";+import { Scene } from "./3DPhone/Scene";++export const ThreeDPlayer: React.FC = () => {+ return (+ <Player+ component={Scene}+ compositionWidth={1280}+ compositionHeight={720}+ durationInFrames={300}+ controls+ loop+ autoPlay+ style={{+ width: "100%",+ }}+ fps={30}+ inputProps={{+ videoSrc: phone,+ baseScale: 1,+ }}+ ></Player>+ );+};diff --git a/packages/docs/docs/three.mdx b/packages/docs/docs/three.mdxnew file mode 100644index 0000000000..c9624dff2d--- /dev/null+++ b/packages/docs/docs/three.mdx@@ -0,0 +1,58 @@+---+id: three+title: "@remotion/three"+sidebar_label: Overview+---++import Tabs from "@theme/Tabs";+import { ThreeDPlayer } from "../components/3DPhonePlayer.tsx";++is a package for integrating [React Three Fiber](https://github.com/pmndrs/react-three-fiber) with Remotion.++- [`<ThreeCanvas />`](/docs/three-canvas) will allow you to use `useCurrentFrame()` and other Remotion hooks within a R3F Canvas. Animations are now not inside a `useFrame()` hook but directly rendered into the markup.++- [`useVideoTexture()`](/docs/use-video-texture) allows you to use a Remotion [`<Video />`](/docs/video) as a texture map.++These are the only two APIs provided - for everything else you can use the standard [React Three Fiber](https://github.com/pmndrs/react-three-fiber) APIs.++## Starter template++Check out [remotion-template-three](https://github.com/jonnyburger/remotion-template-three), a minimal boilerplate for Remotion and React Three Fiber. It is a template repository, you can click "Use this template" on the Github repo to get started.++<ThreeDPlayer />++The template features a 3D phone with a video inside which you can effortlessly swap out. Just as easily, you can change properties like the color, size, thickness, corner radius of the phone.++The template serves as an soft introduction on how to use `<ThreeCanvas />` and `useVideoTexture()`. You can easily delete everything inside the canvas to start working on a different idea.++## Installation++<Tabs+defaultValue="npm"+values={[+{ label: 'npm', value: 'npm', },+{ label: 'yarn', value: 'yarn', },+]+}>+<TabItem value="npm">++```bash+npm i three @react-three/fiber @remotion/three+```++ </TabItem>++ <TabItem value="yarn">++```bash+yarn add three @react-three/fiber @remotion/three+```++ </TabItem>+</Tabs>++You are now set up and can render a [`<ThreeCanvas />`](/docs/three-canvas) in your project.++## Thanks++Big thanks to [Björn Zeutzheim](https://github.com/olee) for researching and discovering the techniques needed for React Three Fiber integration and for doing the initial implementation of the @remotion/three APIs.diff --git a/packages/docs/package.json b/packages/docs/package.jsonindex 5dbd1b60de..ed1cf74e4a 100644--- a/packages/docs/package.json+++ b/packages/docs/package.json@@ -17,6 +17,8 @@"@docusaurus/preset-classic": "2.0.0-beta.0","@mdx-js/react": "^1.6.21","@remotion/player": "^2.1.6",+ "@remotion/media-utils": "^2.1.6",+ "@remotion/three": "^2.1.6","@splitbee/web": "^0.2.4","@types/color-namer": "^1.3.0","clsx": "^1.1.1",diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 48bd113e02..705d8e56e5 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -83,7 +83,7 @@ module.exports = {{type: "category",label: "API - @remotion/three",- items: ["three-canvas", "use-video-texture"],+ items: ["three", "three-canvas", "use-video-texture"],},{type: "category",