-
-
Notifications
You must be signed in to change notification settings - Fork 574
/
Spline.ts
318 lines (281 loc) · 7.82 KB
/
Spline.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import {
BBox,
PossibleVector2,
SerializedVector2,
SignalValue,
SimpleSignal,
Vector2,
unwrap,
useLogger,
} from '@motion-canvas/core';
import {
CubicBezierSegment,
CurveProfile,
KnotInfo,
getBezierSplineProfile,
} from '../curves';
import {PolynomialSegment} from '../curves/PolynomialSegment';
import {computed, initial, signal} from '../decorators';
import {DesiredLength} from '../partials';
import {
arc,
bezierCurveTo,
drawLine,
drawPivot,
lineTo,
moveTo,
quadraticCurveTo,
} from '../utils';
import {Curve, CurveProps} from './Curve';
import {Knot} from './Knot';
import {Node} from './Node';
import splineWithInsufficientKnots from './__logs__/spline-with-insufficient-knots.md';
export interface SplineProps extends CurveProps {
/**
* {@inheritDoc Spline.smoothness}
*/
smoothness?: SignalValue<number>;
/**
* {@inheritDoc Spline.points}
*/
points?: SignalValue<SignalValue<PossibleVector2[]>>;
}
/**
* A node for drawing a smooth line through a number of points.
*
* @remarks
* This node uses Bézier curves for drawing each segment of the spline.
*
* @example
* Defining knots using the `points` property. This will automatically
* calculate the handle positions for each knot do draw a smooth curve. You
* can control the smoothness of the resulting curve via the
* {@link Spline.smoothness} property:
*
* ```tsx
* <Spline
* lineWidth={4}
* stroke={'white'}
* smoothness={0.4}
* points={[
* [-400, 0],
* [-200, -300],
* [0, 0],
* [200, -300],
* [400, 0],
* ]}
* />
* ```
*
* Defining knots with {@link Knot} nodes:
*
* ```tsx
* <Spline lineWidth={4} stroke={'white'}>
* <Knot position={[-400, 0]} />
* <Knot position={[-200, -300]} />
* <Knot
* position={[0, 0]}
* startHandle={[-100, 200]}
* endHandle={[100, 200]}
* />
* <Knot position={[200, -300]} />
* <Knot position={[400, 0]} />
* </Spline>
* ```
*/
export class Spline extends Curve {
/**
* The smoothness of the spline when using auto-calculated handles.
*
* @remarks
* This property is only applied to knots that don't use explicit handles.
*
* @defaultValue 0.4
*/
@initial(0.4)
@signal()
public declare readonly smoothness: SimpleSignal<number>;
/**
* The knots of the spline as an array of knots with auto-calculated handles.
*
* @remarks
* You can control the smoothness of the resulting curve
* via the {@link smoothness} property.
*/
@initial(null)
@signal()
public declare readonly points: SimpleSignal<
SignalValue<PossibleVector2>[] | null,
this
>;
public constructor(props: SplineProps) {
super(props);
if (
(props.children === undefined ||
!Array.isArray(props.children) ||
props.children.length < 2) &&
(props.points === undefined ||
(typeof props.points !== 'function' && 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(),
this.closed(),
this.smoothness(),
);
}
@computed()
public knots(): KnotInfo[] {
const points = this.points();
if (points) {
return points.map(signal => {
const point = new Vector2(unwrap(signal));
return {
position: point,
startHandle: point,
endHandle: point,
auto: {start: 1, end: 1},
};
});
}
return this.children()
.filter(this.isKnot)
.map(knot => knot.points());
}
@computed()
protected childrenBBox() {
const points = (this.profile().segments as PolynomialSegment[]).flatMap(
segment => segment.points,
);
return BBox.fromPoints(...points);
}
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> {
return this.getTightBBox().size;
}
protected override offsetComputedLayout(box: BBox): BBox {
box.position = box.position.sub(this.getTightBBox().center);
return box;
}
@computed()
private getTightBBox(): BBox {
const bounds = (this.profile().segments as PolynomialSegment[]).map(
segment => segment.getBBox(),
);
return BBox.fromBBoxes(...bounds);
}
public override drawOverlay(
context: CanvasRenderingContext2D,
matrix: DOMMatrix,
) {
const size = this.computedSize();
const box = this.childrenBBox().transformCorners(matrix);
const offset = size.mul(this.offset()).scale(0.5).transformAsPoint(matrix);
const segments = this.profile().segments as PolynomialSegment[];
context.lineWidth = 1;
context.strokeStyle = 'white';
context.fillStyle = 'white';
const splinePath = new Path2D();
// Draw the actual spline first so that all control points get drawn on top of it.
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
const [from, startHandle, endHandle, to] =
segment.transformPoints(matrix);
moveTo(splinePath, from);
if (segment instanceof CubicBezierSegment) {
bezierCurveTo(splinePath, startHandle, endHandle, to as Vector2);
} else {
quadraticCurveTo(splinePath, startHandle, endHandle);
}
}
context.stroke(splinePath);
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
context.fillStyle = 'white';
const [from, startHandle, endHandle, to] =
segment.transformPoints(matrix);
const handlePath = new Path2D();
context.globalAlpha = 0.5;
// Line from p0 to p1
moveTo(handlePath, from);
lineTo(handlePath, startHandle);
if (segment instanceof CubicBezierSegment) {
// Line from p2 to p3
moveTo(handlePath, endHandle);
lineTo(handlePath, to as Vector2);
context.beginPath();
context.stroke(handlePath);
} else {
// Line from p1 to p2
lineTo(handlePath, endHandle);
context.beginPath();
context.stroke(handlePath);
}
context.globalAlpha = 1;
context.lineWidth = 2;
// Draw first point of segment
moveTo(context, from);
context.beginPath();
arc(context, from, 4);
context.closePath();
context.stroke();
context.fill();
// Draw final point of segment only if we're on the last segment.
// Otherwise, it will get drawn as the start point of the next segment.
if (i === segments.length - 1) {
if (to !== undefined) {
moveTo(context, to);
context.beginPath();
arc(context, to, 4);
context.closePath();
context.stroke();
context.fill();
}
}
// Draw the control points
context.fillStyle = 'black';
for (const point of [startHandle, endHandle]) {
if (point.magnitude > 0) {
moveTo(context, point);
context.beginPath();
arc(context, point, 4);
context.closePath();
context.fill();
context.stroke();
}
}
}
context.lineWidth = 1;
context.beginPath();
drawPivot(context, offset);
context.stroke();
context.beginPath();
drawLine(context, box);
context.closePath();
context.stroke();
}
private isKnot(node: Node): node is Knot {
return node instanceof Knot;
}
}