@beff/aula 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +8 -2
  2. package/dist/animations.d.ts +634 -0
  3. package/dist/animations.js +1793 -0
  4. package/dist/braces.d.ts +84 -0
  5. package/dist/braces.js +253 -0
  6. package/dist/card.d.ts +17 -0
  7. package/dist/card.js +90 -0
  8. package/dist/colors-palette.d.ts +2242 -0
  9. package/dist/colors-palette.js +2241 -0
  10. package/dist/colors.d.ts +120 -0
  11. package/dist/colors.js +403 -0
  12. package/dist/curves.d.ts +10 -0
  13. package/dist/curves.js +128 -0
  14. package/dist/engine.d.ts +1595 -0
  15. package/dist/engine.js +3364 -0
  16. package/dist/errors.d.ts +19 -0
  17. package/dist/errors.js +25 -0
  18. package/dist/generated/aula.conditional-suspending-3-i32-to-void.wasm +0 -0
  19. package/dist/generated/aula.core.wasm +0 -0
  20. package/dist/generated/aula.core2.wasm +0 -0
  21. package/dist/generated/aula.core3.wasm +0 -0
  22. package/dist/generated/aula.core4.wasm +0 -0
  23. package/dist/generated/aula.core5.wasm +0 -0
  24. package/dist/generated/aula.core6.wasm +0 -0
  25. package/dist/generated/aula.core7.wasm +0 -0
  26. package/dist/generated/aula.core8.wasm +0 -0
  27. package/dist/generated/aula.d.ts +80 -0
  28. package/dist/generated/aula.js +54639 -0
  29. package/dist/generated/interfaces/aula-engine-engine.d.ts +983 -0
  30. package/dist/generated/interfaces/aula-engine-host.d.ts +10 -0
  31. package/dist/generated/interfaces/aula-engine-tts.d.ts +43 -0
  32. package/dist/generated/interfaces/aula-engine-types.d.ts +60 -0
  33. package/dist/geometry.d.ts +551 -0
  34. package/dist/geometry.js +1821 -0
  35. package/dist/graph.d.ts +117 -0
  36. package/dist/graph.js +526 -0
  37. package/dist/graphing.d.ts +597 -0
  38. package/dist/graphing.js +1504 -0
  39. package/dist/host.d.ts +19 -0
  40. package/dist/host.js +85 -0
  41. package/dist/index.d.ts +5 -0
  42. package/dist/index.js +11 -0
  43. package/dist/licenses/aula-g2p-NOTICE.txt +13 -0
  44. package/dist/licenses/espeak-ng-COPYING.txt +674 -0
  45. package/dist/licenses/fonts-OFL-JetBrainsMono.txt +93 -0
  46. package/dist/licenses/fonts-OFL-NunitoSans.txt +93 -0
  47. package/dist/load.d.ts +16 -0
  48. package/dist/load.js +69 -0
  49. package/dist/logo.d.ts +30 -0
  50. package/dist/logo.js +186 -0
  51. package/dist/manim.d.ts +22 -0
  52. package/dist/manim.js +19 -0
  53. package/dist/mobjects.d.ts +127 -0
  54. package/dist/mobjects.js +316 -0
  55. package/dist/pointcloud.d.ts +144 -0
  56. package/dist/pointcloud.js +400 -0
  57. package/dist/rates.d.ts +19 -0
  58. package/dist/rates.js +54 -0
  59. package/dist/run.d.ts +82 -0
  60. package/dist/run.js +245 -0
  61. package/dist/tables.d.ts +179 -0
  62. package/dist/tables.js +403 -0
  63. package/dist/tex.d.ts +8 -0
  64. package/dist/tex.js +257 -0
  65. package/dist/text-layouts.d.ts +64 -0
  66. package/dist/text-layouts.js +225 -0
  67. package/dist/text.d.ts +35 -0
  68. package/dist/text.js +52 -0
  69. package/dist/theme.d.ts +25 -0
  70. package/dist/theme.js +12 -0
  71. package/dist/user-code.d.ts +5 -0
  72. package/dist/user-code.js +20 -0
  73. package/dist/utils.d.ts +152 -0
  74. package/dist/utils.js +517 -0
  75. package/dist/vector-field.d.ts +132 -0
  76. package/dist/vector-field.js +361 -0
  77. package/package.json +45 -3
