@motionscript/plot 0.0.0-stage → 0.1.0-alpha.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 (102) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +201 -0
  3. package/dist/browser/chunks/chunk-RCFWYW6O.js +2 -0
  4. package/dist/browser/chunks/chunk-RCFWYW6O.js.map +7 -0
  5. package/dist/browser/index.js +84 -0
  6. package/dist/browser/index.js.map +7 -0
  7. package/dist/browser/kit.js +2 -0
  8. package/dist/browser/kit.js.map +7 -0
  9. package/dist/browser/manifest.json +12 -0
  10. package/dist/engine.d.ts +14 -0
  11. package/dist/engine.d.ts.map +1 -0
  12. package/dist/engine.js +14 -0
  13. package/dist/engine.js.map +1 -0
  14. package/dist/graph2d/curve-cache.d.ts +60 -0
  15. package/dist/graph2d/curve-cache.d.ts.map +1 -0
  16. package/dist/graph2d/curve-cache.js +79 -0
  17. package/dist/graph2d/curve-cache.js.map +1 -0
  18. package/dist/graph2d/curve-error.d.ts +12 -0
  19. package/dist/graph2d/curve-error.d.ts.map +1 -0
  20. package/dist/graph2d/curve-error.js +15 -0
  21. package/dist/graph2d/curve-error.js.map +1 -0
  22. package/dist/graph2d/curve.d.ts +104 -0
  23. package/dist/graph2d/curve.d.ts.map +1 -0
  24. package/dist/graph2d/curve.js +531 -0
  25. package/dist/graph2d/curve.js.map +1 -0
  26. package/dist/graph2d/graph2d.d.ts +164 -0
  27. package/dist/graph2d/graph2d.d.ts.map +1 -0
  28. package/dist/graph2d/graph2d.js +404 -0
  29. package/dist/graph2d/graph2d.js.map +1 -0
  30. package/dist/graph2d/index.d.ts +32 -0
  31. package/dist/graph2d/index.d.ts.map +1 -0
  32. package/dist/graph2d/index.js +32 -0
  33. package/dist/graph2d/index.js.map +1 -0
  34. package/dist/graph2d/plane-fill.d.ts +110 -0
  35. package/dist/graph2d/plane-fill.d.ts.map +1 -0
  36. package/dist/graph2d/plane-fill.js +248 -0
  37. package/dist/graph2d/plane-fill.js.map +1 -0
  38. package/dist/graph2d/plane.d.ts +179 -0
  39. package/dist/graph2d/plane.d.ts.map +1 -0
  40. package/dist/graph2d/plane.js +359 -0
  41. package/dist/graph2d/plane.js.map +1 -0
  42. package/dist/graph2d/shared.d.ts +40 -0
  43. package/dist/graph2d/shared.d.ts.map +1 -0
  44. package/dist/graph2d/shared.js +70 -0
  45. package/dist/graph2d/shared.js.map +1 -0
  46. package/dist/graph3d/expression.d.ts +30 -0
  47. package/dist/graph3d/expression.d.ts.map +1 -0
  48. package/dist/graph3d/expression.js +35 -0
  49. package/dist/graph3d/expression.js.map +1 -0
  50. package/dist/graph3d/graph3d.d.ts +186 -0
  51. package/dist/graph3d/graph3d.d.ts.map +1 -0
  52. package/dist/graph3d/graph3d.js +404 -0
  53. package/dist/graph3d/graph3d.js.map +1 -0
  54. package/dist/graph3d/index.d.ts +22 -0
  55. package/dist/graph3d/index.d.ts.map +1 -0
  56. package/dist/graph3d/index.js +22 -0
  57. package/dist/graph3d/index.js.map +1 -0
  58. package/dist/graph3d/shared.d.ts +61 -0
  59. package/dist/graph3d/shared.d.ts.map +1 -0
  60. package/dist/graph3d/shared.js +101 -0
  61. package/dist/graph3d/shared.js.map +1 -0
  62. package/dist/index.d.ts +4 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +4 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/kit/equations.d.ts +56 -0
  67. package/dist/kit/equations.d.ts.map +1 -0
  68. package/dist/kit/equations.js +63 -0
  69. package/dist/kit/equations.js.map +1 -0
  70. package/dist/kit/expression.d.ts +60 -0
  71. package/dist/kit/expression.d.ts.map +1 -0
  72. package/dist/kit/expression.js +268 -0
  73. package/dist/kit/expression.js.map +1 -0
  74. package/dist/kit/index.d.ts +15 -0
  75. package/dist/kit/index.d.ts.map +1 -0
  76. package/dist/kit/index.js +13 -0
  77. package/dist/kit/index.js.map +1 -0
  78. package/dist/nodes.d.ts +19 -0
  79. package/dist/nodes.d.ts.map +1 -0
  80. package/dist/nodes.js +19 -0
  81. package/dist/nodes.js.map +1 -0
  82. package/package.json +68 -3
  83. package/registry.json +34 -0
  84. package/src/engine.ts +13 -0
  85. package/src/graph2d/curve-cache.ts +103 -0
  86. package/src/graph2d/curve-error.ts +19 -0
  87. package/src/graph2d/curve.ts +657 -0
  88. package/src/graph2d/graph2d.ts +586 -0
  89. package/src/graph2d/index.ts +31 -0
  90. package/src/graph2d/plane-fill.ts +308 -0
  91. package/src/graph2d/plane.ts +457 -0
  92. package/src/graph2d/shared.ts +103 -0
  93. package/src/graph3d/expression.ts +51 -0
  94. package/src/graph3d/graph3d.ts +614 -0
  95. package/src/graph3d/index.ts +21 -0
  96. package/src/graph3d/shared.ts +143 -0
  97. package/src/index.ts +3 -0
  98. package/src/kit/equations.ts +102 -0
  99. package/src/kit/expression.ts +323 -0
  100. package/src/kit/index.ts +29 -0
  101. package/src/nodes.ts +19 -0
  102. package/README.md +0 -4
