Skip to content

Visualize Your Ideas With Code

refactor(2d): extract curve base component (#594)

Kai Sassnowskid1f2ff2930fb
diff --git a/packages/2d/src/components/Curve.ts b/packages/2d/src/components/Curve.ts
new file mode 100644
index 00000000..bc2eceae
--- /dev/null
+++ b/packages/2d/src/components/Curve.ts
@@ -0,0 +1,233 @@
+import {SignalValue, SimpleSignal} from '@motion-canvas/core/lib/signals';
+import {clamp} from '@motion-canvas/core/lib/tweening';
+import {BBox, SerializedVector2, Vector2} from '@motion-canvas/core/lib/types';
+import {
+ CurveDrawingInfo,
+ CurvePoint,
+ CurveProfile,
+ getPointAtDistance,
+} from '../curves';
+import {computed, initial, signal} from '../decorators';
+import {DesiredLength} from '../partials';
+import {lineTo, moveTo, resolveCanvasStyle} from '../utils';
+import {Node} from './Node';
+import {Shape, ShapeProps} from './Shape';
+
+export interface CurveProps extends ShapeProps {
+ children?: Node[];
+ closed?: SignalValue<boolean>;
+ start?: SignalValue<number>;
+ startOffset?: SignalValue<number>;
+ startArrow?: SignalValue<boolean>;
+ end?: SignalValue<number>;
+ endOffset?: SignalValue<number>;
+ endArrow?: SignalValue<boolean>;
+ arrowSize?: SignalValue<number>;
+}
+
+export abstract class Curve extends Shape {
+ @initial(false)
+ @signal()
+ public declare readonly closed: SimpleSignal<boolean, this>;
+
+ @initial(0)
+ @signal()
+ public declare readonly start: SimpleSignal<number, this>;
+
+ @initial(0)
+ @signal()
+ public declare readonly startOffset: SimpleSignal<number, this>;
+
+ @initial(false)
+ @signal()
+ public declare readonly startArrow: SimpleSignal<boolean, this>;
+
+ @initial(1)
+ @signal()
+ public declare readonly end: SimpleSignal<number, this>;
+
+ @initial(0)
+ @signal()
+ public declare readonly endOffset: SimpleSignal<number, this>;
+
+ @initial(false)
+ @signal()
+ public declare readonly endArrow: SimpleSignal<boolean, this>;
+
+ @initial(24)
+ @signal()
+ public declare readonly arrowSize: SimpleSignal<number, this>;
+
+ protected override desiredSize(): SerializedVector2<DesiredLength> {
+ return this.childrenBBox().size;
+ }
+
+ public constructor(props: CurveProps) {
+ super(props);
+ }
+
+ protected abstract childrenBBox(): BBox;
+
+ public abstract profile(): CurveProfile;
+
+ public percentageToDistance(value: number): number {
+ const {arcLength} = this.profile();
+ const startOffset = this.startOffset();
+ const endOffset = this.endOffset();
+ const realLength = arcLength - startOffset - endOffset;
+ return startOffset + realLength * value;
+ }
+
+ @computed()
+ protected curveDrawingInfo(): CurveDrawingInfo {
+ const path = new Path2D();
+ const profile = this.profile();
+
+ let start = this.percentageToDistance(this.start());
+ let end = this.percentageToDistance(this.end());
+ if (start > end) {
+ [start, end] = [end, start];
+ }
+
+ const distance = end - start;
+ const arrowSize = Math.min(distance / 2, this.arrowSize());
+
+ if (this.startArrow()) {
+ start += arrowSize / 2;
+ }
+
+ if (this.endArrow()) {
+ end -= arrowSize / 2;
+ }
+
+ let length = 0;
+ let startPoint = null;
+ let startTangent = null;
+ let endPoint = null;
+ let endTangent = null;
+ for (const segment of profile.segments) {
+ const previousLength = length;
+ length += segment.arcLength;
+ if (length < start) {
+ continue;
+ }
+
+ const relativeStart = (start - previousLength) / segment.arcLength;
+ const relativeEnd = (end - previousLength) / segment.arcLength;
+
+ const clampedStart = clamp(0, 1, relativeStart);
+ const clampedEnd = clamp(0, 1, relativeEnd);
+
+ const [
+ currentStartPoint,
+ currentStartTangent,
+ currentEndPoint,
+ currentEndTangent,
+ ] = segment.draw(path, clampedStart, clampedEnd, startPoint === null);
+
+ if (startPoint === null) {
+ startPoint = currentStartPoint;
+ startTangent = currentStartTangent;
+ }
+
+ endPoint = currentEndPoint;
+ endTangent = currentEndTangent;
+ if (length > end) {
+ break;
+ }
+ }
+
+ if (this.end() === 1 && this.closed()) {
+ path.closePath();
+ }
+
+ return {
+ startPoint: startPoint ?? Vector2.zero,
+ startTangent: startTangent ?? Vector2.up,
+ endPoint: endPoint ?? Vector2.zero,
+ endTangent: endTangent ?? Vector2.up,
+ arrowSize,
+ path,
+ startOffset: start,
+ };
+ }
+
+ protected getPointAtDistance(value: number): CurvePoint {
+ return getPointAtDistance(this.profile(), value + this.startOffset());
+ }
+
+ public getPointAtPercentage(value: number): CurvePoint {
+ return getPointAtDistance(this.profile(), this.percentageToDistance(value));
+ }
+
+ protected override applyStyle(context: CanvasRenderingContext2D) {
+ super.applyStyle(context);
+ const {arcLength} = this.profile();
+ context.lineDashOffset -= arcLength / 2;
+ }
+
+ protected override getComputedLayout(): BBox {
+ return this.offsetComputedLayout(super.getComputedLayout());
+ }
+
+ protected offsetComputedLayout(box: BBox): BBox {
+ box.position = box.position.sub(this.childrenBBox().center);
+ return box;
+ }
+
+ protected override getPath(): Path2D {
+ return this.curveDrawingInfo().path;
+ }
+
+ protected override getCacheBBox(): BBox {
+ const box = this.childrenBBox();
+ const arrowSize = this.arrowSize();
+ const lineWidth = this.lineWidth();
+
+ const coefficient = this.lineWidthCoefficient();
+
+ return box.expand(Math.max(0, arrowSize, lineWidth * coefficient));
+ }
+
+ protected lineWidthCoefficient(): number {
+ return this.lineCap() === 'square' ? 0.5 * 1.4143 : 0.5;
+ }
+
+ protected override drawShape(context: CanvasRenderingContext2D) {
+ super.drawShape(context);
+ const {startPoint, startTangent, endPoint, endTangent, arrowSize} =
+ this.curveDrawingInfo();
+ if (arrowSize < 0.001) {
+ return;
+ }
+
+ context.save();
+ context.beginPath();
+ if (this.endArrow()) {
+ this.drawArrow(context, endPoint, endTangent, arrowSize);
+ }
+ if (this.startArrow()) {
+ this.drawArrow(context, startPoint, startTangent, arrowSize);
+ }
+ context.fillStyle = resolveCanvasStyle(this.stroke(), context);
+ context.closePath();
+ context.fill();
+ context.restore();
+ }
+
+ private drawArrow(
+ context: CanvasRenderingContext2D | Path2D,
+ center: Vector2,
+ tangent: Vector2,
+ arrowSize: number,
+ ) {
+ const normal = tangent.perpendicular;
+ const origin = center.add(normal.scale(-arrowSize / 2));
+
+ moveTo(context, origin);
+ lineTo(context, origin.add(normal.add(tangent).scale(arrowSize)));
+ lineTo(context, origin.add(normal.sub(tangent).scale(arrowSize)));
+ lineTo(context, origin);
+ context.closePath();
+ }
+}
diff --git a/packages/2d/src/components/Line.ts b/packages/2d/src/components/Line.ts
index 0936e87f..517d377c 100644
--- a/packages/2d/src/components/Line.ts
+++ b/packages/2d/src/components/Line.ts
@@ -1,82 +1,27 @@
-import {Shape, ShapeProps} from './Shape';
-import {Node} from './Node';
-import {computed, initial, signal} from '../decorators';
-import {arc, drawLine, lineTo, moveTo, resolveCanvasStyle} from '../utils';
import {
isReactive,
SignalValue,
SimpleSignal,
} from '@motion-canvas/core/lib/signals';
-import {
- PossibleVector2,
- BBox,
- SerializedVector2,
- Vector2,
-} from '@motion-canvas/core/lib/types';
-import {clamp} from '@motion-canvas/core/lib/tweening';
-import {DesiredLength} from '../partials';
-import {Layout} from './Layout';
-import {
- CurveDrawingInfo,
- CurvePoint,
- CurveProfile,
- getPointAtDistance,
- getPolylineProfile,
-} from '../curves';
+import {BBox, PossibleVector2, Vector2} from '@motion-canvas/core/lib/types';
import {useLogger} from '@motion-canvas/core/lib/utils';
+import {CurveProfile, getPolylineProfile} from '../curves';
+import {computed, initial, signal} from '../decorators';
+import {arc, drawLine, lineTo, moveTo} from '../utils';
+import {Curve, CurveProps} from './Curve';
+import {Layout} from './Layout';
import lineWithoutPoints from './__logs__/line-without-points.md';
-export interface LineProps extends ShapeProps {
- children?: Node[];
- closed?: SignalValue<boolean>;
+export interface LineProps extends CurveProps {
radius?: SignalValue<number>;
- start?: SignalValue<number>;
- startOffset?: SignalValue<number>;
- startArrow?: SignalValue<boolean>;
- end?: SignalValue<number>;
- endOffset?: SignalValue<number>;
- endArrow?: SignalValue<boolean>;
- arrowSize?: SignalValue<number>;
points?: SignalValue<SignalValue<PossibleVector2>[]>;
}
-export class Line extends Shape {
+export class Line extends Curve {
@initial(0)
@signal()
public declare readonly radius: SimpleSignal<number, this>;
- @initial(false)
- @signal()
- public declare readonly closed: SimpleSignal<boolean, this>;
-
- @initial(0)
- @signal()
- public declare readonly start: SimpleSignal<number, this>;
-
- @initial(0)
- @signal()
- public declare readonly startOffset: SimpleSignal<number, this>;
-
- @initial(false)
- @signal()
- public declare readonly startArrow: SimpleSignal<boolean, this>;
-
- @initial(1)
- @signal()
- public declare readonly end: SimpleSignal<number, this>;
-
- @initial(0)
- @signal()
- public declare readonly endOffset: SimpleSignal<number, this>;
-
- @initial(false)
- @signal()
- public declare readonly endArrow: SimpleSignal<boolean, this>;
-
- @initial(24)
- @signal()
- public declare readonly arrowSize: SimpleSignal<number, this>;
-
@initial(null)
@signal()
public declare readonly points: SimpleSignal<
@@ -84,13 +29,16 @@ export class Line extends Shape {
this
>;
- protected override desiredSize(): SerializedVector2<DesiredLength> {
- return this.childrenBBox().size;
- }
-
public constructor(props: LineProps) {
super(props);
- this.validateProps(props);
+
+ if (props.children === undefined && props.points === undefined) {
+ useLogger().warn({
+ message: 'No points specified for the line',
+ remarks: lineWithoutPoints,
+ inspect: this.key,
+ });
+ }
}
@computed()
@@ -126,183 +74,20 @@ export class Line extends Shape {
);
}
- public percentageToDistance(value: number): number {
- const {arcLength} = this.profile();
- const startOffset = this.startOffset();
- const endOffset = this.endOffset();
- const realLength = arcLength - startOffset - endOffset;
- return startOffset + realLength * value;
- }
-
- @computed()
- protected curveDrawingInfo(): CurveDrawingInfo {
- const path = new Path2D();
- const profile = this.profile();
-
- let start = this.percentageToDistance(this.start());
- let end = this.percentageToDistance(this.end());
- if (start > end) {
- [start, end] = [end, start];
- }
-
- const distance = end - start;
- const arrowSize = Math.min(distance / 2, this.arrowSize());
-
- if (this.startArrow()) {
- start += arrowSize / 2;
- }
-
- if (this.endArrow()) {
- end -= arrowSize / 2;
- }
-
- let length = 0;
- let startPoint = null;
- let startTangent = null;
- let endPoint = null;
- let endTangent = null;
- for (const segment of profile.segments) {
- const previousLength = length;
- length += segment.arcLength;
- if (length < start) {
- continue;
- }
-
- const relativeStart = (start - previousLength) / segment.arcLength;
- const relativeEnd = (end - previousLength) / segment.arcLength;
-
- const clampedStart = clamp(0, 1, relativeStart);
- const clampedEnd = clamp(0, 1, relativeEnd);
-
- const [
- currentStartPoint,
- currentStartTangent,
- currentEndPoint,
- currentEndTangent,
- ] = segment.draw(path, clampedStart, clampedEnd, startPoint === null);
-
- if (startPoint === null) {
- startPoint = currentStartPoint;
- startTangent = currentStartTangent;
- }
-
- endPoint = currentEndPoint;
- endTangent = currentEndTangent;
- if (length > end) {
- break;
- }
- }
-
- if (this.end() === 1 && this.closed()) {
- path.closePath();
- }
-
- return {
- startPoint: startPoint ?? Vector2.zero,
- startTangent: startTangent ?? Vector2.up,
- endPoint: endPoint ?? Vector2.zero,
- endTangent: endTangent ?? Vector2.up,
- arrowSize,
- path,
- startOffset: start,
- };
- }
-
- protected getPointAtDistance(value: number): CurvePoint {
- return getPointAtDistance(this.profile(), value + this.startOffset());
- }
-
- public getPointAtPercentage(value: number): CurvePoint {
- return getPointAtDistance(this.profile(), this.percentageToDistance(value));
- }
-
- protected override applyStyle(context: CanvasRenderingContext2D) {
- super.applyStyle(context);
- const {arcLength} = this.profile();
- context.lineDashOffset -= arcLength / 2;
- }
-
- protected override getComputedLayout(): BBox {
- return this.offsetComputedLayout(super.getComputedLayout());
- }
-
- protected offsetComputedLayout(box: BBox): BBox {
- box.position = box.position.sub(this.childrenBBox().center);
- return box;
- }
-
- protected validateProps(props: LineProps) {
- if (props.children === undefined && props.points === undefined) {
- useLogger().warn({
- message: 'No points specified for the line',
- remarks: lineWithoutPoints,
- inspect: this.key,
- });
- }
- }
-
- protected override getPath(): Path2D {
- return this.curveDrawingInfo().path;
- }
-
- protected override getCacheBBox(): BBox {
- const box = this.childrenBBox();
- const arrowSize = this.arrowSize();
- const lineWidth = this.lineWidth();
+ protected override lineWidthCoefficient(): number {
const radius = this.radius();
const join = this.lineJoin();
- const cap = this.lineCap();
- let coefficient = 0.5;
+ let coefficient = super.lineWidthCoefficient();
+
if (radius === 0 && join === 'miter') {
const {minSin} = this.profile();
if (minSin > 0) {
coefficient = Math.max(coefficient, 0.5 / minSin);
}
}
- if (cap === 'square') {
- coefficient = Math.max(coefficient, 0.5 * 1.4143);
- }
-
- return box.expand(Math.max(0, arrowSize, lineWidth * coefficient));
- }
-
- protected override drawShape(context: CanvasRenderingContext2D) {
- super.drawShape(context);
- const {startPoint, startTangent, endPoint, endTangent, arrowSize} =
- this.curveDrawingInfo();
- if (arrowSize < 0.001) {
- return;
- }
-
- context.save();
- context.beginPath();
- if (this.endArrow()) {
- this.drawArrow(context, endPoint, endTangent, arrowSize);
- }
- if (this.startArrow()) {
- this.drawArrow(context, startPoint, startTangent, arrowSize);
- }
- context.fillStyle = resolveCanvasStyle(this.stroke(), context);
- context.closePath();
- context.fill();
- context.restore();
- }
- private drawArrow(
- context: CanvasRenderingContext2D | Path2D,
- center: Vector2,
- tangent: Vector2,
- arrowSize: number,
- ) {
- const normal = tangent.perpendicular;
- const origin = center.add(normal.scale(-arrowSize / 2));
-
- moveTo(context, origin);
- lineTo(context, origin.add(normal.add(tangent).scale(arrowSize)));
- lineTo(context, origin.add(normal.sub(tangent).scale(arrowSize)));
- lineTo(context, origin);
- context.closePath();
+ return coefficient;
}
public override drawOverlay(
diff --git a/packages/2d/src/components/Spline.ts b/packages/2d/src/components/Spline.ts
index d863d6c5..42861a9c 100644
--- a/packages/2d/src/components/Spline.ts
+++ b/packages/2d/src/components/Spline.ts
@@ -1,14 +1,24 @@
-import {SignalValue, SimpleSignal} from '@motion-canvas/core/lib/signals';
+import {
+ isReactive,
+ SignalValue,
+ SimpleSignal,
+} from '@motion-canvas/core/lib/signals';
+import {
+ BBox,
+ PossibleVector2,
+ SerializedVector2,
+ Vector2,
+} from '@motion-canvas/core/lib/types';
import {useLogger} from '@motion-canvas/core/lib/utils';
-import {Line, LineProps} from './Line';
-import {Node} from './Node';
import {
CubicBezierSegment,
CurveProfile,
getBezierSplineProfile,
KnotInfo,
} from '../curves';
+import {PolynomialSegment} from '../curves/PolynomialSegment';
import {computed, initial, signal} from '../decorators';
+import {DesiredLength} from '../partials';
import {
arc,
bezierCurveTo,
@@ -17,17 +27,21 @@ import {
moveTo,
quadraticCurveTo,
} from '../utils';
+import {Curve, CurveProps} from './Curve';
import {Knot} from './Knot';
-import {BBox, SerializedVector2, Vector2} from '@motion-canvas/core/lib/types';
-import {DesiredLength} from '../partials';
+import {Node} from './Node';
import splineWithInsufficientKnots from './__logs__/spline-with-insufficient-knots.md';
-import {PolynomialSegment} from '../curves/PolynomialSegment';
-export interface SplineProps extends LineProps {
+export interface SplineProps extends CurveProps {
/**
* {@inheritDoc Spline.smoothness}
*/
smoothness?: SignalValue<number>;
+
+ /**
+ * {@inheritDoc Spline.points}
+ */
+ points?: SignalValue<SignalValue<PossibleVector2[]>>;
}
/**
@@ -73,7 +87,7 @@ export interface SplineProps extends LineProps {
* </Spline>
* ```
*/
-export class Spline extends Line {
+export class Spline extends Curve {
/**
* Determine the smoothness of the spline when using auto-calculated handles.
*
@@ -86,10 +100,31 @@ export class Spline extends Line {
@signal()
public declare readonly smoothness: SimpleSignal<number>;
+ @initial(null)
+ @signal()
+ public declare readonly points: SimpleSignal<
+ SignalValue<PossibleVector2>[] | null,
+ this
+ >;
+
public constructor(props: SplineProps) {
super(props);
+
+ if (
+ (props.children === undefined || props.children.length < 2) &&
+ (props.points === undefined || props.points.length < 2) &&
+ props.spawner === undefined
+ ) {
+ useLogger().warn({
+ message:
+ 'Insufficient number of knots specified for spline. A spline needs at least two knots.',
+ remarks: splineWithInsufficientKnots,
+ inspect: this.key,
+ });
+ }
}
+ @computed()
public override profile(): CurveProfile {
return getBezierSplineProfile(
this.knots(),
@@ -100,13 +135,19 @@ export class Spline extends Line {
@computed()
public knots(): KnotInfo[] {
- if (this.points()) {
- return this.parsedPoints().map(point => ({
- position: point,
- startHandle: point,
- endHandle: point,
- auto: {start: 1, end: 1},
- }));
+ const points = this.points();
+
+ if (points) {
+ return points.map(signal => {
+ const point = new Vector2(isReactive(signal) ? signal() : signal);
+
+ return {
+ position: point,
+ startHandle: point,
+ endHandle: point,
+ auto: {start: 1, end: 1},
+ };
+ });
}
return this.children()
@@ -114,26 +155,29 @@ export class Spline extends Line {
.map(knot => knot.points());
}
- protected override childrenBBox() {
+ @computed()
+ protected childrenBBox() {
const points = (this.profile().segments as PolynomialSegment[]).flatMap(
segment => segment.points,
);
return BBox.fromPoints(...points);
}
- protected override validateProps(props: SplineProps) {
- if (
- (props.children === undefined || props.children.length < 2) &&
- (props.points === undefined || props.points.length < 2) &&
- props.spawner === undefined
- ) {
- useLogger().warn({
- message:
- 'Insufficient number of knots specified for spline. A spline needs at least two knots.',
- remarks: splineWithInsufficientKnots,
- inspect: this.key,
- });
+ protected override lineWidthCoefficient(): number {
+ const join = this.lineJoin();
+
+ let coefficient = super.lineWidthCoefficient();
+
+ if (join !== 'miter') {
+ return coefficient;
}
+
+ const {minSin} = this.profile();
+ if (minSin > 0) {
+ coefficient = Math.max(coefficient, 0.5 / minSin);
+ }
+
+ return coefficient;
}
protected override desiredSize(): SerializedVector2<DesiredLength> {