@@ -0,0 +1,1821 @@
1
+ // Manim CE's geometry in `m`: the modules `geometry.arc`, `.line`, `.polygram`, `.tips`,
2
+ // `.labeled`, `.shape_matchers` and `.boolean_ops`, and `graphing.functions`. The shapes are
3
+ // engine nodes; the classes add CE's methods. The tips, the arcs from points, the boolean
4
+ // operations and the function graphs make their points here, in TypeScript.
5
+ import { BLUE, RED } from "./colors-palette.js";
6
+ import { engine } from "./load.js";
7
+ import { BLACK, DEGREES, DOWN, FRAME_HEIGHT, FRAME_WIDTH, LEFT, MED_SMALL_BUFF, MathTex, Mobject, ORIGIN, PI, RIGHT, SMALL_BUFF, TAU, UP, VGroup, WHITE, PURE_YELLOW, add, circleFrames, lerp, mul, norm, flatPoints, raw, split, styled, sub, wrap, wrong, } from "./engine.js";
8
+ // --- point helpers ---------------------------------------------------------------------
9
+ function clip01(x) {
10
+ return Math.max(0, Math.min(1, x));
11
+ }
12
+ function dot(a, b) {
13
+ return a[0] * b[0] + a[1] * b[1];
14
+ }
15
+ function cross(a, b) {
16
+ return a[0] * b[1] - a[1] * b[0];
17
+ }
18
+ function angleOf(v) {
19
+ return Math.atan2(v[1], v[0]);
20
+ }
21
+ function unit(v) {
22
+ const n = norm(v);
23
+ return n === 0 ? [0, 0] : mul(v, 1 / n);
24
+ }
25
+ function rotated(v, angle) {
26
+ const [c, s] = [Math.cos(angle), Math.sin(angle)];
27
+ return [v[0] * c - v[1] * s, v[0] * s + v[1] * c];
28
+ }
29
+ function same(a, b, tolerance = 1e-9) {
30
+ return norm(sub(a, b)) <= tolerance;
31
+ }
32
+ /** A straight curve from `a` to `b`, with its handles at the thirds (Manim's corners). */
33
+ function straight(a, b) {
34
+ return [a, lerp(a, b, 1 / 3), lerp(a, b, 2 / 3), b];
35
+ }
36
+ /** The control points of straight pieces through `vertices` (Manim `set_points_as_corners`). */
37
+ function corners(vertices) {
38
+ return vertices.slice(1).flatMap((v, i) => straight(vertices[i] ?? v, v));
39
+ }
40
+ function cubics(controlPoints) {
41
+ const out = [];
42
+ for (let i = 0; i + 3 < controlPoints.length; i += 4) {
43
+ const [a, b, c, d] = [controlPoints[i], controlPoints[i + 1], controlPoints[i + 2], controlPoints[i + 3]];
44
+ if (a && b && c && d)
45
+ out.push([a, b, c, d]);
46
+ }
47
+ return out;
48
+ }
49
+ function cubicAt(c, t) {
50
+ const u = 1 - t;
51
+ const [a, b, d, e] = c;
52
+ return [
53
+ u * u * u * a[0] + 3 * u * u * t * b[0] + 3 * u * t * t * d[0] + t * t * t * e[0],
54
+ u * u * u * a[1] + 3 * u * u * t * b[1] + 3 * u * t * t * d[1] + t * t * t * e[1],
55
+ ];
56
+ }
57
+ /** The part of `c` from `a` to `b` (Manim `partial_bezier_points`). */
58
+ function cubicPart(c, a, b) {
59
+ const halves = (k, t) => {
60
+ const [p0, p1, p2, p3] = k;
61
+ const q0 = lerp(p0, p1, t);
62
+ const q1 = lerp(p1, p2, t);
63
+ const q2 = lerp(p2, p3, t);
64
+ const r0 = lerp(q0, q1, t);
65
+ const r1 = lerp(q1, q2, t);
66
+ const s = lerp(r0, r1, t);
67
+ return [
68
+ [p0, q0, r0, s],
69
+ [s, r1, q2, p3],
70
+ ];
71
+ };
72
+ const right = halves(c, a)[1];
73
+ return halves(right, a === 1 ? 0 : (b - a) / (1 - a))[0];
74
+ }
75
+ function isStraight(c) {
76
+ const [a, b, d, e] = c;
77
+ const v = sub(e, a);
78
+ return Math.abs(cross(v, sub(b, a))) < 1e-12 && Math.abs(cross(v, sub(d, a))) < 1e-12;
79
+ }
80
+ function cubicLength(c) {
81
+ if (isStraight(c))
82
+ return norm(sub(c[3], c[0]));
83
+ let total = 0;
84
+ let last = c[0];
85
+ for (let i = 1; i <= 16; i++) {
86
+ const p = cubicAt(c, i / 16);
87
+ total += norm(sub(p, last));
88
+ last = p;
89
+ }
90
+ return total;
91
+ }
92
+ function arcLength(controlPoints) {
93
+ return cubics(controlPoints).reduce((s, c) => s + cubicLength(c), 0);
94
+ }
95
+ /** The part of a path from proportion `a` to `b` of its length (Manim `pointwise_become_partial`). */
96
+ function pathPart(controlPoints, a, b) {
97
+ const cs = cubics(controlPoints);
98
+ const lengths = cs.map(cubicLength);
99
+ const total = lengths.reduce((s, l) => s + l, 0);
100
+ const out = [];
101
+ let run = 0;
102
+ cs.forEach((c, i) => {
103
+ const l = lengths[i] ?? 0;
104
+ const [s, e] = [run, run + l];
105
+ run = e;
106
+ const from = Math.max(a * total, s);
107
+ const to = Math.min(b * total, e);
108
+ if (l === 0 || to <= from)
109
+ return;
110
+ out.push(...cubicPart(c, (from - s) / l, (to - s) / l));
111
+ });
112
+ return out;
113
+ }
114
+ /** Manim's `line_intersection` of two lines through point pairs, or undefined when parallel. */
115
+ function lineIntersection(l1, l2) {
116
+ const d1 = sub(l1[1], l1[0]);
117
+ const d2 = sub(l2[1], l2[0]);
118
+ const den = cross(d1, d2);
119
+ if (Math.abs(den) < 1e-12)
120
+ return undefined;
121
+ const t = cross(sub(l2[0], l1[0]), d2) / den;
122
+ return add(l1[0], mul(d1, t));
123
+ }
124
+ /** Manim's `regular_vertices`: `start_angle` defaults to 0 for an even `n`, else 90°. */
125
+ function regularVertices(n, radius, startAngle) {
126
+ const start = startAngle ?? (n % 2 === 0 ? 0 : TAU / 4);
127
+ const vs = Array.from({ length: n }, (_, k) => {
128
+ const a = start + (k * TAU) / n;
129
+ return [radius * Math.cos(a), radius * Math.sin(a)];
130
+ });
131
+ return [vs, start];
132
+ }
133
+ /** The points of a node and all its descendants (Manim `get_all_points`). */
134
+ function familyPoints(m) {
135
+ return m.getFamily().flatMap((x) => x.getPoints());
136
+ }
137
+ /** Manim `get_boundary_point`: the point of the family farthest in `direction`. */
138
+ function boundaryPoint(m, direction) {
139
+ const ps = familyPoints(m);
140
+ let best = ps[0] ?? m.getCenter();
141
+ for (const p of ps)
142
+ if (dot(p, direction) > dot(best, direction))
143
+ best = p;
144
+ return best;
145
+ }
146
+ /** A new path node with these control points and the default shape style. */
147
+ function pathNode(controlPoints) {
148
+ const h = engine.polyline([
149
+ [0, 0],
150
+ [1, 0],
151
+ ]);
152
+ if (controlPoints.length > 0)
153
+ h.setPoints([...controlPoints]);
154
+ else
155
+ h.setPoints([]);
156
+ return h;
157
+ }
158
+ /** Control points of smooth curves through each list of anchors (Manim `make_smooth`). */
159
+ function smoothPaths(lines) {
160
+ return lines.flatMap((anchors) => {
161
+ if (anchors.length < 2)
162
+ return [];
163
+ const h = engine.polyline([
164
+ [0, 0],
165
+ [1, 0],
166
+ ]);
167
+ h.setPointsSmoothly([...anchors]);
168
+ return h.getPoints();
169
+ });
170
+ }
171
+ /** The handle of child `i` of `parent`, as a new wrapper of class `make`. Only for new nodes. */
172
+ function child(parent, i, make) {
173
+ const handles = raw(parent).children();
174
+ const h = i < 0 ? handles.at(i) : handles[i];
175
+ return h === undefined ? undefined : make(h);
176
+ }
177
+ // --- tips ------------------------------------------------------------------------------
178
+ /** An arrow tip: Manim's `ArrowTip`. Its first point is the tip point, and the point half
179
+ * way along its path is the base. */
180
+ export class ArrowTipMobject extends Mobject {
181
+ /** The point half way along the path (Manim `base`). */
182
+ get base() {
183
+ return this.pointFromProportion(0.5);
184
+ }
185
+ /** The first point (Manim `tip_point`). */
186
+ get tipPoint() {
187
+ return this.getPoints()[0] ?? this.getCenter();
188
+ }
189
+ /** `tipPoint - base` (Manim `vector`). */
190
+ get vector() {
191
+ return sub(this.tipPoint, this.base);
192
+ }
193
+ /** The angle of `vector` (Manim `tip_angle`). */
194
+ get tipAngle() {
195
+ return angleOf(this.vector);
196
+ }
197
+ /** The length of `vector` (Manim `length`), not the number of submobjects. */
198
+ get length() {
199
+ return norm(this.vector);
200
+ }
201
+ copy() {
202
+ return new ArrowTipMobject(raw(this).copy());
203
+ }
204
+ }
205
+ /** The tip of a stealth arrow: its `length` is 1.6 times `vector`. */
206
+ export class StealthTipMobject extends ArrowTipMobject {
207
+ get length() {
208
+ return norm(this.vector) * 1.6;
209
+ }
210
+ copy() {
211
+ return new StealthTipMobject(raw(this).copy());
212
+ }
213
+ }
214
+ /** Manim's `ArrowTip` is abstract: make a tip with one of the tip shapes. */
215
+ export function ArrowTip() {
216
+ return wrong("ArrowTip", "ArrowTip is abstract", "use m.ArrowTriangleFilledTip, m.ArrowTriangleTip, m.ArrowCircleTip, m.ArrowSquareTip or m.StealthTip");
217
+ }
218
+ function polygonTip(vertices, o, fill, stroke) {
219
+ const t = new ArrowTipMobject(pathNode(corners(vertices)));
220
+ return styled(t, { fillOpacity: fill, strokeWidth: stroke, ...o });
221
+ }
222
+ /** A triangle tip that points left before it is placed (Manim `ArrowTriangleTip`). Alone, it is
223
+ * blue, as Manim's `Triangle`; on a path, it takes the colour of the path. */
224
+ export function ArrowTriangleTip(opts = {}) {
225
+ const { fillOpacity = 0, strokeWidth = 3, length = 0.35, width = 0.35, startAngle = PI, ...style } = opts;
226
+ const [vs] = regularVertices(3, 1, startAngle);
227
+ const t = polygonTip([...vs, vs[0] ?? ORIGIN], { color: BLUE, ...style }, fillOpacity, strokeWidth);
228
+ return t.stretchToFitWidth(length).stretchToFitHeight(width);
229
+ }
230
+ export function ArrowTriangleFilledTip(opts = {}) {
231
+ return ArrowTriangleTip({ fillOpacity: 1, strokeWidth: 0, ...opts });
232
+ }
233
+ /** A circle tip (Manim `ArrowCircleTip`): its path starts at angle 0, as in Manim. */
234
+ export function ArrowCircleTip(opts = {}) {
235
+ const { fillOpacity = 0, strokeWidth = 3, length = 0.35, startAngle: _ = PI, ...style } = opts;
236
+ const t = new ArrowTipMobject(engine.circle(1));
237
+ styled(t, { color: RED, fillOpacity, strokeWidth, ...style });
238
+ return t.stretchToFitWidth(length).stretchToFitHeight(length);
239
+ }
240
+ export function ArrowCircleFilledTip(opts = {}) {
241
+ return ArrowCircleTip({ fillOpacity: 1, strokeWidth: 0, ...opts });
242
+ }
243
+ /** A square tip (Manim `ArrowSquareTip`): a corner is the tip point. */
244
+ export function ArrowSquareTip(opts = {}) {
245
+ const { fillOpacity = 0, strokeWidth = 3, length = 0.35, startAngle: _ = PI, ...style } = opts;
246
+ const h = length / 2;
247
+ const vs = [
248
+ [h, h],
249
+ [-h, h],
250
+ [-h, -h],
251
+ [h, -h],
252
+ [h, h],
253
+ ];
254
+ return polygonTip(vs, style, fillOpacity, strokeWidth);
255
+ }
256
+ export function ArrowSquareFilledTip(opts = {}) {
257
+ return ArrowSquareTip({ fillOpacity: 1, strokeWidth: 0, ...opts });
258
+ }
259
+ /** A stealth tip (Manim `StealthTip`). */
260
+ export function StealthTip(opts = {}) {
261
+ const { fillOpacity = 1, strokeWidth = 3, length = 0.35 / 2, startAngle: _ = PI, ...style } = opts;
262
+ const vs = [
263
+ [2, 0],
264
+ [-1.2, 1.6],
265
+ [0, 0],
266
+ [-1.2, -1.6],
267
+ [2, 0],
268
+ ];
269
+ const t = styled(new StealthTipMobject(pathNode(corners(vs))), { fillOpacity, strokeWidth, ...style });
270
+ return t.scale(length / t.length);
271
+ }
272
+ /** A path that can have a tip at each end (Manim `TipableVMobject`). */
273
+ export class TipableVMobjectMobject extends Mobject {
274
+ tipLength = 0.35;
275
+ tipStyle = {};
276
+ #tip;
277
+ #startTip;
278
+ /** A copy with the same class, tips and settings. */
279
+ copy() {
280
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- every subclass takes one handle
281
+ const make = this.constructor;
282
+ const c = new make(raw(this).copy());
283
+ c.takeSettings(this);
284
+ return c;
285
+ }
286
+ /** Copies the settings of `from` (a copy of the same node) to this copy. */
287
+ takeSettings(from) {
288
+ this.tipLength = from.tipLength;
289
+ this.tipStyle = from.tipStyle;
290
+ const kids = from.submobjects;
291
+ const mine = raw(this).children();
292
+ const at = (t) => {
293
+ const i = t === undefined ? -1 : kids.indexOf(t);
294
+ const h = mine[i];
295
+ return i < 0 || h === undefined
296
+ ? undefined
297
+ : t instanceof StealthTipMobject
298
+ ? new StealthTipMobject(h)
299
+ : new ArrowTipMobject(h);
300
+ };
301
+ this.#tip = at(from.#tip);
302
+ this.#startTip = at(from.#startTip);
303
+ }
304
+ /** Adds a tip (Manim `add_tip`): `tip` as it is, or a new tip of `tipShape`. The path is
305
+ * shortened to end at the base of the tip. A tip at the end makes the Mobject an arrow
306
+ * for the arrow checks. */
307
+ addTip(opts = {}) {
308
+ const { tip: given, atStart = false, ...make } = opts;
309
+ const t = given === undefined ? this.createTip({ ...make, atStart }) : this.positionTip(given, atStart);
310
+ if (atStart) {
311
+ this.resetEndpointsBasedOnTip(t, true);
312
+ this.add(t);
313
+ }
314
+ else {
315
+ // The engine's tip marks the node as an arrow; the new tip takes its place, first.
316
+ const others = this.submobjects;
317
+ this.remove(others);
318
+ const ps = this.getPoints();
319
+ raw(this).addTip(t.length, t.length, false);
320
+ this.remove(this.submobjects);
321
+ this.setPoints(ps);
322
+ this.resetEndpointsBasedOnTip(t, false);
323
+ this.add(t, ...others);
324
+ }
325
+ return this.assignTipAttr(t, atStart);
326
+ }
327
+ /** A new tip, placed at the start or the end (Manim `create_tip`). */
328
+ createTip(opts = {}) {
329
+ const { atStart = false, ...make } = opts;
330
+ return this.positionTip(this.getUnpositionedTip(make), atStart);
331
+ }
332
+ /** A new tip in the colour of the path, not placed yet (Manim `get_unpositioned_tip`). */
333
+ getUnpositionedTip(opts = {}) {
334
+ const shape = opts.tipShape ?? ArrowTriangleFilledTip;
335
+ const length = opts.tipLength ?? this.getDefaultTipLength();
336
+ const color = this.getStrokeColor();
337
+ const width = opts.tipWidth ?? (shape === ArrowTriangleFilledTip ? this.getDefaultTipLength() : undefined);
338
+ return shape({
339
+ length,
340
+ ...(width === undefined ? {} : { width }),
341
+ fillColor: color,
342
+ strokeColor: color,
343
+ ...this.tipStyle,
344
+ });
345
+ }
346
+ /** Turns and moves `tip` so that its tip point is at the end (or the start) and it points
347
+ * along the path (Manim `position_tip`). */
348
+ positionTip(tip, atStart = false) {
349
+ const ps = this.getPoints();
350
+ const anchor = atStart ? ps[0] : ps.at(-1);
351
+ if (anchor === undefined)
352
+ return wrong("addTip", "the Mobject has no path of its own to put a tip on");
353
+ const inward = (atStart ? ps.slice(1) : ps.slice(0, -1).toReversed()).find((p) => !same(p, anchor));
354
+ const handle = inward ?? anchor;
355
+ tip.rotate(angleOf(sub(handle, anchor)) - PI - tip.tipAngle);
356
+ tip.shift(sub(anchor, tip.tipPoint));
357
+ return tip;
358
+ }
359
+ /** Moves the end of the path (or its start) to the base of `tip` (Manim
360
+ * `reset_endpoints_based_on_tip`). */
361
+ resetEndpointsBasedOnTip(tip, atStart) {
362
+ if (!(this instanceof ArrowMobject)) {
363
+ // Manim's put_start_and_end_on: the whole family scales and turns about the start, so a
364
+ // tip that is already on keeps its tip point and turns with the path.
365
+ const [start, end] = [this.getStart(), this.getEnd()];
366
+ if (same(start, end, 0))
367
+ return this;
368
+ const [s1, e1] = atStart ? [tip.base, end] : [start, tip.base];
369
+ const [v0, v1] = [sub(end, start), sub(e1, s1)];
370
+ return this.scale(norm(v1) / norm(v0), { aboutPoint: start })
371
+ .rotate(angleOf(v1) - angleOf(v0), { aboutPoint: start })
372
+ .shift(sub(s1, start));
373
+ }
374
+ // An arrow's scale keeps its tips (Manim `Arrow.scale`): only the own path moves.
375
+ const ps = this.getPoints();
376
+ const [start, end] = [ps[0], ps.at(-1)];
377
+ if (start === undefined || end === undefined || same(start, end, 0))
378
+ return this;
379
+ const [s1, e1] = atStart ? [tip.base, end] : [start, tip.base];
380
+ const [v0, v1] = [sub(end, start), sub(e1, s1)];
381
+ const k = norm(v1) / norm(v0);
382
+ const turn = angleOf(v1) - angleOf(v0);
383
+ return this.setPoints(ps.map((p) => add(s1, rotated(mul(sub(p, start), k), turn))));
384
+ }
385
+ /** Keeps `tip` as the tip at the end, or at the start (Manim `assign_tip_attr`). */
386
+ assignTipAttr(tip, atStart) {
387
+ if (atStart)
388
+ this.#startTip = tip;
389
+ else
390
+ this.#tip = tip;
391
+ return this;
392
+ }
393
+ hasTip() {
394
+ return this.#tip !== undefined && this.contains(this.#tip);
395
+ }
396
+ hasStartTip() {
397
+ return this.#startTip !== undefined && this.contains(this.#startTip);
398
+ }
399
+ /** Removes the tips and gives them as a group; the path keeps its ends (Manim `pop_tips`). */
400
+ popTips() {
401
+ const [start, end] = [this.getStart(), this.getEnd()];
402
+ const result = VGroup();
403
+ const tips = [this.hasTip() ? this.#tip : undefined, this.hasStartTip() ? this.#startTip : undefined];
404
+ for (const t of tips) {
405
+ if (t === undefined)
406
+ continue;
407
+ this.remove(t);
408
+ result.add(t);
409
+ }
410
+ if (result.length > 0)
411
+ this.putStartAndEndOn(start, end);
412
+ return result;
413
+ }
414
+ /** The tips, the end tip first (Manim `get_tips`). */
415
+ getTips() {
416
+ return VGroup([this.#tip, this.#startTip].filter((t) => t !== undefined));
417
+ }
418
+ /** The end tip, else the start tip. No tip is an error (Manim `get_tip`). */
419
+ getTip() {
420
+ const t = this.#tip ?? this.#startTip;
421
+ return t ?? wrong("getTip", "the Mobject has no tip", "add one with addTip()");
422
+ }
423
+ getDefaultTipLength() {
424
+ return this.tipLength;
425
+ }
426
+ /** The second control point (Manim `get_first_handle`). */
427
+ getFirstHandle() {
428
+ return this.getPoints()[1] ?? this.getStart();
429
+ }
430
+ /** The control point before the last (Manim `get_last_handle`). */
431
+ getLastHandle() {
432
+ return this.getPoints().at(-2) ?? this.getEnd();
433
+ }
434
+ /** The tip point of the end tip, else the end of the path. */
435
+ getEnd() {
436
+ if (this.hasTip() && this.#tip)
437
+ return this.#tip.tipPoint;
438
+ return this.getPoints().at(-1) ?? super.getEnd();
439
+ }
440
+ /** The tip point of the start tip, else the start of the path. */
441
+ getStart() {
442
+ if (this.hasStartTip() && this.#startTip)
443
+ return this.#startTip.tipPoint;
444
+ return this.getPoints()[0] ?? super.getStart();
445
+ }
446
+ /** The distance from `getStart()` to `getEnd()`. */
447
+ getLength() {
448
+ return norm(sub(this.getEnd(), this.getStart()));
449
+ }
450
+ }
451
+ /** An empty path that can have tips (Manim `TipableVMobject`). */
452
+ export function TipableVMobject(opts = {}) {
453
+ return tipable(new TipableVMobjectMobject(pathNode([])), opts);
454
+ }
455
+ function tipable(m, opts) {
456
+ const { tipLength = 0.35, tipStyle = {}, ...style } = opts;
457
+ m.tipLength = tipLength;
458
+ m.tipStyle = tipStyle;
459
+ return styled(m, style);
460
+ }
461
+ // --- arcs ------------------------------------------------------------------------------
462
+ /** An arc: Manim's `Arc`, with its centre methods. */
463
+ export class ArcMobject extends TipableVMobjectMobject {
464
+ /** The centre of the circle of the first curve (Manim `get_arc_center`), or the origin when
465
+ * the first curve is straight. aula prints no warning. */
466
+ getArcCenter(_opts = {}) {
467
+ const [a1, h1, h2, a2] = this.getPoints();
468
+ if (!a1 || !h1 || !h2 || !a2)
469
+ return ORIGIN;
470
+ if (same(a1, a2, 0))
471
+ return a1;
472
+ const n1 = rotated(sub(h1, a1), TAU / 4);
473
+ const n2 = rotated(sub(h2, a2), TAU / 4);
474
+ return lineIntersection([a1, add(a1, n1)], [a2, add(a2, n2)]) ?? ORIGIN;
475
+ }
476
+ moveArcCenterTo(point) {
477
+ return this.shift(sub(point, this.getArcCenter()));
478
+ }
479
+ /** The angle of the last point about the centre, from 0 to TAU (Manim `stop_angle`). */
480
+ stopAngle() {
481
+ const end = this.getPoints().at(-1) ?? ORIGIN;
482
+ const a = angleOf(sub(end, this.getArcCenter())) % TAU;
483
+ return a < 0 ? a + TAU : a;
484
+ }
485
+ }
486
+ /** An arc of `radius` about `arcCenter`, counter-clockwise from `startAngle` by `angle`. */
487
+ export function Arc(opts = {}) {
488
+ const { radius = 1, startAngle = 0, angle = TAU / 4, numComponents = 9, arcCenter = ORIGIN, ...rest } = opts;
489
+ const m = new ArcMobject(engine.arc(radius, startAngle, angle, Math.max(2, Math.round(numComponents))));
490
+ return tipable(m.shift(arcCenter), rest);
491
+ }
492
+ /** An arc from `start` to `end` that turns by `angle`, or on a circle of `radius` (Manim
493
+ * `ArcBetweenPoints`). A positive angle bends it counter-clockwise. */
494
+ export function ArcBetweenPoints(start, end, opts = {}) {
495
+ const { radius, ...rest } = opts;
496
+ let { angle = TAU / 4 } = opts;
497
+ if (radius !== undefined) {
498
+ const sign = radius < 0 ? -2 : 2;
499
+ const r = Math.abs(radius);
500
+ const half = norm(sub(start, end)) / 2;
501
+ if (r < half) {
502
+ wrong("ArcBetweenPoints", `the radius ${String(r)} is smaller than half the distance between the points (${String(half)})`);
503
+ }
504
+ const height = r - Math.sqrt(r * r - half * half);
505
+ angle = Math.acos((r - height) / r) * sign;
506
+ }
507
+ const arc = Arc({ ...rest, radius: radius ?? 1, angle });
508
+ if (angle === 0)
509
+ arc.setPoints(straight(LEFT, RIGHT));
510
+ return arc.putStartAndEndOn(start, end);
511
+ }
512
+ /** An arc from `startPoint` to `endPoint` with a tip at the end (Manim `CurvedArrow`). The
513
+ * default `angle` (TAU / 4) bends it counter-clockwise. */
514
+ export function CurvedArrow(startPoint, endPoint, opts = {}) {
515
+ const { tipShape, tipShapeEnd, tipShapeStart: _, ...rest } = opts;
516
+ const shape = tipShapeEnd ?? tipShape;
517
+ return ArcBetweenPoints(startPoint, endPoint, rest).addTip(shape === undefined ? {} : { tipShape: shape });
518
+ }
519
+ /** A CurvedArrow with a tip at both ends (Manim `CurvedDoubleArrow`). */
520
+ export function CurvedDoubleArrow(startPoint, endPoint, opts = {}) {
521
+ const { tipShapeStart, ...rest } = opts;
522
+ const arrow = CurvedArrow(startPoint, endPoint, rest);
523
+ return arrow.addTip({ atStart: true, ...(tipShapeStart === undefined ? {} : { tipShape: tipShapeStart }) });
524
+ }
525
+ /** A circle: Manim's `Circle`, with `surround`, `pointAtAngle` and `fromThreePoints`. */
526
+ export class CircleMobject extends ArcMobject {
527
+ /** Fits the circle around `mobject` and grows it by `bufferFactor` (Manim `surround`). */
528
+ surround(mobject, opts = {}) {
529
+ const { dimToMatch = 0, stretch = false, bufferFactor = 1.2 } = opts;
530
+ this.replace(mobject, { dimToMatch, stretch });
531
+ this.width = Math.hypot(mobject.width, mobject.height);
532
+ return this.scale(bufferFactor);
533
+ }
534
+ /** The point at `angle` (radians from the start of the circle, Manim `point_at_angle`). */
535
+ pointAtAngle(angle) {
536
+ const p = angle / TAU;
537
+ return this.pointFromProportion(p - Math.floor(p));
538
+ }
539
+ /** The circle through three points (Manim `Circle.from_three_points`). */
540
+ fromThreePoints(p1, p2, p3, opts = {}) {
541
+ return circleThrough(p1, p2, p3, opts);
542
+ }
543
+ }
544
+ function bisector(a, b) {
545
+ const m = lerp(a, b, 0.5);
546
+ return [m, add(m, rotated(sub(b, a), TAU / 4))];
547
+ }
548
+ function circleThrough(p1, p2, p3, opts) {
549
+ const center = lineIntersection(bisector(p1, p2), bisector(p2, p3));
550
+ if (center === undefined)
551
+ return wrong("Circle.fromThreePoints", "the three points are on one line");
552
+ return Circle({ ...opts, radius: norm(sub(p1, center)) }).shift(center);
553
+ }
554
+ /** A circle of `radius` (Manim `Circle`). */
555
+ export function Circle(opts = {}) {
556
+ const { radius = 1, ...style } = opts;
557
+ return styled(new CircleMobject(engine.circle(radius)), { color: RED, ...style });
558
+ }
559
+ /** The circle through three points (Manim `Circle.from_three_points`). */
560
+ Circle.fromThreePoints = (p1, p2, p3, opts = {}) => circleThrough(p1, p2, p3, opts);
561
+ circleFrames.add(Circle);
562
+ /** A filled dot: Manim's `fillOpacity` 1 and `strokeWidth` 0. */
563
+ export function Dot(point = ORIGIN, opts = {}) {
564
+ const { radius = 0.08, ...style } = opts;
565
+ return styled(new CircleMobject(engine.dot(point, radius, WHITE)), style);
566
+ }
567
+ /** A dot with a white ring (Manim `AnnotationDot`). */
568
+ export function AnnotationDot(opts = {}) {
569
+ const { radius = 0.08 * 1.3, strokeWidth = 5, strokeColor = WHITE, fillColor = BLUE, point, ...rest } = opts;
570
+ return Dot(point ?? ORIGIN, { radius, strokeWidth, strokeColor, fillColor, ...rest });
571
+ }
572
+ /** A dot with a label in it (Manim `LabeledDot`). A string becomes a black `MathTex`. */
573
+ export function LabeledDot(label, opts = {}) {
574
+ const { radius, buff = SMALL_BUFF, point, ...style } = opts;
575
+ const text = typeof label === "string" ? MathTex(label, { color: BLACK }) : label;
576
+ const r = radius ?? buff + Math.hypot(text.width, text.height) / 2;
577
+ const d = Dot(point ?? ORIGIN, { radius: r, ...style });
578
+ text.moveTo(d.getCenter());
579
+ return d.add(text);
580
+ }
581
+ export function Ellipse(opts = {}) {
582
+ const { width = 2, height = 1, ...style } = opts;
583
+ return styled(new CircleMobject(engine.ellipse(width, height)), { color: RED, ...style });
584
+ }
585
+ /** A filled ring piece: Manim's `fillOpacity` 1 and `strokeWidth` 0. */
586
+ export function AnnularSector(opts = {}) {
587
+ const { innerRadius = 1, outerRadius = 2, angle = TAU / 4, startAngle = 0, arcCenter = ORIGIN, ...style } = opts;
588
+ const m = new ArcMobject(engine.annularSector(innerRadius, outerRadius, angle, startAngle));
589
+ return styled(m, style).shift(arcCenter);
590
+ }
591
+ /** A filled circle piece (Manim `Sector`): an AnnularSector with inner radius 0. */
592
+ export function Sector(opts = {}) {
593
+ const { radius = 1, ...rest } = opts;
594
+ return AnnularSector({ ...rest, innerRadius: 0, outerRadius: radius });
595
+ }
596
+ /** A filled ring (Manim `Annulus`): the outer circle and the inner circle backwards. */
597
+ export function Annulus(opts = {}) {
598
+ const { innerRadius = 1, outerRadius = 2, arcCenter = ORIGIN, ...style } = opts;
599
+ const m = new CircleMobject(engine.circle(outerRadius));
600
+ const inner = new CircleMobject(engine.circle(innerRadius)).getPoints().toReversed();
601
+ m.setPoints([...m.getPoints(), ...inner]);
602
+ styled(m, { fillOpacity: 1, strokeWidth: 0, color: WHITE });
603
+ return styled(m, style).shift(arcCenter);
604
+ }
605
+ function isList(v) {
606
+ return Array.isArray(v);
607
+ }
608
+ /** A path with the arcs as submobjects (Manim `ArcPolygon` and `ArcPolygonFromArcs`). */
609
+ export class ArcPolygonMobject extends Mobject {
610
+ /** The arcs (Manim `arcs`). */
611
+ get arcs() {
612
+ return this.submobjects;
613
+ }
614
+ copy() {
615
+ return new ArcPolygonMobject(raw(this).copy());
616
+ }
617
+ }
618
+ /** A closed path of arcs between the vertices (Manim `ArcPolygon`): `ArcPolygon(...vertices, opts)`. */
619
+ export function ArcPolygon(...args) {
620
+ const [items, o = {}] = split(args);
621
+ const { angle = PI / 4, radius, arcConfig, ...style } = o;
622
+ const vs = flatPoints(items);
623
+ const n = vs.length;
624
+ const configs = isList(arcConfig) ? arcConfig : undefined;
625
+ const single = isList(arcConfig) ? undefined : arcConfig;
626
+ if (configs !== undefined && configs.length !== n) {
627
+ wrong("ArcPolygon", `arcConfig has ${String(configs.length)} entries for ${String(n)} vertices`);
628
+ }
629
+ const arcs = vs.map((v, k) => {
630
+ const c = configs?.[k] ?? single ?? (radius ? { radius } : { angle });
631
+ return ArcBetweenPoints(v, vs[(k + 1) % n] ?? v, c);
632
+ });
633
+ const m = new ArcPolygonMobject(pathNode(arcs.flatMap((a) => a.getPoints())));
634
+ styled(m, style);
635
+ return m.add(arcs);
636
+ }
637
+ /** A closed path of the arcs, with straight lines between them (Manim `ArcPolygonFromArcs`). */
638
+ export function ArcPolygonFromArcs(...args) {
639
+ const [arcs, style] = split(args);
640
+ if (!arcs.every((a) => a instanceof ArcMobject)) {
641
+ wrong("ArcPolygonFromArcs", "all the arguments must be arcs (m.Arc or m.ArcBetweenPoints)");
642
+ }
643
+ const ps = [];
644
+ arcs.forEach((a1, i) => {
645
+ const a2 = arcs[(i + 1) % arcs.length] ?? a1;
646
+ const own = a1.getPoints();
647
+ ps.push(...own);
648
+ const [from, to] = [a1.getEnd(), a2.getStart()];
649
+ const ratio = norm(sub(to, from)) / arcLength(own);
650
+ if (!Number.isFinite(ratio))
651
+ return;
652
+ const n = Math.max(1, Math.floor((own.length / 4) * ratio) + 1);
653
+ for (let k = 0; k < n; k++)
654
+ ps.push(...straight(lerp(from, to, k / n), lerp(from, to, (k + 1) / n)));
655
+ });
656
+ const m = new ArcPolygonMobject(pathNode(ps));
657
+ styled(m, style);
658
+ return m.add(arcs);
659
+ }
660
+ /** An arc of `radius` that touches both lines (Manim `TangentialArc`). `corner` picks the
661
+ * corner: the sign along each line from the intersection. */
662
+ export function TangentialArc(line1, line2, radius, opts = {}) {
663
+ const { corner = [1, 1], ...rest } = opts;
664
+ const at = lineIntersection([line1.getStart(), line1.getEnd()], [line2.getStart(), line2.getEnd()]);
665
+ if (at === undefined)
666
+ return wrong("TangentialArc", "the lines are parallel");
667
+ const u1 = mul(line1.getUnitVector(), corner[0]);
668
+ const u2 = mul(line2.getUnitVector(), corner[1]);
669
+ const cornerAngle = Math.acos(Math.max(-1, Math.min(1, dot(u1, u2))));
670
+ const d = radius / Math.tan(cornerAngle / 2);
671
+ const [t1, t2] = [add(at, mul(u1, d)), add(at, mul(u2, d))];
672
+ const [s, e] = cross(u1, u2) < 0 ? [t1, t2] : [t2, t1];
673
+ return ArcBetweenPoints(s, e, { ...rest, radius });
674
+ }
675
+ /** A point, or a mobject: its centre, or its boundary point toward the other end (Manim
676
+ * `Line._pointify`). */
677
+ function pointify(v, direction) {
678
+ if (!(v instanceof Mobject))
679
+ return v;
680
+ return direction === undefined ? v.getCenter() : boundaryPoint(v, direction);
681
+ }
682
+ function ends(start, end) {
683
+ const v = unit(sub(pointify(end), pointify(start)));
684
+ return [pointify(start, v), pointify(end, mul(v, -1))];
685
+ }
686
+ /** A line: Manim's `Line`, with its methods. */
687
+ export class LineMobject extends TipableVMobjectMobject {
688
+ /** Sets the points from `start` to `end` with `buff` and `pathArc` (Manim `set_points_by_ends`). */
689
+ setPointsByEnds(start, end, opts = {}) {
690
+ const [s, e] = ends(start, end);
691
+ const h = engine.line(s, e, opts.buff ?? 0, opts.pathArc ?? 0);
692
+ return this.setPoints(h.getPoints());
693
+ }
694
+ /** Bends the line into an arc of `newValue` between its ends (Manim `set_path_arc`). */
695
+ setPathArc(newValue) {
696
+ return this.setPointsByEnds(this.getStart(), this.getEnd(), { pathArc: newValue });
697
+ }
698
+ /** The point of the line (made infinite) nearest to `point` (Manim `get_projection`). */
699
+ getProjection(point) {
700
+ const s = this.getStart();
701
+ const u = unit(sub(this.getEnd(), s));
702
+ return add(s, mul(u, dot(sub(point, s), u)));
703
+ }
704
+ /** `tan(getAngle())` (Manim `get_slope`). */
705
+ getSlope() {
706
+ return Math.tan(this.getAngle());
707
+ }
708
+ /** Turns the line about `aboutPoint` (default its start) to the angle `angle` (Manim `set_angle`). */
709
+ setAngle(angle, opts = {}) {
710
+ return this.rotate(angle - this.getAngle(), { aboutPoint: opts.aboutPoint ?? this.getStart() });
711
+ }
712
+ /** Scales the line about its centre to `length` (Manim `set_length`). */
713
+ setLength(length) {
714
+ return this.scale(length / this.getLength());
715
+ }
716
+ }
717
+ /** A line from `start` to `end`, points or mobjects. `buff` leaves a gap at both ends;
718
+ * `pathArc` bends it into an arc of that angle (counter-clockwise for a positive angle). */
719
+ export function Line(start = LEFT, end = RIGHT, opts = {}) {
720
+ const { buff = 0, pathArc = 0, ...rest } = opts;
721
+ const [s, e] = ends(start, end);
722
+ return tipable(new LineMobject(engine.line(s, e, buff, pathArc)), rest);
723
+ }
724
+ /** A dashed line: Manim's `DashedLine`. Its dashes are its submobjects. */
725
+ export class DashedLineMobject extends LineMobject {
726
+ getStart() {
727
+ return this.submobjects[0]?.getStart() ?? super.getStart();
728
+ }
729
+ getEnd() {
730
+ return this.submobjects.at(-1)?.getEnd() ?? super.getEnd();
731
+ }
732
+ getFirstHandle() {
733
+ return this.submobjects[0]?.getPoints()[1] ?? super.getFirstHandle();
734
+ }
735
+ getLastHandle() {
736
+ return this.submobjects.at(-1)?.getPoints()[2] ?? super.getLastHandle();
737
+ }
738
+ }
739
+ /** A dashed line (Manim `DashedLine`): `max(2, ceil(length / dashLength * dashedRatio))` dashes. */
740
+ export function DashedLine(start = LEFT, end = RIGHT, opts = {}) {
741
+ const { dashLength = 0.05, dashedRatio = 0.5, numDashes, buff = 0, pathArc = 0, ...rest } = opts;
742
+ const [s, e] = ends(start, end);
743
+ const line = engine.line(s, e, buff, pathArc);
744
+ const length = norm(sub(e, s));
745
+ const n = numDashes ?? Math.max(2, Math.ceil((length / dashLength) * dashedRatio));
746
+ const m = new DashedLineMobject(engine.dashed(line, n, 0.5, 0, true));
747
+ if (dashedRatio !== 0.5) {
748
+ const whole = line.getPoints();
749
+ const dash = dashedRatio / n;
750
+ const gap = n === 1 ? 1 - dashedRatio : (1 - dashedRatio) / (n - 1);
751
+ m.submobjects.forEach((d, i) => d.setPoints(pathPart(whole, i * (dash + gap), i * (dash + gap) + dash)));
752
+ }
753
+ return tipable(m, rest);
754
+ }
755
+ /** A line of `length` that touches `vmob` at proportion `alpha` (Manim `TangentLine`). */
756
+ export function TangentLine(vmob, alpha, opts = {}) {
757
+ const { length = 1, dAlpha = 1e-6, ...rest } = opts;
758
+ const line = Line(vmob.pointFromProportion(clip01(alpha - dAlpha)), vmob.pointFromProportion(clip01(alpha + dAlpha)), rest);
759
+ return line.scale(length / line.getLength());
760
+ }
761
+ /** Two short lines at a right angle (Manim `Elbow`), turned by `angle` about the origin. */
762
+ export function Elbow(opts = {}) {
763
+ const { width = 0.2, angle = 0, ...style } = opts;
764
+ const m = styled(wrap(pathNode(corners([UP, add(UP, RIGHT), RIGHT]))), style);
765
+ return m.scale(width / m.width, { aboutPoint: ORIGIN }).rotate(angle, { aboutPoint: ORIGIN });
766
+ }
767
+ /** Sets the stroke width of `m` only, not of its submobjects (Manim `family=False`). */
768
+ function setOwnStrokeWidth(m, width) {
769
+ const others = m.getFamily().slice(1);
770
+ const widths = others.map((x) => x.getStrokeWidth());
771
+ m.setStroke({ width });
772
+ others.forEach((x, i) => x.setStroke({ width: widths[i] ?? 0 }));
773
+ }
774
+ /** An arrow: Manim's `Arrow`. Its first submobject is the tip. */
775
+ export class ArrowMobject extends LineMobject {
776
+ maxTipLengthToLengthRatio = 0.25;
777
+ maxStrokeWidthToLengthRatio = 5;
778
+ initialStrokeWidth = 6;
779
+ takeSettings(from) {
780
+ super.takeSettings(from);
781
+ this.maxTipLengthToLengthRatio = from.maxTipLengthToLengthRatio;
782
+ this.maxStrokeWidthToLengthRatio = from.maxStrokeWidthToLengthRatio;
783
+ this.initialStrokeWidth = from.initialStrokeWidth;
784
+ }
785
+ /** Scales the arrow. The tips keep their size unless `scaleTips` (Manim `Arrow.scale`). */
786
+ scale(factor, opts = {}) {
787
+ const { scaleTips = false, ...about } = opts;
788
+ if (this.getLength() === 0)
789
+ return this;
790
+ if (scaleTips) {
791
+ super.scale(factor, about);
792
+ return this.setStrokeWidthFromLength();
793
+ }
794
+ const [hasTip, hasStartTip] = [this.hasTip(), this.hasStartTip()];
795
+ const old = hasTip || hasStartTip ? this.popTips().submobjects : [];
796
+ super.scale(factor, about);
797
+ this.setStrokeWidthFromLength();
798
+ const [end, start] = [hasTip ? old[0] : undefined, hasStartTip ? old.at(-1) : undefined];
799
+ if (end instanceof ArrowTipMobject)
800
+ this.addTip({ tip: end });
801
+ if (start instanceof ArrowTipMobject)
802
+ this.addTip({ tip: start, atStart: true });
803
+ return this;
804
+ }
805
+ /** `min(tipLength, maxTipLengthToLengthRatio * length)` (Manim `get_default_tip_length`). */
806
+ getDefaultTipLength() {
807
+ return Math.min(this.tipLength, this.maxTipLengthToLengthRatio * this.getLength());
808
+ }
809
+ setStrokeWidthFromLength() {
810
+ const width = Math.min(this.initialStrokeWidth, this.maxStrokeWidthToLengthRatio * this.getLength());
811
+ setOwnStrokeWidth(this, width);
812
+ return this;
813
+ }
814
+ }
815
+ function makeArrow(start, end, o, make, double) {
816
+ const { color = WHITE, strokeWidth = 6, buff = MED_SMALL_BUFF, tipLength = 0.35, maxTipLengthToLengthRatio = 0.25, maxStrokeWidthToLengthRatio = 5, pathArc = 0, tipShape, tipShapeEnd, tipShapeStart, tipStyle = {}, ...style } = o;
817
+ const [s, e] = ends(start, end);
818
+ const endShape = tipShapeEnd ?? tipShape;
819
+ const plain = pathArc === 0 && endShape === undefined && tipShapeStart === undefined && Object.keys(tipStyle).length === 0;
820
+ let m;
821
+ if (plain) {
822
+ const options = { color, strokeWidth, buff, tipLength, maxTipLengthToLengthRatio, maxStrokeWidthToLengthRatio };
823
+ m = make(double ? engine.doubleArrow(s, e, options) : engine.arrow(s, e, options));
824
+ const endTip = child(m, 0, (h) => new ArrowTipMobject(h));
825
+ if (endTip)
826
+ m.assignTipAttr(endTip, false);
827
+ const back = double ? child(m, -1, (h) => new ArrowTipMobject(h)) : undefined;
828
+ if (back)
829
+ m.assignTipAttr(back, true);
830
+ }
831
+ else {
832
+ m = make(engine.line(s, e, buff, pathArc));
833
+ m.setColor(color).setStroke({ width: strokeWidth });
834
+ }
835
+ m.tipLength = tipLength;
836
+ m.tipStyle = tipStyle;
837
+ m.maxTipLengthToLengthRatio = maxTipLengthToLengthRatio;
838
+ m.maxStrokeWidthToLengthRatio = maxStrokeWidthToLengthRatio;
839
+ m.initialStrokeWidth = strokeWidth;
840
+ if (!plain) {
841
+ m.addTip(endShape === undefined ? {} : { tipShape: endShape });
842
+ if (double)
843
+ m.addTip({ atStart: true, ...(tipShapeStart === undefined ? {} : { tipShape: tipShapeStart }) });
844
+ // Manim sets the width from the length with the tips on; a DoubleArrow sets it again in
845
+ // `Arrow.scale`, from the shaft between its tips.
846
+ const ps = m.getPoints();
847
+ const length = double ? norm(sub(ps.at(-1) ?? ORIGIN, ps[0] ?? ORIGIN)) : m.getLength();
848
+ setOwnStrokeWidth(m, Math.min(strokeWidth, maxStrokeWidthToLengthRatio * length));
849
+ }
850
+ return styled(m, style);
851
+ }
852
+ /** An arrow from `start` to `end` (Manim `Arrow`). `pathArc` bends it; `tipShape` sets the tip. */
853
+ export function Arrow(start = LEFT, end = RIGHT, opts = {}) {
854
+ return makeArrow(start, end, opts, (h) => new ArrowMobject(h), false);
855
+ }
856
+ /** An arrow with a tip at both ends (Manim `DoubleArrow`): `tipShapeStart` and `tipShapeEnd`. */
857
+ export function DoubleArrow(start = LEFT, end = RIGHT, opts = {}) {
858
+ return makeArrow(start, end, opts, (h) => new ArrowMobject(h), true);
859
+ }
860
+ /** An arrow from the origin: Manim's `Vector`. */
861
+ export class VectorMobject extends ArrowMobject {
862
+ /** The coordinates of the end as a column (Manim `coordinate_label`), next to the end. A
863
+ * `MathTex` matrix, not Manim's `Matrix`. */
864
+ coordinateLabel(opts = {}) {
865
+ const { integerLabels = true, nDim = 2, color } = opts;
866
+ const end = this.getEnd();
867
+ const values = end.slice(0, nDim).map((v) => (integerLabels ? Math.round(v) : v));
868
+ const label = MathTex(`\\begin{bmatrix} ${values.map((v) => String(v)).join(" \\\\ ")} \\end{bmatrix}`);
869
+ label.scale(1 - 0.2);
870
+ const shift = end[0] >= 0
871
+ ? sub(end, add(label.getLeft(), mul(LEFT, MED_SMALL_BUFF)))
872
+ : sub(end, add(label.getRight(), mul(RIGHT, MED_SMALL_BUFF)));
873
+ label.shift(shift);
874
+ if (color !== undefined)
875
+ label.setColor(color);
876
+ return label;
877
+ }
878
+ }
879
+ /** An arrow from the origin to `direction`, with no gaps (Manim `Vector`). */
880
+ export function Vector(direction = RIGHT, opts = {}) {
881
+ return makeArrow(ORIGIN, direction, { buff: 0, ...opts }, (h) => new VectorMobject(h), false);
882
+ }
883
+ /** An angle mark between two lines: Manim's `Angle`. */
884
+ export class AngleMobject extends Mobject {
885
+ lines;
886
+ /** The angle in radians (Manim `angle_value`). */
887
+ angleValue = 0;
888
+ copy() {
889
+ const c = new AngleMobject(raw(this).copy());
890
+ c.lines = this.lines;
891
+ c.angleValue = this.angleValue;
892
+ return c;
893
+ }
894
+ /** The two lines (Manim `get_lines`). */
895
+ getLines() {
896
+ return VGroup(this.lines ?? []);
897
+ }
898
+ /** The angle in radians, or in degrees with `degrees` (Manim `get_value`). */
899
+ getValue(opts = {}) {
900
+ return opts.degrees === true ? this.angleValue / DEGREES : this.angleValue;
901
+ }
902
+ /** The angle at `B` from `A` to `C` (Manim `Angle.from_three_points`). */
903
+ fromThreePoints(A, B, C, opts = {}) {
904
+ return Angle(Line(B, A), Line(B, C), opts);
905
+ }
906
+ }
907
+ /** An arc (or with `elbow`, a right-angle mark) between two lines (Manim `Angle`). */
908
+ export function Angle(line1, line2, opts = {}) {
909
+ const { radius, quadrant = [1, 1], otherAngle = false, dot: withDot = false, dotRadius, dotDistance = 0.55, dotColor = WHITE, elbow = false, ...style } = opts;
910
+ const m = styled(new AngleMobject(pathNode([])), style);
911
+ m.lines = [line1, line2];
912
+ const inter = lineIntersection([line1.getStart(), line1.getEnd()], [line2.getStart(), line2.getEnd()]);
913
+ if (inter === undefined)
914
+ return m;
915
+ const dist = (l, q) => norm(sub(q === 1 ? l.getEnd() : l.getStart(), inter));
916
+ const nearest = Math.min(dist(line1, quadrant[0]), dist(line2, quadrant[1]));
917
+ const r = radius ?? (nearest < 0.6 ? (2 / 3) * nearest : 0.4);
918
+ const a1 = add(inter, mul(line1.getUnitVector(), quadrant[0] * r));
919
+ const a2 = add(inter, mul(line2.getUnitVector(), quadrant[1] * r));
920
+ if (elbow) {
921
+ const middle = add(add(inter, mul(line1.getUnitVector(), quadrant[0] * r)), mul(line2.getUnitVector(), quadrant[1] * r));
922
+ m.setPoints(corners([a1, middle, a2]));
923
+ return m;
924
+ }
925
+ const [t1, t2] = [angleOf(sub(a1, inter)), angleOf(sub(a2, inter))];
926
+ const value = otherAngle ? (t2 < t1 ? t2 - t1 : -TAU + (t2 - t1)) : t2 > t1 ? t2 - t1 : TAU - (t1 - t2);
927
+ m.angleValue = value;
928
+ const arc = Arc({ radius: r, angle: value, startAngle: t1, arcCenter: inter });
929
+ m.setPoints(arc.getPoints());
930
+ if (withDot) {
931
+ const toward = unit(sub(arc.getCenter(), inter));
932
+ const d = Dot(ORIGIN, { radius: dotRadius ?? r / 10, color: dotColor });
933
+ m.add(d.moveTo(add(inter, mul(toward, r * dotDistance))));
934
+ }
935
+ return m;
936
+ }
937
+ /** The angle at `B` from `A` to `C` (Manim `Angle.from_three_points`). */
938
+ Angle.fromThreePoints = (A, B, C, opts = {}) => Angle(Line(B, A), Line(B, C), opts);
939
+ /** A right-angle mark between two lines (Manim `RightAngle`): an elbow of side `length`. */
940
+ export function RightAngle(line1, line2, opts = {}) {
941
+ const { length, ...rest } = opts;
942
+ return Angle(line1, line2, { ...rest, ...(length === undefined ? {} : { radius: length }), elbow: true });
943
+ }
944
+ // --- polygrams -------------------------------------------------------------------------
945
+ /** A path of closed polygons: Manim's `Polygram`, `Polygon`, `Rectangle`, … */
946
+ export class PolygramMobject extends Mobject {
947
+ copy() {
948
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- every subclass takes one handle
949
+ const make = this.constructor;
950
+ return new make(raw(this).copy());
951
+ }
952
+ /** The first point of each curve (Manim `get_vertices`). */
953
+ getVertices() {
954
+ return cubics(this.getPoints()).map((c) => c[0]);
955
+ }
956
+ /** The vertices of each closed polygon (Manim `get_vertex_groups`). */
957
+ getVertexGroups() {
958
+ const groups = [];
959
+ let group = [];
960
+ for (const c of cubics(this.getPoints())) {
961
+ group.push(c[0]);
962
+ if (same(c[3], group[0] ?? c[3], 1e-6)) {
963
+ groups.push(group);
964
+ group = [];
965
+ }
966
+ }
967
+ return groups;
968
+ }
969
+ /** Rounds each corner with an arc of `radius` (or each radius of a list, in turn) (Manim
970
+ * `round_corners`). */
971
+ roundCorners(opts = {}) {
972
+ const { radius = 0.5, evenlyDistributeAnchors = false, componentsPerRoundedCorner = 2 } = opts;
973
+ if (radius === 0)
974
+ return this;
975
+ const out = [];
976
+ for (const group of this.getVertexGroups()) {
977
+ const n = group.length;
978
+ const radii = typeof radius === "number" ? group.map(() => radius) : group.map((_, i) => radius[i % radius.length] ?? 0);
979
+ const arcs = group.map((_, i) => {
980
+ const [v1, v2, v3] = [group[i], group[(i + 1) % n], group[(i + 2) % n]];
981
+ if (!v1 || !v2 || !v3)
982
+ return ArcBetweenPoints(ORIGIN, ORIGIN, { angle: 0 });
983
+ const [d1, d2] = [sub(v2, v1), sub(v3, v2)];
984
+ const r = radii[i] ?? 0;
985
+ let angle = Math.acos(Math.max(-1, Math.min(1, dot(unit(d1), unit(d2))))) * Math.sign(r);
986
+ const maxCut = Math.min(norm(d1), norm(d2)) / 2;
987
+ const cut = Math.max(-maxCut, Math.min(maxCut, r * Math.tan(angle / 2)));
988
+ angle *= Math.sign(cross(d1, d2));
989
+ return ArcBetweenPoints(sub(v2, mul(unit(d1), cut)), add(v2, mul(unit(d2), cut)), {
990
+ angle,
991
+ numComponents: componentsPerRoundedCorner,
992
+ });
993
+ });
994
+ const real = arcs.filter((a) => a.getPoints().length > 4);
995
+ const average = real.length > 0
996
+ ? real.reduce((s, a) => s + arcLength(a.getPoints()), 0) /
997
+ (real.reduce((s, a) => s + a.getPoints().length, 0) / 4)
998
+ : 1;
999
+ const ordered = [arcs.at(-1), ...arcs.slice(0, -1)].filter((a) => a !== undefined);
1000
+ ordered.forEach((a1, i) => {
1001
+ const a2 = ordered[(i + 1) % ordered.length] ?? a1;
1002
+ out.push(...a1.getPoints());
1003
+ const [from, to] = [a1.getEnd(), a2.getStart()];
1004
+ const k = evenlyDistributeAnchors ? Math.max(1, Math.ceil(norm(sub(to, from)) / average) + 1) : 1;
1005
+ for (let j = 0; j < k; j++)
1006
+ out.push(...straight(lerp(from, to, j / k), lerp(from, to, (j + 1) / k)));
1007
+ });
1008
+ }
1009
+ return this.setPoints(out);
1010
+ }
1011
+ }
1012
+ function closedRing(vs) {
1013
+ const first = vs[0];
1014
+ return first === undefined ? [] : corners([...vs, first]);
1015
+ }
1016
+ /** Closed polygons, one for each list of vertices (Manim `Polygram`): `Polygram(group1, group2, opts)`. */
1017
+ export function Polygram(...args) {
1018
+ const [groups, style] = split(args);
1019
+ const first = groups[0] ?? [];
1020
+ const m = new PolygramMobject(engine.polygon([...first]));
1021
+ if (groups.length > 1)
1022
+ m.setPoints(groups.flatMap(closedRing));
1023
+ return styled(m, { color: BLUE, ...style });
1024
+ }
1025
+ /** `Polygon(...vertices, opts)`: the vertices are points or arrays of points. */
1026
+ export function Polygon(...args) {
1027
+ const [vertices, style] = split(args);
1028
+ return styled(new PolygramMobject(engine.polygon(flatPoints(vertices))), { color: BLUE, ...style });
1029
+ }
1030
+ /** The vertex groups of a regular star polygon {numVertices/density} (Manim `RegularPolygram`). */
1031
+ function regularGroups(numVertices, density, radius, startAngle) {
1032
+ const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
1033
+ const gons = gcd(numVertices, density);
1034
+ const n = numVertices / gons;
1035
+ const d = density / gons;
1036
+ const gen = (start) => {
1037
+ const [vs, s] = regularVertices(n, radius, start);
1038
+ const out = [];
1039
+ let i = 0;
1040
+ do {
1041
+ out.push(vs[i] ?? ORIGIN);
1042
+ i = (i + d) % n;
1043
+ } while (i !== 0);
1044
+ return [out, s];
1045
+ };
1046
+ const [first, s0] = gen(startAngle);
1047
+ const groups = [first];
1048
+ for (let i = 1; i < gons; i++)
1049
+ groups.push(gen(s0 + ((i / gons) * TAU) / n)[0]);
1050
+ return groups;
1051
+ }
1052
+ /** A regular star polygon {numVertices/density} (Manim `RegularPolygram`). */
1053
+ export function RegularPolygram(numVertices, opts = {}) {
1054
+ const { density = 2, radius = 1, startAngle, ...style } = opts;
1055
+ return Polygram(...regularGroups(numVertices, density, radius, startAngle), style);
1056
+ }
1057
+ export function RegularPolygon(n = 6, opts = {}) {
1058
+ const { radius, startAngle, ...style } = opts;
1059
+ const m = new PolygramMobject(engine.regularPolygon(n));
1060
+ if (radius !== undefined || startAngle !== undefined) {
1061
+ m.setPoints(closedRing(regularVertices(n, radius ?? 1, startAngle)[0]));
1062
+ }
1063
+ return styled(m, { color: BLUE, ...style });
1064
+ }
1065
+ export function Triangle(opts = {}) {
1066
+ const { radius, startAngle, ...style } = opts;
1067
+ const m = new PolygramMobject(engine.triangle());
1068
+ if (radius !== undefined || startAngle !== undefined) {
1069
+ m.setPoints(closedRing(regularVertices(3, radius ?? 1, startAngle)[0]));
1070
+ }
1071
+ return styled(m, { color: BLUE, ...style });
1072
+ }
1073
+ /** A star of `n` points (Manim `Star`). Without `innerRadius`, `density` sets it: 2 makes the
1074
+ * lines of a pentagram. */
1075
+ export function Star(n = 5, opts = {}) {
1076
+ const { outerRadius = 1, innerRadius, density = 2, startAngle = TAU / 4, ...style } = opts;
1077
+ const innerAngle = TAU / (2 * n);
1078
+ let inner = innerRadius;
1079
+ if (inner === undefined) {
1080
+ if (density <= 0 || density >= n / 2)
1081
+ wrong("Star", `density ${String(density)} does not fit ${String(n)} points`);
1082
+ const outerAngle = (TAU * density) / n;
1083
+ const inverseX = 1 - Math.tan(innerAngle) * ((Math.cos(outerAngle) - 1) / Math.sin(outerAngle));
1084
+ inner = outerRadius / (Math.cos(innerAngle) * inverseX);
1085
+ }
1086
+ const [outs, s] = regularVertices(n, outerRadius, startAngle);
1087
+ const [ins] = regularVertices(n, inner, s + innerAngle);
1088
+ const m = new PolygramMobject(engine.star(n, outerRadius));
1089
+ m.setPoints(closedRing(outs.flatMap((o, i) => [o, ins[i] ?? o])));
1090
+ return styled(m, { color: BLUE, ...style });
1091
+ }
1092
+ function addGrid(m, width, height, o) {
1093
+ const { gridXstep, gridYstep, color } = o;
1094
+ const corner = [-width / 2, height / 2];
1095
+ const lines = VGroup();
1096
+ const style = color === undefined ? {} : { color };
1097
+ if (gridXstep) {
1098
+ const step = Math.abs(gridXstep);
1099
+ const xs = Array.from({ length: Math.max(0, Math.trunc(width / step) - 1) }, (_, i) => (i + 1) * step);
1100
+ lines.add(VGroup(xs.map((x) => Line(add(corner, [x, 0]), add(corner, [x, -height]), style))));
1101
+ }
1102
+ if (gridYstep) {
1103
+ const step = Math.abs(gridYstep);
1104
+ const ys = Array.from({ length: Math.max(0, Math.trunc(height / step) - 1) }, (_, i) => (i + 1) * step);
1105
+ lines.add(VGroup(ys.map((y) => Line(add(corner, [0, -y]), add(corner, [width, -y]), style))));
1106
+ }
1107
+ if (lines.length > 0)
1108
+ m.add(lines);
1109
+ }
1110
+ export function Rectangle(opts = {}) {
1111
+ const { width = 4, height = 2, gridXstep, gridYstep, ...style } = opts;
1112
+ const m = styled(new PolygramMobject(engine.rectangle(width, height)), style);
1113
+ addGrid(m, width, height, {
1114
+ ...(gridXstep === undefined ? {} : { gridXstep }),
1115
+ ...(gridYstep === undefined ? {} : { gridYstep }),
1116
+ ...style,
1117
+ });
1118
+ return m;
1119
+ }
1120
+ /** A rectangle with round corners (Manim `RoundedRectangle`). A list of radii rounds the
1121
+ * corners in turn. */
1122
+ export function RoundedRectangle(opts = {}) {
1123
+ const { width = 4, height = 2, cornerRadius = 0.5, ...style } = opts;
1124
+ if (typeof cornerRadius === "number") {
1125
+ return styled(new PolygramMobject(engine.roundedRectangle(width, height, cornerRadius)), style);
1126
+ }
1127
+ return Rectangle({ width, height, ...style }).roundCorners({ radius: cornerRadius });
1128
+ }
1129
+ /** A square: Manim's `Square`, with `sideLength`. */
1130
+ export class SquareMobject extends PolygramMobject {
1131
+ /** The length of a side (Manim `side_length`); setting it scales the square. */
1132
+ get sideLength() {
1133
+ const [a, b] = this.getVertices();
1134
+ return a && b ? norm(sub(a, b)) : 0;
1135
+ }
1136
+ set sideLength(value) {
1137
+ this.scale(value / this.sideLength);
1138
+ }
1139
+ }
1140
+ export function Square(opts = {}) {
1141
+ const { sideLength = 2, gridXstep, gridYstep, ...style } = opts;
1142
+ const m = styled(new SquareMobject(engine.square(sideLength)), style);
1143
+ addGrid(m, sideLength, sideLength, {
1144
+ ...(gridXstep === undefined ? {} : { gridXstep }),
1145
+ ...(gridYstep === undefined ? {} : { gridYstep }),
1146
+ ...style,
1147
+ });
1148
+ return m;
1149
+ }
1150
+ /** The signed area of a closed path's anchors: positive when counter-clockwise. */
1151
+ function signedArea(controlPoints) {
1152
+ return cubics(controlPoints).reduce((s, c) => s + cross(c[0], c[3]) / 2, 0);
1153
+ }
1154
+ /** The control points backwards. */
1155
+ function reversedPath(controlPoints) {
1156
+ return controlPoints.toReversed();
1157
+ }
1158
+ /** `mainShape` with holes in the shapes of `mobjects` (Manim `Cutout`). */
1159
+ export function Cutout(mainShape, ...args) {
1160
+ const [holes, style] = split(args);
1161
+ const main = mainShape.getPoints();
1162
+ const ccw = signedArea(main) > 0;
1163
+ const ps = [...main];
1164
+ for (const h of holes) {
1165
+ const own = h.getPoints();
1166
+ ps.push(...(signedArea(own) > 0 === ccw ? reversedPath(own) : own));
1167
+ }
1168
+ return styled(wrap(pathNode(ps)), style);
1169
+ }
1170
+ /** The convex hull of the points, counter-clockwise (Manim `ConvexHull`). */
1171
+ export function ConvexHull(...args) {
1172
+ const [items, o = {}] = split(args);
1173
+ const { tolerance = 1e-5, ...style } = o;
1174
+ const ps = flatPoints(items).toSorted((a, b) => a[0] - b[0] || a[1] - b[1]);
1175
+ const half = (list) => {
1176
+ const out = [];
1177
+ for (const p of list) {
1178
+ while (out.length >= 2) {
1179
+ const [a, b] = [out.at(-2), out.at(-1)];
1180
+ if (!a || !b || cross(sub(b, a), sub(p, a)) > tolerance)
1181
+ break;
1182
+ out.pop();
1183
+ }
1184
+ out.push(p);
1185
+ }
1186
+ return out.slice(0, -1);
1187
+ };
1188
+ const hull = [...half(ps), ...half([...ps].toReversed())];
1189
+ if (hull.length < 3)
1190
+ return wrong("ConvexHull", "the points need a hull with at least 3 vertices");
1191
+ return Polygon(hull, style);
1192
+ }
1193
+ function boundsOf(ms) {
1194
+ const all = ms.map((m) => m.bounds()).filter((b) => b !== undefined);
1195
+ if (all.length === 0)
1196
+ return [ORIGIN, ORIGIN];
1197
+ return [
1198
+ [Math.min(...all.map((b) => b[0][0])), Math.min(...all.map((b) => b[0][1]))],
1199
+ [Math.max(...all.map((b) => b[1][0])), Math.max(...all.map((b) => b[1][1]))],
1200
+ ];
1201
+ }
1202
+ /** The control points of a box around `ms`, `buff` out, with round corners of `cornerRadius`. */
1203
+ function boxAround(ms, buff, cornerRadius) {
1204
+ const [bx, by] = typeof buff === "number" ? [buff, buff] : buff;
1205
+ const [lo, hi] = boundsOf(ms);
1206
+ const [w, h] = [hi[0] - lo[0] + 2 * bx, hi[1] - lo[1] + 2 * by];
1207
+ const box = cornerRadius > 0 ? engine.roundedRectangle(w, h, cornerRadius) : engine.rectangle(w, h);
1208
+ box.moveTo(lerp(lo, hi, 0.5));
1209
+ return box.getPoints();
1210
+ }
1211
+ /** A box around one or more mobjects (Manim `SurroundingRectangle`): `SurroundingRectangle(a, b, opts)`. */
1212
+ export function SurroundingRectangle(...args) {
1213
+ const [ms, o = {}] = split(args);
1214
+ const { color = PURE_YELLOW, buff = SMALL_BUFF, cornerRadius = 0, ...style } = o;
1215
+ const first = ms[0] ?? wrong("SurroundingRectangle", "give at least one Mobject");
1216
+ const m = new PolygramMobject(engine.surroundingRectangle(raw(first), color, 0));
1217
+ m.setPoints(boxAround(ms, buff, cornerRadius));
1218
+ return styled(m, style);
1219
+ }
1220
+ /** A filled box behind mobjects: Manim's `BackgroundRectangle`. */
1221
+ export class BackgroundRectangleMobject extends PolygramMobject {
1222
+ originalFillOpacity = 0.75;
1223
+ copy() {
1224
+ const c = new BackgroundRectangleMobject(raw(this).copy());
1225
+ c.originalFillOpacity = this.originalFillOpacity;
1226
+ return c;
1227
+ }
1228
+ /** Sets the fill opacity to `b` times the first one (Manim's `pointwise_become_partial`,
1229
+ * which `Create` uses). */
1230
+ pointwiseBecomePartial(mobject, a, b) {
1231
+ return this.setFill({ opacity: b * this.originalFillOpacity });
1232
+ }
1233
+ /** A black fill of `fillOpacity` and no stroke (Manim `set_style`); other options are ignored. */
1234
+ setStyle(fillOpacity) {
1235
+ const opacity = typeof fillOpacity === "object" ? fillOpacity.fillOpacity : fillOpacity;
1236
+ return this.setStroke(BLACK, { width: 0 }).setFill(BLACK, { opacity: opacity ?? this.getFillOpacity() });
1237
+ }
1238
+ }
1239
+ /** A filled box behind one or more mobjects (Manim `BackgroundRectangle`), black by default. */
1240
+ export function BackgroundRectangle(...args) {
1241
+ const [ms, o = {}] = split(args);
1242
+ const { color = BLACK, fillOpacity = 0.75, buff = 0, cornerRadius = 0, strokeWidth = 0, strokeOpacity = 0, ...style } = o;
1243
+ const first = ms[0] ?? wrong("BackgroundRectangle", "give at least one Mobject");
1244
+ const m = new BackgroundRectangleMobject(engine.backgroundRectangle(raw(first), color, fillOpacity, 0));
1245
+ m.setPoints(boxAround(ms, buff, cornerRadius));
1246
+ m.originalFillOpacity = fillOpacity;
1247
+ styled(m, { strokeWidth, strokeOpacity, ...style });
1248
+ return m;
1249
+ }
1250
+ /** Two crossed lines over `mobject` (Manim `Cross`). */
1251
+ export function Cross(mobject, opts = {}) {
1252
+ const { strokeColor = RED, strokeWidth = 6, scaleFactor = 1, ...style } = opts;
1253
+ const g = VGroup(Line(add(UP, LEFT), add(DOWN, RIGHT)), Line(add(UP, RIGHT), add(DOWN, LEFT)));
1254
+ styled(g, style);
1255
+ if (mobject !== undefined)
1256
+ g.replace(mobject, { stretch: true });
1257
+ return g.scale(scaleFactor).setStroke(strokeColor, { width: strokeWidth });
1258
+ }
1259
+ /** A line under `mobject`, as wide as it (Manim `Underline`). */
1260
+ export function Underline(mobject, opts = {}) {
1261
+ const { buff = SMALL_BUFF, ...rest } = opts;
1262
+ const line = Line(LEFT, RIGHT, { buff, ...rest });
1263
+ line.scaleToFitWidth(mobject.width);
1264
+ return line.nextTo(mobject, DOWN, { buff });
1265
+ }
1266
+ /** A label on a box with a frame (Manim `Label`): a string becomes a `MathTex`. Its
1267
+ * submobjects are the box, the label and the frame. */
1268
+ export function Label(label, opts = {}) {
1269
+ const { color = WHITE, fontSize = 48 } = opts.labelConfig ?? {};
1270
+ const text = typeof label === "string" ? MathTex(label, { color, fontSize }) : label;
1271
+ const { buff: boxBuff = 0.05, fillOpacity = 1, strokeWidth = 0.5, ...box } = opts.boxConfig ?? {};
1272
+ const { buff: frameBuff = 0.05, color: frameColor = WHITE, strokeWidth: frameWidth = 0.5, ...frame } = opts.frameConfig ?? {};
1273
+ return VGroup(BackgroundRectangle(text, { buff: boxBuff, fillOpacity, strokeWidth, ...box }), text, SurroundingRectangle(text, { buff: frameBuff, color: frameColor, strokeWidth: frameWidth, ...frame }));
1274
+ }
1275
+ function labelOptions(o) {
1276
+ return {
1277
+ ...(o.labelConfig === undefined ? {} : { labelConfig: o.labelConfig }),
1278
+ ...(o.boxConfig === undefined ? {} : { boxConfig: o.boxConfig }),
1279
+ ...(o.frameConfig === undefined ? {} : { frameConfig: o.frameConfig }),
1280
+ };
1281
+ }
1282
+ function putLabel(line, label, position, o) {
1283
+ const l = Label(label, labelOptions(o));
1284
+ l.moveTo(lerp(line.getStart(), line.getEnd(), position));
1285
+ return line.add(l);
1286
+ }
1287
+ /** A line with a label (Manim `LabeledLine`): `LabeledLine("x", { start, end, labelPosition })`. */
1288
+ export function LabeledLine(label, opts = {}) {
1289
+ const { labelPosition = 0.5, labelConfig: _l, boxConfig: _b, frameConfig: _f, start = LEFT, end = RIGHT, ...rest } = opts;
1290
+ return putLabel(Line(start, end, rest), label, labelPosition, opts);
1291
+ }
1292
+ /** An arrow with a label (Manim `LabeledArrow`). */
1293
+ export function LabeledArrow(label, opts = {}) {
1294
+ const { labelPosition = 0.5, labelConfig: _l, boxConfig: _b, frameConfig: _f, start = LEFT, end = RIGHT, ...rest } = opts;
1295
+ return putLabel(Arrow(start, end, rest), label, labelPosition, opts);
1296
+ }
1297
+ /** The pole of inaccessibility of rings (the inside point farthest from the edges), to
1298
+ * `precision` (Manim's `polylabel`). */
1299
+ function polylabel(shape, precision) {
1300
+ const outer = shape[0] ?? [];
1301
+ const xs = outer.map((p) => p[0]);
1302
+ const ys = outer.map((p) => p[1]);
1303
+ const [minX, minY, maxX, maxY] = [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
1304
+ const distance = (p) => {
1305
+ let within = false;
1306
+ let best = Infinity;
1307
+ for (const ring of shape) {
1308
+ ring.forEach((a, i) => {
1309
+ const b = ring[(i + 1) % ring.length] ?? a;
1310
+ if (a[1] > p[1] !== b[1] > p[1] && p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0])
1311
+ within = !within;
1312
+ const ab = sub(b, a);
1313
+ const t = Math.max(0, Math.min(1, dot(sub(p, a), ab) / (dot(ab, ab) || 1)));
1314
+ best = Math.min(best, norm(sub(p, add(a, mul(ab, t)))));
1315
+ });
1316
+ }
1317
+ return (within ? 1 : -1) * best;
1318
+ };
1319
+ const cell = (c, h) => {
1320
+ const d = distance(c);
1321
+ return { c, h, d, max: d + h * Math.SQRT2 };
1322
+ };
1323
+ const size = Math.min(maxX - minX, maxY - minY);
1324
+ if (size === 0)
1325
+ return [minX, minY];
1326
+ let h = size / 2;
1327
+ const queue = [];
1328
+ for (let x = minX; x < maxX; x += size)
1329
+ for (let y = minY; y < maxY; y += size)
1330
+ queue.push(cell([x + h, y + h], h));
1331
+ let best = cell([(minX + maxX) / 2, (minY + maxY) / 2], 0);
1332
+ while (queue.length > 0) {
1333
+ queue.sort((a, b) => a.max - b.max);
1334
+ const c = queue.pop();
1335
+ if (c === undefined)
1336
+ break;
1337
+ if (c.d > best.d)
1338
+ best = c;
1339
+ if (c.max - best.d <= precision)
1340
+ continue;
1341
+ h = c.h / 2;
1342
+ for (const [dx, dy] of [
1343
+ [-1, -1],
1344
+ [1, -1],
1345
+ [-1, 1],
1346
+ [1, 1],
1347
+ ])
1348
+ queue.push(cell([c.c[0] + dx * h, c.c[1] + dy * h], h));
1349
+ }
1350
+ return best.c;
1351
+ }
1352
+ /** A polygram with a label at its pole of inaccessibility (Manim `LabeledPolygram`):
1353
+ * `LabeledPolygram(group1, group2, { label })`. */
1354
+ export function LabeledPolygram(...args) {
1355
+ const [groups, o] = split(args);
1356
+ if (o === undefined)
1357
+ return wrong("LabeledPolygram", "the options need a label", "LabeledPolygram(vertices, { label })");
1358
+ const { label, precision = 0.01, labelConfig: _l, boxConfig: _b, frameConfig: _f, ...style } = o;
1359
+ const m = Polygram(...groups, style);
1360
+ const l = Label(label, labelOptions(o));
1361
+ l.moveTo(polylabel(groups, precision));
1362
+ return m.add(l);
1363
+ }
1364
+ function lineCubic(a, b) {
1365
+ return [a, lerp(a, b, 1 / 3), lerp(a, b, 2 / 3), b];
1366
+ }
1367
+ function reversed(c) {
1368
+ return [c[3], c[2], c[1], c[0]];
1369
+ }
1370
+ /** The loops of the family of `m`, each closed with a straight piece as Skia closes a filled path. */
1371
+ function loopsOf(m) {
1372
+ const out = [];
1373
+ const close = (loop) => {
1374
+ const [first, last] = [loop[0], loop.at(-1)];
1375
+ if (first === undefined || last === undefined)
1376
+ return;
1377
+ if (!same(last[3], first[0], 1e-6))
1378
+ loop.push(lineCubic(last[3], first[0]));
1379
+ out.push(loop);
1380
+ };
1381
+ for (const member of m.getFamily()) {
1382
+ let loop = [];
1383
+ for (const c of cubics(member.getPoints())) {
1384
+ if (c.every((p) => same(p, c[0], 0)))
1385
+ continue;
1386
+ const last = loop.at(-1);
1387
+ if (last !== undefined && !same(last[3], c[0], 1e-6)) {
1388
+ close(loop);
1389
+ loop = [];
1390
+ }
1391
+ loop.push(c);
1392
+ }
1393
+ close(loop);
1394
+ }
1395
+ return out;
1396
+ }
1397
+ /** The real roots of `a t² + b t + c`. */
1398
+ function quadraticRoots(a, b, c) {
1399
+ if (Math.abs(a) < 1e-12)
1400
+ return Math.abs(b) < 1e-12 ? [] : [-c / b];
1401
+ const d = b * b - 4 * a * c;
1402
+ if (d < 0)
1403
+ return [];
1404
+ const s = Math.sqrt(d);
1405
+ return [(-b - s) / (2 * a), (-b + s) / (2 * a)];
1406
+ }
1407
+ /** The parameter ranges of `c` where its `y` only rises or only falls. */
1408
+ function yMonotonic(c) {
1409
+ const [a, b, d] = [c[1][1] - c[0][1], c[2][1] - c[1][1], c[3][1] - c[2][1]];
1410
+ const roots = quadraticRoots(a - 2 * b + d, 2 * (b - a), a).filter((t) => t > 0 && t < 1);
1411
+ const ts = [0, ...roots.toSorted((x, y) => x - y), 1];
1412
+ return ts.slice(1).map((t, i) => [ts[i] ?? 0, t]);
1413
+ }
1414
+ /** Non-zero inside test of `p` in the loops, as Skia and the renderer fill. */
1415
+ function insideLoops(p, loops) {
1416
+ let winding = 0;
1417
+ for (const loop of loops)
1418
+ for (const c of loop)
1419
+ for (const [t0, t1] of yMonotonic(c)) {
1420
+ const [y0, y1] = [cubicAt(c, t0)[1], cubicAt(c, t1)[1]];
1421
+ if (y0 > p[1] === y1 > p[1])
1422
+ continue;
1423
+ let [lo, hi] = [t0, t1];
1424
+ for (let i = 0; i < 60; i++) {
1425
+ const mid = (lo + hi) / 2;
1426
+ if (cubicAt(c, mid)[1] > p[1] === y0 > p[1])
1427
+ lo = mid;
1428
+ else
1429
+ hi = mid;
1430
+ }
1431
+ if (cubicAt(c, (lo + hi) / 2)[0] > p[0])
1432
+ winding += y1 > y0 ? 1 : -1;
1433
+ }
1434
+ return winding !== 0;
1435
+ }
1436
+ function bezierDerivative(c, t) {
1437
+ const u = 1 - t;
1438
+ const [a, b, d] = [sub(c[1], c[0]), sub(c[2], c[1]), sub(c[3], c[2])];
1439
+ return add(add(mul(a, 3 * u * u), mul(b, 6 * u * t)), mul(d, 3 * t * t));
1440
+ }
1441
+ function flat(c) {
1442
+ const v = sub(c[3], c[0]);
1443
+ const n = norm(v);
1444
+ const off = (q) => (n === 0 ? norm(sub(q, c[0])) : Math.abs(cross(v, sub(q, c[0]))) / n);
1445
+ return Math.max(off(c[1]), off(c[2])) < 1e-9;
1446
+ }
1447
+ function boxesMeet(a, b) {
1448
+ for (const k of [0, 1]) {
1449
+ const [as, bs] = [a.map((p) => p[k]), b.map((p) => p[k])];
1450
+ if (Math.min(...as) > Math.max(...bs) + 1e-9 || Math.min(...bs) > Math.max(...as) + 1e-9)
1451
+ return false;
1452
+ }
1453
+ return true;
1454
+ }
1455
+ /** The crossings of two cubics: subdivision down to flat pieces, then Newton steps on the curves. */
1456
+ function crossings(a, b) {
1457
+ const rough = [];
1458
+ const go = (pa, ta, pb, tb, depth) => {
1459
+ if (!boxesMeet(pa, pb))
1460
+ return;
1461
+ const [fa, fb] = [flat(pa), flat(pb)];
1462
+ if ((fa && fb) || depth > 48) {
1463
+ const [r, s] = [sub(pa[3], pa[0]), sub(pb[3], pb[0])];
1464
+ const den = cross(r, s);
1465
+ if (Math.abs(den) <= 1e-12 * norm(r) * norm(s)) {
1466
+ // Two straight curves on one line cut each other at the ends of their common part.
1467
+ if (depth > 0 || Math.abs(cross(r, sub(pb[0], pa[0]))) > 1e-9 * norm(r))
1468
+ return;
1469
+ const on = (q, from, v) => dot(sub(q, from), v) / dot(v, v);
1470
+ const commonEnds = [
1471
+ { t: on(pb[0], pa[0], r), u: 0 },
1472
+ { t: on(pb[3], pa[0], r), u: 1 },
1473
+ { t: 0, u: on(pa[0], pb[0], s) },
1474
+ { t: 1, u: on(pa[3], pb[0], s) },
1475
+ ];
1476
+ rough.push(...commonEnds.filter((h) => h.t >= 0 && h.t <= 1 && h.u >= 0 && h.u <= 1));
1477
+ return;
1478
+ }
1479
+ const t = cross(sub(pb[0], pa[0]), s) / den;
1480
+ const u = cross(sub(pb[0], pa[0]), r) / den;
1481
+ if (t < -1e-9 || t > 1 + 1e-9 || u < -1e-9 || u > 1 + 1e-9)
1482
+ return;
1483
+ rough.push({ t: ta[0] + (ta[1] - ta[0]) * clip01(t), u: tb[0] + (tb[1] - tb[0]) * clip01(u) });
1484
+ return;
1485
+ }
1486
+ const halves = (c, ts, isFlat) => {
1487
+ if (isFlat)
1488
+ return [[c, ts]];
1489
+ const half = (ts[0] + ts[1]) / 2;
1490
+ return [
1491
+ [cubicPart(c, 0, 0.5), [ts[0], half]],
1492
+ [cubicPart(c, 0.5, 1), [half, ts[1]]],
1493
+ ];
1494
+ };
1495
+ for (const [ca, ra] of halves(pa, ta, fa))
1496
+ for (const [cb, rb] of halves(pb, tb, fb))
1497
+ go(ca, ra, cb, rb, depth + 1);
1498
+ };
1499
+ go(a, [0, 1], b, [0, 1], 0);
1500
+ const hits = [];
1501
+ for (let { t, u } of rough) {
1502
+ for (let i = 0; i < 8; i++) {
1503
+ const f = sub(cubicAt(a, t), cubicAt(b, u));
1504
+ const [da, db] = [bezierDerivative(a, t), bezierDerivative(b, u)];
1505
+ const det = -cross(da, db);
1506
+ if (Math.abs(det) < 1e-14)
1507
+ break;
1508
+ const [nt, nu] = [clip01(t + cross(f, db) / det), clip01(u - cross(da, f) / det)];
1509
+ if (norm(sub(cubicAt(a, nt), cubicAt(b, nu))) > norm(f))
1510
+ break;
1511
+ [t, u] = [nt, nu];
1512
+ }
1513
+ const p = lerp(cubicAt(a, t), cubicAt(b, u), 0.5);
1514
+ if (!hits.some((h) => same(h.p, p, 1e-7)))
1515
+ hits.push({ t, u, p });
1516
+ }
1517
+ return hits;
1518
+ }
1519
+ /** The pieces of `c` between its cuts; each cut point ends one piece and starts the next. */
1520
+ function cutCubic(c, cuts) {
1521
+ const inner = cuts.filter((k) => k.t > 1e-9 && k.t < 1 - 1e-9).toSorted((x, y) => x.t - y.t);
1522
+ const stops = [{ t: 0, p: c[0] }];
1523
+ for (const k of inner)
1524
+ if (k.t - (stops.at(-1)?.t ?? 0) > 1e-9)
1525
+ stops.push(k);
1526
+ stops.push({ t: 1, p: c[3] });
1527
+ return stops.slice(1).map((end, i) => {
1528
+ const start = stops[i] ?? end;
1529
+ const part = cubicPart(c, start.t, end.t);
1530
+ return [start.p, part[1], part[2], end.p];
1531
+ });
1532
+ }
1533
+ /** The curves of both shapes, cut where they cross. */
1534
+ function cutAll(la, lb) {
1535
+ const [ca, cb] = [la.flat(), lb.flat()];
1536
+ const cutsA = ca.map(() => []);
1537
+ const cutsB = cb.map(() => []);
1538
+ ca.forEach((a, i) => {
1539
+ cb.forEach((b, j) => {
1540
+ for (const h of crossings(a, b)) {
1541
+ cutsA[i]?.push({ t: h.t, p: h.p });
1542
+ cutsB[j]?.push({ t: h.u, p: h.p });
1543
+ }
1544
+ });
1545
+ });
1546
+ return [ca.flatMap((c, i) => cutCubic(c, cutsA[i] ?? [])), cb.flatMap((c, i) => cutCubic(c, cutsB[i] ?? []))];
1547
+ }
1548
+ /** Where the curve heads at its start or end: the first handle that is not on the anchor. */
1549
+ function heading(c, atEnd) {
1550
+ const ds = atEnd
1551
+ ? [sub(c[3], c[2]), sub(c[3], c[1]), sub(c[3], c[0])]
1552
+ : [sub(c[1], c[0]), sub(c[2], c[0]), sub(c[3], c[0])];
1553
+ return ds.find((d) => norm(d) > 1e-12) ?? [1, 0];
1554
+ }
1555
+ /** The turn from heading `into` to heading `out`, counter-clockwise positive. */
1556
+ function turnAngle(into, out) {
1557
+ return Math.atan2(cross(into, out), dot(into, out));
1558
+ }
1559
+ /** Two straight pieces in a row on one line become one, as Skia writes them. */
1560
+ function mergeLines(loop) {
1561
+ const inLine = (a, b) => isStraight(a) && isStraight(b) && Math.abs(cross(unit(sub(a[3], a[0])), unit(sub(b[3], b[0])))) < 1e-9;
1562
+ const out = [];
1563
+ for (const c of loop) {
1564
+ const last = out.at(-1);
1565
+ if (last !== undefined && inLine(last, c))
1566
+ out[out.length - 1] = lineCubic(last[0], c[3]);
1567
+ else
1568
+ out.push(c);
1569
+ }
1570
+ const [first, last] = [out[0], out.at(-1)];
1571
+ if (out.length > 2 && first !== undefined && last !== undefined && inLine(last, first))
1572
+ return [lineCubic(last[0], first[3]), ...out.slice(1, -1)];
1573
+ return out;
1574
+ }
1575
+ /** The kept pieces, each with the result on its left, joined into closed loops. At a point
1576
+ * where loops touch, each loop takes the piece that turns most to the left, so the loops stay
1577
+ * apart. The outer loops turn counter-clockwise and the holes clockwise, so the even-odd fill
1578
+ * and the non-zero fill agree. */
1579
+ function joinLoops(pieces) {
1580
+ const used = new Set();
1581
+ const found = [];
1582
+ pieces.forEach((first, i) => {
1583
+ if (used.has(i))
1584
+ return;
1585
+ used.add(i);
1586
+ const loop = [first];
1587
+ for (;;) {
1588
+ const last = loop.at(-1) ?? first;
1589
+ const into = heading(last, true);
1590
+ let [best, bestTurn] = [-1, -Infinity];
1591
+ pieces.forEach((c, k) => {
1592
+ if (used.has(k) || !same(c[0], last[3], 1e-6))
1593
+ return;
1594
+ const t = turnAngle(into, heading(c, false));
1595
+ if (t > bestTurn)
1596
+ [best, bestTurn] = [k, t];
1597
+ });
1598
+ const closing = same(first[0], last[3], 1e-6);
1599
+ if (closing && turnAngle(into, heading(first, false)) >= bestTurn) {
1600
+ loop[loop.length - 1] = [last[0], last[1], last[2], first[0]];
1601
+ break;
1602
+ }
1603
+ const next = pieces[best];
1604
+ if (next === undefined)
1605
+ break;
1606
+ used.add(best);
1607
+ loop.push([last[3], next[1], next[2], next[3]]);
1608
+ }
1609
+ found.push(mergeLines(loop));
1610
+ });
1611
+ return found.flat(2);
1612
+ }
1613
+ /** The boundary of the result, as Skia's path operations make it: the curves of `a` and `b`
1614
+ * cut where they cross. A piece is kept when the result is on one side of it and not on the
1615
+ * other, and it is turned so that the result is on its left. A piece that both shapes have
1616
+ * is kept one time. */
1617
+ function boolean(label, a, b, op) {
1618
+ const [la, lb] = [loopsOf(a), loopsOf(b)];
1619
+ if (la.length === 0 || lb.length === 0)
1620
+ wrong(label, "each Mobject needs a closed path");
1621
+ const [pa, pb] = cutAll(la, lb);
1622
+ const kept = [];
1623
+ for (const c of [...pa, ...pb]) {
1624
+ const p = cubicAt(c, 0.5);
1625
+ const left = mul(rotated(unit(bezierDerivative(c, 0.5)), PI / 2), 1e-6);
1626
+ const inResult = (q) => op(insideLoops(q, la), insideLoops(q, lb));
1627
+ const [onLeft, onRight] = [inResult(add(p, left)), inResult(sub(p, left))];
1628
+ if (onLeft === onRight)
1629
+ continue;
1630
+ const piece = onLeft ? c : reversed(c);
1631
+ const twin = (k) => same(k[0], piece[0], 1e-7) && same(k[3], piece[3], 1e-7) && same(cubicAt(k, 0.5), p, 1e-7);
1632
+ if (!kept.some(twin))
1633
+ kept.push(piece);
1634
+ }
1635
+ return joinLoops(kept);
1636
+ }
1637
+ function fold(label, ms, op, style) {
1638
+ if (ms.length < 2)
1639
+ wrong(label, `${label} needs at least 2 Mobjects`);
1640
+ const [first, ...rest] = ms;
1641
+ let acc = first ?? wrong(label, "no Mobject");
1642
+ for (const m of rest)
1643
+ acc = wrap(pathNode(boolean(label, acc, m, op)));
1644
+ return styled(acc, style);
1645
+ }
1646
+ /** The area inside any of the mobjects (Manim `Union`): `Union(a, b, opts)`. */
1647
+ export function Union(...args) {
1648
+ const [ms, style] = split(args);
1649
+ return fold("Union", ms, (inA, inB) => inA || inB, style ?? {});
1650
+ }
1651
+ /** The area inside all the mobjects (Manim `Intersection`). */
1652
+ export function Intersection(...args) {
1653
+ const [ms, style] = split(args);
1654
+ return fold("Intersection", ms, (inA, inB) => inA && inB, style ?? {});
1655
+ }
1656
+ /** The area of `subject` outside `clip` (Manim `Difference`). */
1657
+ export function Difference(subject, clip, opts = {}) {
1658
+ return fold("Difference", [subject, clip], (inA, inB) => inA && !inB, opts);
1659
+ }
1660
+ /** The area inside one of the two, not both (Manim `Exclusion`). */
1661
+ export function Exclusion(subject, clip, opts = {}) {
1662
+ return fold("Exclusion", [subject, clip], (inA, inB) => inA !== inB, opts);
1663
+ }
1664
+ /** A curve: Manim's `ParametricFunction`. */
1665
+ export class ParametricFunctionMobject extends Mobject {
1666
+ function = () => ORIGIN;
1667
+ copy() {
1668
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- every subclass takes one handle
1669
+ const make = this.constructor;
1670
+ const c = new make(raw(this).copy());
1671
+ c.function = this.function;
1672
+ return c;
1673
+ }
1674
+ getFunction() {
1675
+ return this.function;
1676
+ }
1677
+ getPointFromFunction(t) {
1678
+ return this.function(t);
1679
+ }
1680
+ }
1681
+ function samplePaths(f, range, o) {
1682
+ const [min, max, step = 0.01] = range;
1683
+ const { scaling, dt = 1e-8, discontinuities, useSmoothing = true } = o;
1684
+ const scale = (v) => (scaling === undefined ? v : scaling.function(v));
1685
+ const cuts = (discontinuities ?? []).filter((t) => min <= t && t <= max);
1686
+ const edges = [min, max, ...cuts.map((t) => t - dt), ...cuts.map((t) => t + dt)].toSorted((a, b) => a - b);
1687
+ const lines = [];
1688
+ for (let i = 0; i + 1 < edges.length; i += 2) {
1689
+ const [t1, t2] = [edges[i] ?? min, edges[i + 1] ?? max];
1690
+ const ts = [];
1691
+ for (let t = t1; t < t2; t += step)
1692
+ ts.push(scale(t));
1693
+ ts.push(scale(t2));
1694
+ lines.push(ts.map(f));
1695
+ }
1696
+ return useSmoothing ? smoothPaths(lines) : lines.flatMap(corners);
1697
+ }
1698
+ /** The curve of `function(t)` for `t` in `tRange` (Manim `ParametricFunction`). */
1699
+ export function ParametricFunction(fn, opts = {}) {
1700
+ const { tRange = [0, 1], scaling, dt, discontinuities, useSmoothing, ...style } = opts;
1701
+ const m = new ParametricFunctionMobject(pathNode(samplePaths(fn, tRange, {
1702
+ ...(scaling === undefined ? {} : { scaling }),
1703
+ ...(dt === undefined ? {} : { dt }),
1704
+ ...(discontinuities === undefined ? {} : { discontinuities }),
1705
+ ...(useSmoothing === undefined ? {} : { useSmoothing }),
1706
+ })));
1707
+ m.function = fn;
1708
+ return styled(m, style);
1709
+ }
1710
+ /** The graph of `y = function(x)`: Manim's `FunctionGraph`. */
1711
+ export class FunctionGraphMobject extends Mobject {
1712
+ function = () => 0;
1713
+ copy() {
1714
+ const c = new FunctionGraphMobject(raw(this).copy());
1715
+ c.function = this.function;
1716
+ return c;
1717
+ }
1718
+ /** The function `x => y` (Manim `get_function`). */
1719
+ getFunction() {
1720
+ return this.function;
1721
+ }
1722
+ /** `[x, function(x)]` (Manim `get_point_from_function`). */
1723
+ getPointFromFunction(x) {
1724
+ return [x, this.function(x)];
1725
+ }
1726
+ }
1727
+ /** The graph of `function` over `xRange` (Manim `FunctionGraph`): the frame's width by default. */
1728
+ export function FunctionGraph(fn, opts = {}) {
1729
+ const { xRange = [-FRAME_WIDTH / 2, FRAME_WIDTH / 2], color = PURE_YELLOW, scaling, dt, discontinuities, useSmoothing, ...style } = opts;
1730
+ const f = (x) => [x, fn(x)];
1731
+ const m = new FunctionGraphMobject(pathNode(samplePaths(f, xRange, {
1732
+ ...(scaling === undefined ? {} : { scaling }),
1733
+ ...(dt === undefined ? {} : { dt }),
1734
+ ...(discontinuities === undefined ? {} : { discontinuities }),
1735
+ ...(useSmoothing === undefined ? {} : { useSmoothing }),
1736
+ })));
1737
+ m.function = fn;
1738
+ return styled(m, { color, ...style });
1739
+ }
1740
+ /** The curves where `func(x, y) = 0` (Manim `ImplicitFunction`), found on a grid of
1741
+ * `2 ** minDepth` cells for each side (at most `maxQuads` cells). */
1742
+ export function ImplicitFunction(func, opts = {}) {
1743
+ const { xRange = [-FRAME_WIDTH / 2, FRAME_WIDTH / 2], yRange = [-FRAME_HEIGHT / 2, FRAME_HEIGHT / 2], minDepth = 5, maxQuads = 1500, useSmoothing = true, ...style } = opts;
1744
+ const n = Math.max(2, Math.min(2 ** minDepth, Math.floor(Math.sqrt(maxQuads))));
1745
+ const [x0, x1] = xRange;
1746
+ const [y0, y1] = yRange;
1747
+ const px = (i) => x0 + ((x1 - x0) * i) / n;
1748
+ const py = (j) => y0 + ((y1 - y0) * j) / n;
1749
+ const v = Array.from({ length: n + 1 }, (_, i) => Array.from({ length: n + 1 }, (_unused, j) => func(px(i), py(j))));
1750
+ const value = (i, j) => v[i]?.[j] ?? 0;
1751
+ // A point on each grid edge where the sign changes.
1752
+ const edgePoint = (edge) => {
1753
+ const [kind, si, sj] = edge.split(",");
1754
+ const [i, j] = [Number(si), Number(sj)];
1755
+ const [a, b] = kind === "h"
1756
+ ? [
1757
+ [i, j],
1758
+ [i + 1, j],
1759
+ ]
1760
+ : [
1761
+ [i, j],
1762
+ [i, j + 1],
1763
+ ];
1764
+ const [fa, fb] = [value(...a), value(...b)];
1765
+ const t = fa === fb ? 0.5 : fa / (fa - fb);
1766
+ return [px(a[0] + (b[0] - a[0]) * t), py(a[1] + (b[1] - a[1]) * t)];
1767
+ };
1768
+ const links = new Map();
1769
+ const link = (a, b) => {
1770
+ links.set(a, [...(links.get(a) ?? []), b]);
1771
+ links.set(b, [...(links.get(b) ?? []), a]);
1772
+ };
1773
+ for (let i = 0; i < n; i++) {
1774
+ for (let j = 0; j < n; j++) {
1775
+ const s = [value(i, j), value(i + 1, j), value(i + 1, j + 1), value(i, j + 1)].map((x) => x > 0);
1776
+ const edges = [`h,${i},${j}`, `v,${i + 1},${j}`, `h,${i},${j + 1}`, `v,${i},${j}`];
1777
+ const crossing = edges.filter((_, k) => s[k] !== s[(k + 1) % 4]);
1778
+ if (crossing.length === 2)
1779
+ link(crossing[0] ?? "", crossing[1] ?? "");
1780
+ if (crossing.length === 4) {
1781
+ const center = func(px(i + 0.5), py(j + 0.5)) > 0;
1782
+ const [e0, e1, e2, e3] = edges;
1783
+ if (center === s[0]) {
1784
+ link(e0 ?? "", e1 ?? "");
1785
+ link(e2 ?? "", e3 ?? "");
1786
+ }
1787
+ else {
1788
+ link(e3 ?? "", e0 ?? "");
1789
+ link(e1 ?? "", e2 ?? "");
1790
+ }
1791
+ }
1792
+ }
1793
+ }
1794
+ const seen = new Set();
1795
+ const lines = [];
1796
+ const walk = (from) => {
1797
+ const out = [from];
1798
+ seen.add(from);
1799
+ let cur = from;
1800
+ for (;;) {
1801
+ const next = (links.get(cur) ?? []).find((k) => !seen.has(k));
1802
+ if (next === undefined)
1803
+ break;
1804
+ seen.add(next);
1805
+ out.push(next);
1806
+ cur = next;
1807
+ }
1808
+ return out;
1809
+ };
1810
+ const tails = [...links.keys()].filter((k) => (links.get(k) ?? []).length === 1);
1811
+ for (const k of [...tails, ...links.keys()]) {
1812
+ if (seen.has(k))
1813
+ continue;
1814
+ const chain = walk(k);
1815
+ const closed = (links.get(chain.at(-1) ?? "") ?? []).includes(k) && chain.length > 2;
1816
+ const pts = chain.map(edgePoint);
1817
+ lines.push(closed ? [...pts, pts[0] ?? ORIGIN] : pts);
1818
+ }
1819
+ const ps = useSmoothing ? smoothPaths(lines) : lines.flatMap(corners);
1820
+ return styled(wrap(pathNode(ps)), style);
1821
+ }