@@ -0,0 +1,657 @@
1
+ /**
2
+ * Turning `y = f(x)` into polylines you can actually hand a rasterizer.
3
+ *
4
+ * This is the whole difficulty of a 2D grapher, and it is not the sampling loop
5
+ * anybody writes first. That loop — walk the pixel columns, evaluate, skip
6
+ * anything that isn't on screen — fails in four separate ways, and each failure
7
+ * looks like a *different* bug:
8
+ *
9
+ * 1. **Dropping off-view points instead of clipping segments.** If the last
10
+ * point you keep is the last one that landed inside the box, the curve stops
11
+ * in mid-air an arbitrary distance from the edge. `log(x)` appears to end
12
+ * somewhere over the plot rather than plunging out of the bottom of it. The
13
+ * fix is to build the segment anyway and clip *it* against the frame, so the
14
+ * curve leaves through the edge exactly where it really crosses.
15
+ *
16
+ * 2. **Handing the path API astronomical coordinates.** `log(1e-300)` is about
17
+ * -690, which at any sane zoom is millions of pixels below the box. Skia's
18
+ * scan converter is fixed-point, so a coordinate past roughly ±32k overflows
19
+ * and the contour is *silently dropped* — the curve doesn't render wrong, it
20
+ * doesn't render at all. Clipping (1) already bounds what reaches the path
21
+ * API to the frame plus a hair; {@link COORD_LIMIT} bounds the arithmetic on
22
+ * the way there, so no infinity ever reaches the clipper to turn a `t` into a
23
+ * `NaN`.
24
+ *
25
+ * 3. **Sampling uniformly in x.** Near an asymptote one pixel of x is thousands
26
+ * of pixels of y, so a uniform grid gives a visible polygonal kink where the
27
+ * curve turns; far from one, the same grid spends hundreds of samples on a
28
+ * straight line. {@link sampleCurve} subdivides recursively instead — split
29
+ * any segment that is not flat *in screen space*, stop at a quarter pixel —
30
+ * so sample density follows curvature and comes out dense near `x = 0` for
31
+ * `log` and sparse where it is nearly straight. The flatness test pairs a
32
+ * distance check with an **angle** check, because the distance alone reads a
33
+ * symmetric wiggle (whose midpoint sits exactly on the chord) as flat.
34
+ *
35
+ * 4. **Treating "undefined" and "very large" as the same thing.** `log(-1)` is
36
+ * `NaN`: a genuine hole, and the path has to break. `log(1e-300)` is finite
37
+ * and enormous: the curve is still there, still continuous, and has to keep
38
+ * being drawn until it leaves the frame. Conflating the two is the other half
39
+ * of the cut-off in (1). At a defined/undefined edge this bisects to find
40
+ * where the domain actually ends, so `sqrt(x)` terminates at the origin
41
+ * rather than at whichever sample happened to be last.
42
+ *
43
+ * Everything here is pure and works in node-local pixels, so it is testable with
44
+ * no renderer: the caller supplies the graph→pixel mapping and gets back runs of
45
+ * points ready to stroke.
46
+ */
47
+
48
+ import type { Vector2 } from "@motionscript/core"
49
+
50
+ /**
51
+ * The graph→pixel mapping, as four numbers rather than two closures: this is the
52
+ * hot path (a few thousand projections per curve per frame) and the closures
53
+ * would be called through a megamorphic call site.
54
+ *
55
+ * Pixels are the node's own local space — origin at the node's centre, y **up**,
56
+ * which is both the space `Graphics` draws in and, conveniently, the orientation
57
+ * a graph is thought about in.
58
+ */
59
+ export interface PlaneMap {
60
+ /** Graph x at the node's horizontal centre. */
61
+ centerX: number
62
+ /** Graph y at the node's vertical centre. */
63
+ centerY: number
64
+ /** Pixels per graph unit along x. */
65
+ scaleX: number
66
+ /** Pixels per graph unit along y. */
67
+ scaleY: number
68
+ }
69
+
70
+ /** An axis-aligned rectangle in node-local pixels, y-up. */
71
+ export interface PixelRect {
72
+ left: number
73
+ right: number
74
+ bottom: number
75
+ top: number
76
+ }
77
+
78
+ /**
79
+ * Hard bound on a projected coordinate, in node pixels.
80
+ *
81
+ * Not a rendering decision — clipping is what decides what the rasterizer sees.
82
+ * This exists so the *arithmetic* between projection and clipping stays finite:
83
+ * `1/x` at 1e-320 projects to something that overflows to `Infinity`, and an
84
+ * `Infinity` in the clipper's `q / p` produces a `NaN` `t` that quietly discards
85
+ * the segment — which would put the cut-off of (1) back in through a side door.
86
+ *
87
+ * Large enough that no clamped point is ever inside a plausible frame (so the
88
+ * clamp can't bend a visible part of the curve), small enough to stay far below
89
+ * the fixed-point limit even after a parent scales the node up.
90
+ */
91
+ const COORD_LIMIT = 16_000
92
+
93
+ /** How far a sample may sit from the chord before the segment is split, in px. */
94
+ const TOLERANCE_PX = 0.25
95
+
96
+ /**
97
+ * How narrow a segment may get before the subdivision stops, in pixels of x.
98
+ *
99
+ * A **pixel** size rather than a recursion depth, and that is the single change
100
+ * that bounds this module's cost. Leaves tile the frame, so however violent the
101
+ * function is the whole tree costs at most `2 · width / MIN_SEGMENT_PX`
102
+ * evaluations — about seven and a half thousand on a 1920-px node, against the
103
+ * million a depth of ten over five hundred seeds allowed. Half a pixel because
104
+ * that is where one more halving cannot move a stroked line by as much as its
105
+ * own antialiasing.
106
+ */
107
+ const MIN_SEGMENT_PX = 0.5
108
+
109
+ /**
110
+ * How far the two halves of a segment may disagree in direction before it is
111
+ * split, in radians (~2.9°).
112
+ *
113
+ * The reason the distance test alone is not enough: a symmetric wiggle puts its
114
+ * midpoint *exactly* on the chord, so the perpendicular distance is zero and a
115
+ * distance-only test declares a visible kink flat. Two tests, and a segment has
116
+ * to pass both.
117
+ */
118
+ const ANGLE_TOLERANCE = 0.05
119
+
120
+ /**
121
+ * Backstop on the recursion depth.
122
+ *
123
+ * {@link MIN_SEGMENT_PX} stops the subdivision first at every box size
124
+ * {@link seedCount} can produce — the deepest is about six levels on an 8000-px
125
+ * node — so this only ever fires if a seed interval somehow came out enormous.
126
+ * It is here so the recursion cannot run away on a stack rather than because any
127
+ * curve needs it.
128
+ */
129
+ const MAX_DEPTH = 12
130
+
131
+ /**
132
+ * Evaluations one curve may spend in one frame.
133
+ *
134
+ * The refinement alone cannot reach this — see {@link MIN_SEGMENT_PX} — so what
135
+ * this really bounds is the boundary bisection, which is logarithmic per domain
136
+ * edge but unbounded in the *number* of edges: `sqrt(sin(1000x))` has hundreds.
137
+ * At roughly a tenth of a microsecond for a compiled expression tree this is
138
+ * about four milliseconds, which is as much of a 60 fps frame as one curve may
139
+ * have to itself.
140
+ */
141
+ const MAX_EVALUATIONS = 40_000
142
+
143
+ /**
144
+ * Evaluations every curve is guaranteed, however many of them there are: the
145
+ * seed pass with room for two levels of refinement over all of it.
146
+ *
147
+ * A graph carrying twenty curves draws all twenty coarsely rather than the first
148
+ * three well and the rest not at all.
149
+ */
150
+ const MIN_EVALUATIONS = 2_048
151
+
152
+ /**
153
+ * Evaluations all the curves on one node share in a frame.
154
+ *
155
+ * Three at their individual ceiling, or the verification harness's six at twenty
156
+ * thousand each — about twelve milliseconds in the worst case, which is the
157
+ * point past which degrading the curves beats dropping the frame.
158
+ */
159
+ const FRAME_EVALUATIONS = 120_000
160
+
161
+ /**
162
+ * How many times a defined/undefined edge is bisected before the curve is cut.
163
+ *
164
+ * Generous because the interesting case is not `sqrt(x)`, where the value at the
165
+ * boundary is finite and a handful of steps land on it. It is `log(x)`, whose
166
+ * boundary value is unbounded: each halving buys a constant amount of extra
167
+ * descent, so terminating early leaves the curve stopping *inside* the frame,
168
+ * which is the exact artefact this module exists to prevent. The loop exits as
169
+ * soon as the defined side has left the frame, so the full count is only ever
170
+ * paid on a boundary that stays on screen.
171
+ */
172
+ const BOUNDARY_STEPS = 60
173
+
174
+ /** Roughly how far apart the initial uniform samples are laid, in pixels. */
175
+ const SEED_SPACING_PX = 8
176
+ const MIN_SEEDS = 64
177
+ const MAX_SEEDS = 512
178
+
179
+ /**
180
+ * Ceiling on the points one curve may emit.
181
+ *
182
+ * Adaptive subdivision is self-limiting on anything anybody plots deliberately;
183
+ * it is not self-limiting on `sin(10000x)`, where every segment genuinely is
184
+ * curved at every scale and the recursion expands to its full width. This is the
185
+ * backstop, and going over it degrades the curve to the resolution already
186
+ * reached rather than dropping it.
187
+ */
188
+ const MAX_POINTS = 24_000
189
+
190
+ /** A `y = f(x)` curve, sampled by {@link sampleCurve}. */
191
+ export type CurveFunction = (x: number) => number
192
+
193
+ /** One evaluation of the curve, projected and classified. */
194
+ interface Sample {
195
+ /**
196
+ * Offset from the view's centre, in graph units — the parameter of record.
197
+ *
198
+ * The sampler walks `t` and not `x` because `px` is then one multiply,
199
+ * `t · scaleX`, instead of a round trip out to `centerX` and back:
200
+ * `x = centerX + t` followed by `(x - centerX) · scaleX` is a literal
201
+ * add-then-subtract through a number whose ulp can be wider than the whole
202
+ * visible window. At `centerX = 1e9` and a span of 1e-6 that round trip leaves
203
+ * eight distinct pixel positions across the screen, and the curve staircases.
204
+ */
205
+ t: number
206
+ /** `centerX + t` — what `f` actually saw, kept for the bisections' float-resolution guards. */
207
+ x: number
208
+ /** Graph y — kept raw, so the sign is readable either side of a pole. */
209
+ y: number
210
+ /** Node-local pixels, clamped to {@link COORD_LIMIT}. */
211
+ px: number
212
+ py: number
213
+ /**
214
+ * Whether there is a point here at all: `false` for `NaN` (outside the
215
+ * function's domain) **and** for `±Infinity` (a pole landed on exactly). Both
216
+ * break the path; what separates them is where the bisection either side
217
+ * converges to, which the caller never has to know.
218
+ */
219
+ ok: boolean
220
+ }
221
+
222
+ function blankSample(): Sample {
223
+ return { t: 0, x: 0, y: 0, px: 0, py: 0, ok: false }
224
+ }
225
+
226
+ /**
227
+ * Reused {@link Sample} storage.
228
+ *
229
+ * Every evaluation used to be a fresh object. Six curves at sixty frames a
230
+ * second is millions of short-lived allocations a second, which is a collector
231
+ * running *through* the animation rather than between takes. The recursion is a
232
+ * depth-first walk over one seed interval and nothing outlives that interval, so
233
+ * the arena hands out slots and the seed loop resets the mark — which makes
234
+ * every allocation after the first frame a field write on an object whose hidden
235
+ * class never changes.
236
+ *
237
+ * Module scope, and therefore not re-entrant. Nothing re-enters: one
238
+ * {@link sampleCurve} runs to completion before the next begins, and an arena
239
+ * per call would allocate the thing it exists to avoid.
240
+ */
241
+ const arena: Sample[] = []
242
+ let arenaMark = 0
243
+
244
+ function takeSample(): Sample {
245
+ const slot = arena[arenaMark]
246
+ if (slot !== undefined) {
247
+ arenaMark++
248
+ return slot
249
+ }
250
+ const fresh = blankSample()
251
+ arena.push(fresh)
252
+ arenaMark++
253
+ return fresh
254
+ }
255
+
256
+ /**
257
+ * A ceiling on curve evaluations, shared by every curve drawn in one frame.
258
+ *
259
+ * Shared rather than per curve because what a frame can afford is a property of
260
+ * the frame: one curve with a pole every three pixels must not be allowed to
261
+ * cost what six ordinary ones do, and six ordinary ones must not each be held to
262
+ * a sixth of the budget when five of them are straight lines. A cheap curve
263
+ * hands its slack to whatever comes after it.
264
+ */
265
+ export interface SampleBudget {
266
+ /** Evaluations left for the curves still to be drawn. */
267
+ remaining: number
268
+ /** How many curves are still to be drawn, this one included. */
269
+ pending: number
270
+ }
271
+
272
+ /** A frame's budget, to be handed to each of `curves` {@link sampleCurve} calls. */
273
+ export function sampleBudget(curves: number): SampleBudget {
274
+ return { remaining: FRAME_EVALUATIONS, pending: Math.max(1, curves) }
275
+ }
276
+
277
+ /**
278
+ * Samples `f` across the x range `clip` covers and returns the polylines to
279
+ * stroke: node-local pixel points, clipped to `clip`, split wherever the curve
280
+ * genuinely stops.
281
+ *
282
+ * `clip` should be the node's box grown by about a stroke width, so a curve
283
+ * running just outside the frame still paints the half of its stroke that falls
284
+ * inside it. Nothing outside that rectangle is returned, which is what keeps the
285
+ * rasterizer's fixed-point limit out of reach — see (2) in the module note.
286
+ */
287
+ export function sampleCurve(
288
+ f: CurveFunction,
289
+ map: PlaneMap,
290
+ clip: PixelRect,
291
+ budget?: SampleBudget
292
+ ): Vector2[][] {
293
+ const pen = new CurvePen(clip)
294
+
295
+ // Sample across the *clip*, not the box: the extra sliver either side is what
296
+ // lets a curve enter the frame already at full stroke width instead of
297
+ // starting with a cap flush against the edge.
298
+ //
299
+ // In offsets from the centre rather than in x — see {@link Sample.t}.
300
+ const tLo = clip.left / map.scaleX
301
+ const tHi = clip.right / map.scaleX
302
+ if (!(tHi > tLo) || !(map.scaleX > 0) || !(map.scaleY > 0)) return []
303
+
304
+ const seeds = seedCount(clip.right - clip.left)
305
+ const step = (tHi - tLo) / seeds
306
+
307
+ // This curve's slice of the frame's evaluations. Bounded above so one curve
308
+ // can't eat the frame, and below so a graph full of them still draws every one.
309
+ const share = budget
310
+ ? Math.min(
311
+ MAX_EVALUATIONS,
312
+ Math.max(
313
+ MIN_EVALUATIONS,
314
+ Math.floor(budget.remaining / Math.max(1, budget.pending))
315
+ )
316
+ )
317
+ : MAX_EVALUATIONS
318
+ let spent = 0
319
+
320
+ const write = (slot: Sample, t: number): Sample => {
321
+ const x = map.centerX + t
322
+ const y = f(x)
323
+ spent++
324
+ const ok = Number.isFinite(y)
325
+ slot.t = t
326
+ slot.x = x
327
+ slot.y = y
328
+ slot.px = clampCoord(t * map.scaleX)
329
+ // A non-finite y has no position; 0 is a placeholder the `ok` flag keeps
330
+ // anyone from reading.
331
+ slot.py = ok ? clampCoord((y - map.centerY) * map.scaleY) : 0
332
+ slot.ok = ok
333
+ return slot
334
+ }
335
+
336
+ const at = (t: number): Sample => write(takeSample(), t)
337
+
338
+ /**
339
+ * The last defined sample on the way from `from` towards `to`, where exactly
340
+ * one of the two is defined.
341
+ *
342
+ * Three exits. Off the frame, because past the edge the only thing further
343
+ * halvings buy is a longer segment that is going to be clipped to the same
344
+ * place anyway — this is the one `log` leaves by, and the reason
345
+ * {@link BOUNDARY_STEPS} is generous. *Converged*, because a boundary whose
346
+ * value is finite stops moving after a handful of steps and `sqrt` was paying
347
+ * for all sixty of them. And float resolution, which nothing reaches.
348
+ */
349
+ const edgeOf = (from: Sample, to: Sample): Sample => {
350
+ let inside = from
351
+ let outsideT = to.t
352
+ for (let i = 0; i < BOUNDARY_STEPS; i++) {
353
+ if (spent >= share) break
354
+ if (offFrame(inside, clip)) break
355
+
356
+ const midT = (inside.t + outsideT) / 2
357
+ if (midT === inside.t || midT === outsideT) break // float resolution
358
+ const mid = at(midT)
359
+ if (!mid.ok) {
360
+ outsideT = midT
361
+ continue
362
+ }
363
+ const settled =
364
+ Math.abs(mid.px - inside.px) < TOLERANCE_PX &&
365
+ Math.abs(mid.py - inside.py) < TOLERANCE_PX
366
+ inside = mid
367
+ if (settled) break
368
+ }
369
+ return inside
370
+ }
371
+
372
+ const emit = (
373
+ a: Sample,
374
+ m: Sample | null,
375
+ b: Sample,
376
+ floored: boolean
377
+ ): void => {
378
+ if (a.ok && b.ok) {
379
+ if (floored && diverges(a, m, b, clip)) {
380
+ pen.break()
381
+ return
382
+ }
383
+ pen.draw(a, b)
384
+ return
385
+ }
386
+ if (a.ok) {
387
+ const edge = edgeOf(a, b)
388
+ if (edge.t !== a.t) pen.draw(a, edge)
389
+ pen.break()
390
+ return
391
+ }
392
+ if (b.ok) {
393
+ pen.break()
394
+ const edge = edgeOf(b, a)
395
+ if (edge.t !== b.t) pen.draw(edge, b)
396
+ else pen.start(b)
397
+ return
398
+ }
399
+ pen.break()
400
+ }
401
+
402
+ const refine = (a: Sample, b: Sample, depth: number): void => {
403
+ // Out of budget, or out of room in the path: draw the chord. Deliberately
404
+ // *not* routed through the pole test — with no midpoint there is nothing to
405
+ // judge by, and a vertical line through an asymptote is an ugly frame where
406
+ // a missing branch is a wrong one.
407
+ if (spent >= share || pen.points >= MAX_POINTS) {
408
+ emit(a, null, b, false)
409
+ return
410
+ }
411
+ const m = at((a.t + b.t) / 2)
412
+ const floored = depth >= MAX_DEPTH || b.px - a.px <= MIN_SEGMENT_PX
413
+ if (floored || flat(a, m, b)) {
414
+ // "Gave up" rather than "settled" is what identifies a pole, which is why
415
+ // the midpoint travels with the verdict — see {@link diverges}.
416
+ emit(a, m, b, floored)
417
+ return
418
+ }
419
+ refine(a, m, depth + 1)
420
+ refine(m, b, depth + 1)
421
+ }
422
+
423
+ // The seed endpoints come from their own pair rather than from the arena:
424
+ // `previous` has to survive the reset that recycles the interval it was the
425
+ // right-hand end of.
426
+ const ends: [Sample, Sample] = [blankSample(), blankSample()]
427
+ let previous = write(ends[0], tLo)
428
+ for (let i = 1; i <= seeds; i++) {
429
+ // Recomputed from the ends rather than accumulated, so rounding can't drift
430
+ // the grid off the right-hand edge over five hundred additions.
431
+ const next = write(ends[i & 1], i === seeds ? tHi : tLo + i * step)
432
+ arenaMark = 0
433
+ refine(previous, next, 0)
434
+ previous = next
435
+ }
436
+ arenaMark = 0
437
+
438
+ if (budget) {
439
+ budget.remaining = Math.max(0, budget.remaining - spent)
440
+ budget.pending = Math.max(0, budget.pending - 1)
441
+ }
442
+
443
+ return pen.finish()
444
+ }
445
+
446
+ /** How many uniform samples to lay down before refining anything. */
447
+ function seedCount(widthPx: number): number {
448
+ const wanted = Math.round(widthPx / SEED_SPACING_PX)
449
+ return Math.min(MAX_SEEDS, Math.max(MIN_SEEDS, wanted))
450
+ }
451
+
452
+ /**
453
+ * Whether the arc `a → m → b` is straight enough, in **screen** space, to draw
454
+ * as one segment.
455
+ *
456
+ * Screen space and not graph space, because what "straight enough" has to mean
457
+ * is "the eye can't tell" — a tolerance in graph units would subdivide a flat
458
+ * line to death when zoomed out and give up mid-curve when zoomed in.
459
+ */
460
+ function flat(a: Sample, m: Sample, b: Sample): boolean {
461
+ // A domain edge somewhere inside: always split, so the bisection that finds it
462
+ // runs on as short an interval as possible.
463
+ if (a.ok !== m.ok || m.ok !== b.ok) return false
464
+ // Nothing defined anywhere across it — there is no curve here to be wrong
465
+ // about, so stop.
466
+ if (!a.ok) return true
467
+
468
+ const dx = b.px - a.px
469
+ const dy = b.py - a.py
470
+ const length = Math.hypot(dx, dy) || 1
471
+ const distance = Math.abs((m.px - a.px) * dy - (m.py - a.py) * dx) / length
472
+ if (distance > TOLERANCE_PX) return false
473
+
474
+ // The second half of the test — see {@link ANGLE_TOLERANCE}.
475
+ const first = Math.atan2(m.py - a.py, m.px - a.px)
476
+ const second = Math.atan2(b.py - m.py, b.px - m.px)
477
+ let turn = Math.abs(first - second)
478
+ if (turn > Math.PI) turn = 2 * Math.PI - turn
479
+ return turn < ANGLE_TOLERANCE
480
+ }
481
+
482
+ /**
483
+ * Whether a segment the sampler had to give up on is an **asymptote** — the one
484
+ * case where drawing nothing beats drawing the chord.
485
+ *
486
+ * Two conditions, and the second is the one this module was missing. The ends
487
+ * must have run off *opposite* edges, which is what a vertical line through the
488
+ * frame looks like. And the curve must actually turn back inside the segment: a
489
+ * midpoint outside the range its own ends span is a pole (`tan` climbs to +∞ on
490
+ * one side of π/2 and arrives from -∞ on the other, so the midpoint is always
491
+ * outside), while a midpoint *between* them is an ordinary steep climb.
492
+ *
493
+ * Leaving the second test out is what cut `log(x)` off in mid-air. Once the y
494
+ * axis is stretched, `log` crosses the whole visible band inside a single leaf;
495
+ * the ends of that leaf are both off the frame, so its neighbours clip away to
496
+ * nothing, and treating the leaf itself as a pole deletes not a gap but the
497
+ * entire crossing — the exact artefact this module exists to prevent, arriving
498
+ * through the door meant to keep it out. `exp`, `x^20` and `1/x` all reach it.
499
+ *
500
+ * A `null` midpoint means the sampler ran out of budget and has nothing to judge
501
+ * by. Draw it: only a curve that has already spent forty thousand evaluations
502
+ * can get here, and a spurious vertical line is the lesser wrong.
503
+ */
504
+ function diverges(
505
+ a: Sample,
506
+ m: Sample | null,
507
+ b: Sample,
508
+ clip: PixelRect
509
+ ): boolean {
510
+ if (!straddles(a, b, clip)) return false
511
+ if (m === null) return false
512
+ if (!m.ok) return true
513
+ return m.y < Math.min(a.y, b.y) || m.y > Math.max(a.y, b.y)
514
+ }
515
+
516
+ /** Whether the two ends have run off *opposite* edges of the frame. */
517
+ function straddles(a: Sample, b: Sample, clip: PixelRect): boolean {
518
+ return (
519
+ (a.py > clip.top && b.py < clip.bottom) ||
520
+ (a.py < clip.bottom && b.py > clip.top)
521
+ )
522
+ }
523
+
524
+ /** Whether a sample has left the frame entirely. */
525
+ function offFrame(sample: Sample, clip: PixelRect): boolean {
526
+ return sample.py > clip.top || sample.py < clip.bottom
527
+ }
528
+
529
+ function clampCoord(value: number): number {
530
+ if (value > COORD_LIMIT) return COORD_LIMIT
531
+ if (value < -COORD_LIMIT) return -COORD_LIMIT
532
+ // `NaN` cannot reach here (the caller checks `ok` first), but a `-0` would
533
+ // print oddly in a test snapshot and costs nothing to normalise.
534
+ return value === 0 ? 0 : value
535
+ }
536
+
537
+ /**
538
+ * Accumulates clipped polylines, one segment at a time.
539
+ *
540
+ * Incremental rather than "collect every point, then clip the polyline" because
541
+ * a curve is built by a recursion that already knows where its breaks are, and
542
+ * because the intermediate list is the thing that would carry the astronomical
543
+ * coordinates this module exists to keep out of the renderer.
544
+ */
545
+ class CurvePen {
546
+ private readonly runs: Vector2[][] = []
547
+ private open: Vector2[] = []
548
+ /** The clipped end of the last drawn segment, for joining the next one to. */
549
+ private cursor: Vector2 | null = null
550
+ /** Points emitted so far, against {@link MAX_POINTS}. */
551
+ points = 0
552
+
553
+ constructor(private readonly clip: PixelRect) {}
554
+
555
+ /** Draws `a → b`, clipped; continues the open run when it joins on. */
556
+ draw(a: Sample, b: Sample): void {
557
+ const segment = clipSegment(a.px, a.py, b.px, b.py, this.clip)
558
+ if (!segment) {
559
+ // Wholly outside the frame: whatever run was open ended at the edge.
560
+ this.break()
561
+ return
562
+ }
563
+ const [start, end] = segment
564
+ if (this.cursor && samePoint(this.cursor, start)) {
565
+ this.push(end)
566
+ } else {
567
+ this.break()
568
+ this.push(start)
569
+ this.push(end)
570
+ }
571
+ this.cursor = end
572
+ }
573
+
574
+ /** Begins a run at `b` without drawing anything into it yet. */
575
+ start(b: Sample): void {
576
+ this.break()
577
+ if (inside(b.px, b.py, this.clip)) {
578
+ this.push({ x: b.px, y: b.py })
579
+ this.cursor = { x: b.px, y: b.py }
580
+ }
581
+ }
582
+
583
+ /** Ends the open run. A run of fewer than two points draws nothing. */
584
+ break(): void {
585
+ if (this.open.length >= 2) this.runs.push(this.open)
586
+ this.open = []
587
+ this.cursor = null
588
+ }
589
+
590
+ finish(): Vector2[][] {
591
+ this.break()
592
+ return this.runs
593
+ }
594
+
595
+ private push(point: Vector2): void {
596
+ this.open.push(point)
597
+ this.points++
598
+ }
599
+ }
600
+
601
+ /** Points within a tenth of a pixel are the same point, for run-joining. */
602
+ function samePoint(a: Vector2, b: Vector2): boolean {
603
+ return Math.abs(a.x - b.x) < 0.1 && Math.abs(a.y - b.y) < 0.1
604
+ }
605
+
606
+ function inside(x: number, y: number, clip: PixelRect): boolean {
607
+ return x >= clip.left && x <= clip.right && y >= clip.bottom && y <= clip.top
608
+ }
609
+
610
+ /**
611
+ * Liang–Barsky clip of one segment against `clip`. Returns the surviving
612
+ * `[start, end]`, or `null` when the segment lies wholly outside.
613
+ *
614
+ * The piece of this module that turns "the curve stops in mid-air" into "the
615
+ * curve leaves through the edge": the off-frame endpoint is kept and the
616
+ * *segment* is cut, rather than the point being discarded and the segment never
617
+ * built.
618
+ */
619
+ function clipSegment(
620
+ ax: number,
621
+ ay: number,
622
+ bx: number,
623
+ by: number,
624
+ clip: PixelRect
625
+ ): [Vector2, Vector2] | null {
626
+ const dx = bx - ax
627
+ const dy = by - ay
628
+ let t0 = 0
629
+ let t1 = 1
630
+
631
+ // Each edge as (p, q): the segment survives where p·t <= q.
632
+ const edges: [number, number][] = [
633
+ [-dx, ax - clip.left],
634
+ [dx, clip.right - ax],
635
+ [-dy, ay - clip.bottom],
636
+ [dy, clip.top - ay],
637
+ ]
638
+ for (const [p, q] of edges) {
639
+ if (p === 0) {
640
+ // Parallel to this edge: outside it means the whole segment is out.
641
+ if (q < 0) return null
642
+ continue
643
+ }
644
+ const r = q / p
645
+ if (p < 0) {
646
+ if (r > t1) return null
647
+ if (r > t0) t0 = r
648
+ } else {
649
+ if (r < t0) return null
650
+ if (r < t1) t1 = r
651
+ }
652
+ }
653
+ return [
654
+ { x: ax + t0 * dx, y: ay + t0 * dy },
655
+ { x: ax + t1 * dx, y: ay + t1 * dy },
656
+ ]
657
+ }