Visualize Your Ideas With Code
feat(2d): support tweening Line points (#853)
Jacob4bf37d74d2e4
diff --git a/packages/2d/src/components/Line.ts b/packages/2d/src/components/Line.tsindex 13bc693c..7f87e0ce 100644--- a/packages/2d/src/components/Line.ts+++ b/packages/2d/src/components/Line.ts@@ -1,4 +1,5 @@import {+ createSignal,SignalValue,SimpleSignal,unwrap,@@ -11,17 +12,237 @@ import {arc, drawLine, drawPivot, lineTo, moveTo} from '../utils';import {Curve, CurveProps} from './Curve';import {Layout} from './Layout';import lineWithoutPoints from './__logs__/line-without-points.md';+import {threadable} from '@motion-canvas/core/lib/decorators';+import {TimingFunction, tween} from '@motion-canvas/core/lib/tweening';+import {ThreadGenerator} from '@motion-canvas/core/lib/threading';+import {+ calculateLerpDistance,+ polygonLength,+ polygonPointsLerp,+} from '../curves/createCurveProfileLerp';export interface LineProps extends CurveProps {+ /**+ * {@inheritDoc Line.radius}+ */radius?: SignalValue<number>;+ /**+ * {@inheritDoc Line.points}+ */points?: SignalValue<SignalValue<PossibleVector2>[]>;}+/**+ * A node for drawing lines and polygons.+ *+ * @remarks+ * This node can be used to render any polygonal shape defined by a set of+ * points.+ *+ * @preview+ * ```tsx editor+ * // snippet Simple line+ * import {makeScene2D, Line} from '@motion-canvas/2d';+ *+ * export default makeScene2D(function* (view) {+ * view.add(+ * <Line+ * points={[+ * [150, 50],+ * [0, -50],+ * [-150, 50],+ * ]}+ * stroke={'lightseagreen'}+ * lineWidth={8}+ * radius={40}+ * startArrow+ * />,+ * );+ * });+ *+ * // snippet Polygon+ * import {makeScene2D, Line} from '@motion-canvas/2d';+ *+ * export default makeScene2D(function* (view) {+ * view.add(+ * <Line+ * points={[+ * [-200, 70],+ * [150, 70],+ * [100, -70],+ * [-100, -70],+ * ]}+ * fill={'lightseagreen'}+ * closed+ * />,+ * );+ * });+ *+ * // snippet Using signals+ * import {makeScene2D, Line} from '@motion-canvas/2d';+ * import {createSignal} from '@motion-canvas/core';+ *+ * export default makeScene2D(function* (view) {+ * const tip = createSignal(-150);+ * view.add(+ * <Line+ * points={[+ * [-150, 70],+ * [150, 70],+ * // this point is dynamically calculated based on the signal:+ * () => [tip(), -70],+ * ]}+ * stroke={'lightseagreen'}+ * lineWidth={8}+ * closed+ * />,+ * );+ *+ * yield* tip(150, 1).back(1);+ * });+ *+ * // snippet Tweening points+ * import {makeScene2D, Line} from '@motion-canvas/2d';+ * import {createRef} from '@motion-canvas/core';+ *+ * export default makeScene2D(function* (view) {+ * const line = createRef<Line>();+ * view.add(+ * <Line+ * ref={line}+ * points={[+ * [-150, 70],+ * [150, 70],+ * [0, -70],+ * ]}+ * stroke={'lightseagreen'}+ * lineWidth={8}+ * radius={20}+ * closed+ * />,+ * );+ *+ * yield* line()+ * .points(+ * [+ * [-150, 0],+ * [0, 100],+ * [150, 0],+ * [150, -70],+ * [-150, -70],+ * ],+ * 2,+ * )+ * .back(2);+ * });+ * ```+ */export class Line extends Curve {+ /**+ * Rotate the points to minimize the overall distance traveled when tweening.+ *+ * @param points - The points to rotate.+ * @param reference - The reference points to which the distance is measured.+ * @param closed - Whether the points form a closed polygon.+ */+ private static rotatePoints(+ points: Vector2[],+ reference: Vector2[],+ closed: boolean,+ ) {+ if (closed) {+ let minDistance = Infinity;+ let bestOffset = 0;+ for (let offset = 0; offset < points.length; offset += 1) {+ const distance = calculateLerpDistance(points, reference, offset);+ if (distance < minDistance) {+ minDistance = distance;+ bestOffset = offset;+ }+ }++ if (bestOffset) {+ const spliced = points.splice(0, bestOffset);+ points.splice(points.length, 0, ...spliced);+ }+ } else {+ const originalDistance = calculateLerpDistance(points, reference, 0);+ const reversedPoints = [...points].reverse();+ const reversedDistance = calculateLerpDistance(+ reversedPoints,+ reference,+ 0,+ );+ if (reversedDistance < originalDistance) {+ points.reverse();+ }+ }+ }++ /**+ * Distribute additional points along the polyline.+ *+ * @param points - The points of a polyline along which new points should be+ * distributed.+ * @param count - The number of points to add.+ */+ private static distributePoints(points: Vector2[], count: number) {+ if (points.length === 0) {+ for (let j = 0; j < count; j++) {+ points.push(Vector2.zero);+ }+ return;+ }++ if (points.length === 1) {+ const point = points[0];+ for (let j = 0; j < count; j++) {+ points.push(point);+ }+ return;+ }++ const desiredLength = points.length + count;+ const arcLength = polygonLength(points);+ let density = count / arcLength;++ let i = 0;+ while (points.length < desiredLength) {+ const pointsLeft = desiredLength - points.length;++ if (i + 1 >= points.length) {+ density = pointsLeft / arcLength;+ i = 0;+ continue;+ }++ const a = points[i];+ const b = points[i + 1];+ const length = a.sub(b).magnitude;+ const pointCount = Math.min(Math.round(length * density), pointsLeft) + 1;++ for (let j = 1; j < pointCount; j++) {+ points.splice(++i, 0, Vector2.lerp(a, b, j / pointCount));+ }++ i++;+ }+ }++ /**+ * The radius of the line's corners.+ */@initial(0)@signal()public declare readonly radius: SimpleSignal<number, this>;+ /**+ * The points of the line.+ *+ * @remarks+ * When set to `null`, the Line will use the positions of its children as+ * points.+ */@initial(null)@signal()public declare readonly points: SimpleSignal<@@ -29,6 +250,36 @@ export class Line extends Curve {this>;+ @threadable()+ protected *tweenPoints(+ value: SignalValue<SignalValue<PossibleVector2>[] | null>,+ time: number,+ timingFunction: TimingFunction,+ ): ThreadGenerator {+ const fromPoints = [...this.parsedPoints()];+ const toPoints = this.parsePoints(unwrap(value));+ const closed = this.closed();++ const diff = fromPoints.length - toPoints.length;+ Line.distributePoints(diff < 0 ? fromPoints : toPoints, Math.abs(diff));+ Line.rotatePoints(toPoints, fromPoints, closed);++ this.tweenedPoints(fromPoints);+ yield* tween(+ time,+ value => {+ const progress = timingFunction(value);+ this.tweenedPoints(polygonPointsLerp(fromPoints, toPoints, progress));+ },+ () => {+ this.tweenedPoints(null);+ this.points(value);+ },+ );+ }++ private tweenedPoints = createSignal<Vector2[] | null>(null);+public constructor(props: LineProps) {super(props);@@ -43,28 +294,28 @@ export class Line extends Curve {@computed()protected childrenBBox() {- const custom = this.points();- const points = custom- ? custom.map(signal => new Vector2(unwrap(signal)))- : this.children()- .filter(child => !(child instanceof Layout) || child.isLayoutRoot())- .map(child => child.position());+ let points = this.tweenedPoints();+ if (!points) {+ const custom = this.points();+ points = custom+ ? custom.map(signal => new Vector2(unwrap(signal)))+ : this.children()+ .filter(child => !(child instanceof Layout) || child.isLayoutRoot())+ .map(child => child.position());+ }return BBox.fromPoints(...points);}@computed()public parsedPoints(): Vector2[] {- const custom = this.points();- return custom- ? custom.map(signal => new Vector2(unwrap(signal)))- : this.children().map(child => child.position());+ return this.parsePoints(this.points());}@computed()- public profile(): CurveProfile {+ public override profile(): CurveProfile {return getPolylineProfile(- this.parsedPoints(),+ this.tweenedPoints() ?? this.parsedPoints(),this.radius(),this.closed(),);@@ -99,7 +350,7 @@ export class Line extends Curve {context.lineWidth = 1;const path = new Path2D();- const points = this.parsedPoints().map(point =>+ const points = (this.tweenedPoints() ?? this.parsedPoints()).map(point =>point.transformAsPoint(matrix),);if (points.length > 0) {@@ -126,4 +377,10 @@ export class Line extends Curve {context.closePath();context.stroke();}++ private parsePoints(points: SignalValue<PossibleVector2>[] | null) {+ return points+ ? points.map(signal => new Vector2(unwrap(signal)))+ : this.children().map(child => child.position());+ }}diff --git a/packages/2d/src/curves/createCurveProfileLerp.ts b/packages/2d/src/curves/createCurveProfileLerp.tsindex 1daaa58c..4d1df4e5 100644--- a/packages/2d/src/curves/createCurveProfileLerp.ts+++ b/packages/2d/src/curves/createCurveProfileLerp.ts@@ -187,7 +187,7 @@ function subcurveToPolygon(* @returns - perimeter of polygon*/-function polygonLength(points: Vector2[]) {+export function polygonLength(points: Vector2[]) {return points.reduce((length, point, i) => {if (i) return length + points[i - 1].sub(point).magnitude;return 0;@@ -237,7 +237,7 @@ function addPoints(points: Vector2[], numPoints: number) {* @returns*/-function calculateLerpDistance(+export function calculateLerpDistance(points: Vector2[],reference: Vector2[],offset: number,@@ -429,7 +429,7 @@ function addCurveToCurve(target: CurveProfile, source: CurveProfile) {* @returns - new polygon points*/-function polygonPointsLerp(+export function polygonPointsLerp(from: Vector2[],to: Vector2[],value: number,diff --git a/packages/2d/src/curves/getPolylineProfile.ts b/packages/2d/src/curves/getPolylineProfile.tsindex 7dc70e19..bc91bd29 100644--- a/packages/2d/src/curves/getPolylineProfile.ts+++ b/packages/2d/src/curves/getPolylineProfile.ts@@ -5,7 +5,7 @@ import {CircleSegment} from './CircleSegment';import {clamp} from '@motion-canvas/core/lib/tweening';export function getPolylineProfile(- points: Vector2[],+ points: readonly Vector2[],radius: number,closed: boolean,): CurveProfile {@@ -21,8 +21,7 @@ export function getPolylineProfile(if (closed) {const middle = points[0].add(points[points.length - 1]).scale(0.5);- points.unshift(middle);- points.push(middle);+ points = [middle, ...points, middle];}let last = points[0];diff --git a/packages/docs/src/components/Fiddle/index.tsx b/packages/docs/src/components/Fiddle/index.tsxindex 3eeee346..6ddb6a67 100644--- a/packages/docs/src/components/Fiddle/index.tsx+++ b/packages/docs/src/components/Fiddle/index.tsx@@ -281,7 +281,12 @@ export default function Fiddle({</button>)}</div>- <div className={styles.section}>+ <div+ className={clsx(+ styles.section,+ duration === 0 && player && styles.disabled,+ )}+ ><buttonclassName={styles.icon}onClick={() => player?.requestPreviousFrame()}diff --git a/packages/docs/src/components/Fiddle/styles.module.css b/packages/docs/src/components/Fiddle/styles.module.cssindex 708dfcb4..6c46d247 100644--- a/packages/docs/src/components/Fiddle/styles.module.css+++ b/packages/docs/src/components/Fiddle/styles.module.css@@ -59,6 +59,11 @@padding: 8px;}+.section.disabled {+ opacity: 0.5;+ pointer-events: none;+}+.section:first-child {flex-basis: 100%;justify-content: start;