@ac-kit/math-grid 0.3.0 → 0.5.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 (95) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +117 -10
  3. package/dist/_brand.d.ts +14 -0
  4. package/dist/_brand.d.ts.map +1 -0
  5. package/dist/_brand.js +2 -0
  6. package/dist/_brand.js.map +1 -0
  7. package/dist/_coverage-contour2.d.ts +55 -0
  8. package/dist/_coverage-contour2.d.ts.map +1 -0
  9. package/dist/_coverage-contour2.js +2068 -0
  10. package/dist/_coverage-contour2.js.map +1 -0
  11. package/dist/_grid-offsets2.d.ts +15 -0
  12. package/dist/_grid-offsets2.d.ts.map +1 -0
  13. package/dist/_grid-offsets2.js +53 -0
  14. package/dist/_grid-offsets2.js.map +1 -0
  15. package/dist/_nearest-site-propagation2.d.ts +80 -0
  16. package/dist/_nearest-site-propagation2.d.ts.map +1 -0
  17. package/dist/_nearest-site-propagation2.js +707 -0
  18. package/dist/_nearest-site-propagation2.js.map +1 -0
  19. package/dist/breadth-first-grid2.d.ts +65 -0
  20. package/dist/breadth-first-grid2.d.ts.map +1 -0
  21. package/dist/breadth-first-grid2.js +116 -0
  22. package/dist/breadth-first-grid2.js.map +1 -0
  23. package/dist/flood-fill2.d.ts +39 -0
  24. package/dist/flood-fill2.d.ts.map +1 -0
  25. package/dist/flood-fill2.js +76 -0
  26. package/dist/flood-fill2.js.map +1 -0
  27. package/dist/grid-neighbors2.d.ts +45 -0
  28. package/dist/grid-neighbors2.d.ts.map +1 -0
  29. package/dist/grid-neighbors2.js +45 -0
  30. package/dist/grid-neighbors2.js.map +1 -0
  31. package/dist/grid-pack-dfs.d.ts.map +1 -1
  32. package/dist/grid-pack-dfs.js +4 -2
  33. package/dist/grid-pack-dfs.js.map +1 -1
  34. package/dist/index.d.ts +6 -0
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +6 -0
  37. package/dist/index.js.map +1 -1
  38. package/dist/infinite-grid2.js.map +1 -1
  39. package/dist/max-rects-pack.d.ts +90 -0
  40. package/dist/max-rects-pack.d.ts.map +1 -0
  41. package/dist/max-rects-pack.js +310 -0
  42. package/dist/max-rects-pack.js.map +1 -0
  43. package/dist/rasterize-line2.d.ts +33 -0
  44. package/dist/rasterize-line2.d.ts.map +1 -0
  45. package/dist/rasterize-line2.js +103 -0
  46. package/dist/rasterize-line2.js.map +1 -0
  47. package/dist/shelf-allocator.d.ts +7 -1
  48. package/dist/shelf-allocator.d.ts.map +1 -1
  49. package/dist/shelf-allocator.js +32 -32
  50. package/dist/shelf-allocator.js.map +1 -1
  51. package/dist/signed-distance-from-coverage2.d.ts +63 -21
  52. package/dist/signed-distance-from-coverage2.d.ts.map +1 -1
  53. package/dist/signed-distance-from-coverage2.js +327 -99
  54. package/dist/signed-distance-from-coverage2.js.map +1 -1
  55. package/dist/squared-distance-transform2.d.ts +9 -4
  56. package/dist/squared-distance-transform2.d.ts.map +1 -1
  57. package/dist/squared-distance-transform2.js +9 -4
  58. package/dist/squared-distance-transform2.js.map +1 -1
  59. package/dist/tile/_tile-matrix.d.ts +33 -0
  60. package/dist/tile/_tile-matrix.d.ts.map +1 -0
  61. package/dist/tile/_tile-matrix.js +186 -0
  62. package/dist/tile/_tile-matrix.js.map +1 -0
  63. package/dist/tile/index.d.ts +8 -0
  64. package/dist/tile/index.d.ts.map +1 -0
  65. package/dist/tile/index.js +8 -0
  66. package/dist/tile/index.js.map +1 -0
  67. package/dist/tile/quadkey.d.ts +30 -0
  68. package/dist/tile/quadkey.d.ts.map +1 -0
  69. package/dist/tile/quadkey.js +91 -0
  70. package/dist/tile/quadkey.js.map +1 -0
  71. package/dist/tile/tile-address.d.ts +91 -0
  72. package/dist/tile/tile-address.d.ts.map +1 -0
  73. package/dist/tile/tile-address.js +228 -0
  74. package/dist/tile/tile-address.js.map +1 -0
  75. package/dist/tile/tile-index.d.ts +26 -0
  76. package/dist/tile/tile-index.d.ts.map +1 -0
  77. package/dist/tile/tile-index.js +2 -0
  78. package/dist/tile/tile-index.js.map +1 -0
  79. package/dist/tile/tile-level.d.ts +24 -0
  80. package/dist/tile/tile-level.d.ts.map +1 -0
  81. package/dist/tile/tile-level.js +53 -0
  82. package/dist/tile/tile-level.js.map +1 -0
  83. package/dist/tile/tile-matrix-set-json.d.ts +67 -0
  84. package/dist/tile/tile-matrix-set-json.d.ts.map +1 -0
  85. package/dist/tile/tile-matrix-set-json.js +247 -0
  86. package/dist/tile/tile-matrix-set-json.js.map +1 -0
  87. package/dist/tile/tile-matrix-set.d.ts +174 -0
  88. package/dist/tile/tile-matrix-set.d.ts.map +1 -0
  89. package/dist/tile/tile-matrix-set.js +244 -0
  90. package/dist/tile/tile-matrix-set.js.map +1 -0
  91. package/dist/tile/tile-range.d.ts +57 -0
  92. package/dist/tile/tile-range.d.ts.map +1 -0
  93. package/dist/tile/tile-range.js +140 -0
  94. package/dist/tile/tile-range.js.map +1 -0
  95. package/package.json +10 -8
@@ -0,0 +1,2068 @@
1
+ import { line2Create, line2IntersectLine2, line2Set, polygon2Area, polygon2ClipHalfPlane, } from "@ac-kit/math-geometry";
2
+ import { vec2Create } from "@ac-kit/math-linear";
3
+ import { COVERAGE_STRIDE_, SITE_QUERY_, siteDistanceSquared_, } from "./_nearest-site-propagation2.js";
4
+ /**
5
+ * The contour of an antialiased coverage grid, as sites (see
6
+ * {@link COVERAGE_STRIDE_}): each edge texel's straight edge, merged into one
7
+ * segment per straight run of them, and a corner where two runs meet.
8
+ *
9
+ * Cost is linear in the edge texels: the runs grow once from their pieces, and
10
+ * a corner is only tried where two runs end next to each other, so a texel on a
11
+ * straight edge (most of them) costs its piece and one membership test.
12
+ */
13
+ /**
14
+ * The largest coverage error, as a fraction of a texel, of a straight edge's
15
+ * prediction over the 3 × 3 texels around an edge texel for its texel to count
16
+ * as straight: above the curvature of a disc of radius 6, below what a corner
17
+ * inside the window leaves.
18
+ */
19
+ export const STRAIGHT_RESIDUAL_ = 0.1;
20
+ /** Normals of neighbouring pieces of one run differ by at most 10°. */
21
+ const SAME_RUN_COSINE_ = Math.cos((10 * Math.PI) / 180);
22
+ /**
23
+ * The normals of the two runs of a corner differ by at least 20°, and a run's
24
+ * pieces by at most that much from its first: a flatter corner bends its
25
+ * texels' edges too little to need one.
26
+ */
27
+ const CORNER_COSINE_ = Math.cos((20 * Math.PI) / 180);
28
+ /** A run's contour points lie within this many texels of its fitted line. */
29
+ const RUN_TOLERANCE_ = 0.05;
30
+ /**
31
+ * The shortest run, in texels between its extreme contour points: an arc stays
32
+ * within `RUN_TOLERANCE_` of a chord this long only on a circle of radius 10
33
+ * and more.
34
+ */
35
+ const MIN_RUN_SPAN_ = 2;
36
+ /**
37
+ * A corner's vertex lies within this many texels of the near ends of its runs:
38
+ * a 20° tip is too narrow for straight pieces up to about this far from it.
39
+ */
40
+ const VERTEX_REACH_ = 14;
41
+ /**
42
+ * How far, in texels, the search for the run across a corner walks from a run's
43
+ * end through the texels that belong to no run.
44
+ */
45
+ const JUNCTION_REACH_ = 4;
46
+ /**
47
+ * The largest coverage error, as a fraction of a texel, of a corner's
48
+ * prediction over the 3 × 3 texels around the texel holding it and around its
49
+ * vertex.
50
+ */
51
+ const CORNER_RESIDUAL_ = 0.05;
52
+ /**
53
+ * A corner predicting the coverage this closely is one, however gently its
54
+ * texels bend; between this and `CORNER_RESIDUAL_`, a texel next to the vertex
55
+ * must bend by `BENT_RESIDUAL_`, which a smooth curve's do not (a pair of
56
+ * tangents also fits a curve, to about 0.03–0.05).
57
+ */
58
+ const CLEAR_CORNER_RESIDUAL_ = 0.02;
59
+ const BENT_RESIDUAL_ = 0.2;
60
+ /**
61
+ * `sin(θ / 2)` of the widest tip, of opening angle θ = 60°, whose corner may be
62
+ * judged once placed: its runs' crossing moves by more than twice their error
63
+ * across themselves.
64
+ */
65
+ const SHARP_TIP_HALF_SINE_ = 0.5;
66
+ /**
67
+ * How far, in texels, from the texel holding a corner's vertex the corner
68
+ * replaces the other pieces of contour: a straight piece one texel long,
69
+ * centred up to a texel from its own centre, overshoots a vertex up to two
70
+ * texels away.
71
+ */
72
+ const SPREAD_REACH_ = 2;
73
+ /**
74
+ * How far, in texels, from the texel holding a corner's vertex the corner
75
+ * replaces the pieces of antialiased texels it explains: along a narrow tip,
76
+ * whose texels see both edges, about as far as a 20° tip bends them.
77
+ */
78
+ const EDGE_SPREAD_REACH_ = 6;
79
+ /**
80
+ * A piece of contour the corner replaces lies within this many texels of it: it
81
+ * is a stretch of the corner's own edges, sampled less accurately.
82
+ */
83
+ const SPREAD_TOLERANCE_ = 0.25;
84
+ /** A cell's label before its run is decided. */
85
+ const UNASSIGNED_ = -1;
86
+ /** A straight piece that belongs to no run. */
87
+ const LONE_ = -2;
88
+ /**
89
+ * Writes the straight edge of antialiased texel `(x, y)`, of coverage `value`,
90
+ * at `sites[at]` in the `COVERAGE_STRIDE_` layout, and its straight-edge
91
+ * residual over the 3 × 3 neighbourhood into `residuals[cell]`. Interior texels
92
+ * reuse the nine coverage samples already loaded for the Sobel gradient.
93
+ */
94
+ export function locateEdgeAndResidual_(sites, at, coverage, value, x, y, width, height, residuals, cell) {
95
+ sites[at + 3] = Number.NaN;
96
+ sites[at + 4] = 0;
97
+ const border = x === 0 || y === 0 || x === width - 1 || y === height - 1;
98
+ if (border) {
99
+ if (borderStripe_(sites, at, coverage, value, x, y, width, height)) {
100
+ residuals[cell] = Number.NaN;
101
+ return;
102
+ }
103
+ const topLeft = borderSample_(coverage, x, y, -1, -1, width, height, true);
104
+ const top = borderSample_(coverage, x, y, 0, -1, width, height, true);
105
+ const topRight = borderSample_(coverage, x, y, 1, -1, width, height, true);
106
+ const middleLeft = borderSample_(coverage, x, y, -1, 0, width, height, true);
107
+ const middleRight = borderSample_(coverage, x, y, 1, 0, width, height, true);
108
+ const bottomLeft = borderSample_(coverage, x, y, -1, 1, width, height, true);
109
+ const bottom = borderSample_(coverage, x, y, 0, 1, width, height, true);
110
+ const bottomRight = borderSample_(coverage, x, y, 1, 1, width, height, true);
111
+ const gradientX = topRight +
112
+ 2 * middleRight +
113
+ bottomRight -
114
+ topLeft -
115
+ 2 * middleLeft -
116
+ bottomLeft;
117
+ const gradientY = bottomLeft + 2 * bottom + bottomRight - topLeft - 2 * top - topRight;
118
+ const length = Math.sqrt(gradientX * gradientX + gradientY * gradientY);
119
+ if (length === 0) {
120
+ locateStripe_(sites, at, coverage, value, x, y, width, height, middleLeft + middleRight - 2 * value, top + bottom - 2 * value, topLeft + bottomRight - topRight - bottomLeft);
121
+ residuals[cell] = Number.NaN;
122
+ return;
123
+ }
124
+ const normalX = -gradientX / length;
125
+ const normalY = -gradientY / length;
126
+ sites[at] = normalX;
127
+ sites[at + 1] = normalY;
128
+ EDGE_[0] = normalX;
129
+ EDGE_[1] = normalY;
130
+ EDGE_[2] = value / 255;
131
+ edgeOffset_();
132
+ sites[at + 2] = EDGE_[3];
133
+ edgeResidual_(sites, at, coverage, x, y, width, height, residuals, cell);
134
+ return;
135
+ }
136
+ const above = cell - width;
137
+ const below = cell + width;
138
+ const topLeft = coverage[above - 1];
139
+ const top = coverage[above];
140
+ const topRight = coverage[above + 1];
141
+ const middleLeft = coverage[cell - 1];
142
+ const middleRight = coverage[cell + 1];
143
+ const bottomLeft = coverage[below - 1];
144
+ const bottom = coverage[below];
145
+ const bottomRight = coverage[below + 1];
146
+ const gradientX = topRight +
147
+ 2 * middleRight +
148
+ bottomRight -
149
+ topLeft -
150
+ 2 * middleLeft -
151
+ bottomLeft;
152
+ const gradientY = bottomLeft + 2 * bottom + bottomRight - topLeft - 2 * top - topRight;
153
+ const length = Math.sqrt(gradientX * gradientX + gradientY * gradientY);
154
+ if (length === 0) {
155
+ locateStripe_(sites, at, coverage, value, x, y, width, height, middleLeft + middleRight - 2 * value, top + bottom - 2 * value, topLeft + bottomRight - topRight - bottomLeft);
156
+ residuals[cell] = Number.NaN;
157
+ return;
158
+ }
159
+ const normalX = -gradientX / length;
160
+ const normalY = -gradientY / length;
161
+ const absX = normalX < 0 ? -normalX : normalX;
162
+ const absY = normalY < 0 ? -normalY : normalY;
163
+ const a = absX >= absY ? absX : absY;
164
+ const b = absX >= absY ? absY : absX;
165
+ const alpha = value * INV_255_;
166
+ const half = (a + b) * 0.5;
167
+ let offset;
168
+ if (b < 1e-6) {
169
+ offset = a * (alpha - 0.5);
170
+ }
171
+ else if (alpha <= b / (2 * a)) {
172
+ offset = -half + Math.sqrt(2 * a * b * alpha);
173
+ }
174
+ else if (alpha >= 1 - b / (2 * a)) {
175
+ offset = half - Math.sqrt(2 * a * b * (1 - alpha));
176
+ }
177
+ else {
178
+ offset = a * (alpha - 0.5);
179
+ }
180
+ sites[at] = normalX;
181
+ sites[at + 1] = normalY;
182
+ sites[at + 2] = offset;
183
+ // Residual over the 3 × 3 window using the eight samples already in registers
184
+ // (the centre texel's offset was inverted from `alpha`, so its error is 0).
185
+ const mid = (a - b) * 0.5;
186
+ const invA = 1 / a;
187
+ const inv2ab = b >= 1e-6 ? 0.5 / (a * b) : 0;
188
+ let residual = 0;
189
+ let o = offset + normalX + normalY;
190
+ let pred = edgeCovFast_(o, half, mid, invA, inv2ab);
191
+ let diff = pred - topLeft * INV_255_;
192
+ if (diff < 0) {
193
+ diff = -diff;
194
+ }
195
+ if (diff > residual) {
196
+ residual = diff;
197
+ }
198
+ o = offset + normalY;
199
+ pred = edgeCovFast_(o, half, mid, invA, inv2ab);
200
+ diff = pred - top * INV_255_;
201
+ if (diff < 0) {
202
+ diff = -diff;
203
+ }
204
+ if (diff > residual) {
205
+ residual = diff;
206
+ }
207
+ o = offset - normalX + normalY;
208
+ pred = edgeCovFast_(o, half, mid, invA, inv2ab);
209
+ diff = pred - topRight * INV_255_;
210
+ if (diff < 0) {
211
+ diff = -diff;
212
+ }
213
+ if (diff > residual) {
214
+ residual = diff;
215
+ }
216
+ o = offset + normalX;
217
+ pred = edgeCovFast_(o, half, mid, invA, inv2ab);
218
+ diff = pred - middleLeft * INV_255_;
219
+ if (diff < 0) {
220
+ diff = -diff;
221
+ }
222
+ if (diff > residual) {
223
+ residual = diff;
224
+ }
225
+ o = offset - normalX;
226
+ pred = edgeCovFast_(o, half, mid, invA, inv2ab);
227
+ diff = pred - middleRight * INV_255_;
228
+ if (diff < 0) {
229
+ diff = -diff;
230
+ }
231
+ if (diff > residual) {
232
+ residual = diff;
233
+ }
234
+ o = offset + normalX - normalY;
235
+ pred = edgeCovFast_(o, half, mid, invA, inv2ab);
236
+ diff = pred - bottomLeft * INV_255_;
237
+ if (diff < 0) {
238
+ diff = -diff;
239
+ }
240
+ if (diff > residual) {
241
+ residual = diff;
242
+ }
243
+ o = offset - normalY;
244
+ pred = edgeCovFast_(o, half, mid, invA, inv2ab);
245
+ diff = pred - bottom * INV_255_;
246
+ if (diff < 0) {
247
+ diff = -diff;
248
+ }
249
+ if (diff > residual) {
250
+ residual = diff;
251
+ }
252
+ o = offset - normalX - normalY;
253
+ pred = edgeCovFast_(o, half, mid, invA, inv2ab);
254
+ diff = pred - bottomRight * INV_255_;
255
+ if (diff < 0) {
256
+ diff = -diff;
257
+ }
258
+ if (diff > residual) {
259
+ residual = diff;
260
+ }
261
+ residuals[cell] = residual;
262
+ }
263
+ const INV_255_ = 1 / 255;
264
+ function edgeCovFast_(offset, half, mid, invA, inv2ab) {
265
+ if (offset <= -half) {
266
+ return 0;
267
+ }
268
+ if (offset >= half) {
269
+ return 1;
270
+ }
271
+ if (inv2ab !== 0) {
272
+ if (offset < -mid) {
273
+ const t = offset + half;
274
+ return t * t * inv2ab;
275
+ }
276
+ if (offset > mid) {
277
+ const t = half - offset;
278
+ return 1 - t * t * inv2ab;
279
+ }
280
+ }
281
+ return 0.5 + offset * invA;
282
+ }
283
+ /**
284
+ * Writes the straight edge of antialiased texel `(x, y)`, of coverage `value`,
285
+ * at `sites[at]` in the `COVERAGE_STRIDE_` layout.
286
+ */
287
+ export function locateEdge_(sites, at, coverage, value, x, y, width, height) {
288
+ sites[at + 3] = Number.NaN;
289
+ sites[at + 4] = 0;
290
+ // on the border, a centred stripe's missing samples are its own,
291
+ // reflected through the texel's centre; clamping them instead would give
292
+ // it a gradient it does not have, so the stripe is tried first there
293
+ const border = x === 0 || y === 0 || x === width - 1 || y === height - 1;
294
+ if (border &&
295
+ borderStripe_(sites, at, coverage, value, x, y, width, height)) {
296
+ return;
297
+ }
298
+ let topLeft;
299
+ let top;
300
+ let topRight;
301
+ let middleLeft;
302
+ let middleRight;
303
+ let bottomLeft;
304
+ let bottom;
305
+ let bottomRight;
306
+ if (border) {
307
+ // a missing sample continues the texels on the other side linearly
308
+ // (a one-sided difference): clamped, it would bend the gradient
309
+ topLeft = borderSample_(coverage, x, y, -1, -1, width, height, true);
310
+ top = borderSample_(coverage, x, y, 0, -1, width, height, true);
311
+ topRight = borderSample_(coverage, x, y, 1, -1, width, height, true);
312
+ middleLeft = borderSample_(coverage, x, y, -1, 0, width, height, true);
313
+ middleRight = borderSample_(coverage, x, y, 1, 0, width, height, true);
314
+ bottomLeft = borderSample_(coverage, x, y, -1, 1, width, height, true);
315
+ bottom = borderSample_(coverage, x, y, 0, 1, width, height, true);
316
+ bottomRight = borderSample_(coverage, x, y, 1, 1, width, height, true);
317
+ }
318
+ else {
319
+ const above = (y - 1) * width;
320
+ const middle = y * width;
321
+ const below = (y + 1) * width;
322
+ topLeft = coverage[above + x - 1];
323
+ top = coverage[above + x];
324
+ topRight = coverage[above + x + 1];
325
+ middleLeft = coverage[middle + x - 1];
326
+ middleRight = coverage[middle + x + 1];
327
+ bottomLeft = coverage[below + x - 1];
328
+ bottom = coverage[below + x];
329
+ bottomRight = coverage[below + x + 1];
330
+ }
331
+ // the Sobel gradient points toward more coverage; the outward normal is
332
+ // its opposite
333
+ const gradientX = topRight +
334
+ 2 * middleRight +
335
+ bottomRight -
336
+ topLeft -
337
+ 2 * middleLeft -
338
+ bottomLeft;
339
+ const gradientY = bottomLeft + 2 * bottom + bottomRight - topLeft - 2 * top - topRight;
340
+ // not Math.hypot, which the engine's middle tier calls with its doubles
341
+ // boxed
342
+ const length = Math.sqrt(gradientX * gradientX + gradientY * gradientY);
343
+ if (length === 0) {
344
+ locateStripe_(sites, at, coverage, value, x, y, width, height, middleLeft + middleRight - 2 * value, top + bottom - 2 * value, topLeft + bottomRight - topRight - bottomLeft);
345
+ return;
346
+ }
347
+ const normalX = -gradientX / length;
348
+ const normalY = -gradientY / length;
349
+ sites[at] = normalX;
350
+ sites[at + 1] = normalY;
351
+ EDGE_[0] = normalX;
352
+ EDGE_[1] = normalY;
353
+ EDGE_[2] = value / 255;
354
+ edgeOffset_();
355
+ sites[at + 2] = EDGE_[3];
356
+ }
357
+ /**
358
+ * The coverage of the texel `(dx, dy)` from `(x, y)`; outside the grid, from
359
+ * the texel opposite it through `(x, y)`: that texel's own coverage when
360
+ * `extrapolate` is false (a stripe centred on `(x, y)` repeats there), else the
361
+ * linear continuation `2 · c(x, y) − c(opposite)`; `(x, y)`'s own coverage when
362
+ * both are outside.
363
+ */
364
+ function borderSample_(coverage, x, y, dx, dy, width, height, extrapolate) {
365
+ const column = x + dx;
366
+ const row = y + dy;
367
+ if (column >= 0 && column < width && row >= 0 && row < height) {
368
+ return coverage[row * width + column];
369
+ }
370
+ const centre = coverage[y * width + x];
371
+ const oppositeColumn = x - dx;
372
+ const oppositeRow = y - dy;
373
+ if (oppositeColumn < 0 ||
374
+ oppositeColumn >= width ||
375
+ oppositeRow < 0 ||
376
+ oppositeRow >= height) {
377
+ return centre;
378
+ }
379
+ const opposite = coverage[oppositeRow * width + oppositeColumn];
380
+ return extrapolate ? 2 * centre - opposite : opposite;
381
+ }
382
+ /**
383
+ * Tries a stripe for border texel `(x, y)` (see {@link locateStripe_}), its
384
+ * missing samples reflected through its centre; returns whether one fits, as
385
+ * the samples inside the grid tell, its site then written.
386
+ */
387
+ function borderStripe_(sites, at, coverage, value, x, y, width, height) {
388
+ const topLeft = borderSample_(coverage, x, y, -1, -1, width, height, false);
389
+ const top = borderSample_(coverage, x, y, 0, -1, width, height, false);
390
+ const topRight = borderSample_(coverage, x, y, 1, -1, width, height, false);
391
+ const middleLeft = borderSample_(coverage, x, y, -1, 0, width, height, false);
392
+ const middleRight = borderSample_(coverage, x, y, 1, 0, width, height, false);
393
+ const bottomLeft = borderSample_(coverage, x, y, -1, 1, width, height, false);
394
+ const bottom = borderSample_(coverage, x, y, 0, 1, width, height, false);
395
+ const bottomRight = borderSample_(coverage, x, y, 1, 1, width, height, false);
396
+ if (topRight + 2 * middleRight + bottomRight !==
397
+ topLeft + 2 * middleLeft + bottomLeft ||
398
+ bottomLeft + 2 * bottom + bottomRight !== topLeft + 2 * top + topRight) {
399
+ return false;
400
+ }
401
+ locateStripe_(sites, at, coverage, value, x, y, width, height, middleLeft + middleRight - 2 * value, top + bottom - 2 * value, topLeft + bottomRight - topRight - bottomLeft);
402
+ return sites[at + 4] !== 0;
403
+ }
404
+ /**
405
+ * The largest coverage error, as a fraction of a texel, of a stripe's
406
+ * prediction over the texels around its own: a centred stripe of exact area
407
+ * coverage predicts them to the bytes' rounding, and a feature it does not
408
+ * describe (a dot, a crossing) misses by about its own coverage.
409
+ */
410
+ const STRIPE_RESIDUAL_ = 0.02;
411
+ /**
412
+ * The unit normals {@link locateStripe_} tries: the two principal axes of the
413
+ * second differences (written per texel), then the rows, columns and
414
+ * diagonals.
415
+ */
416
+ const STRIPE_NORMALS_ = new Float64Array([
417
+ 0,
418
+ 0,
419
+ 0,
420
+ 0,
421
+ 1,
422
+ 0,
423
+ 0,
424
+ 1,
425
+ Math.SQRT1_2,
426
+ Math.SQRT1_2,
427
+ Math.SQRT1_2,
428
+ -Math.SQRT1_2,
429
+ ]);
430
+ /**
431
+ * Writes the site of antialiased texel `(x, y)`, of coverage `value`, whose 3 ×
432
+ * 3 coverage has no gradient: symmetric about its centre, so that no straight
433
+ * edge crosses it. A stripe through its centre thinner than a texel (a
434
+ * hairline, or a thin gap in ink) is the straight feature that leaves it so: it
435
+ * runs along a principal axis of the coverage's second differences (`xx`, `yy`
436
+ * and four times `xy`, in bytes), and its width follows from the coverage. The
437
+ * stripe is kept, as `(normalX, normalY, halfWidth, NaN, kind)` with `kind` 1
438
+ * for ink between its edges and −1 for a gap, when it predicts the texels
439
+ * around to `STRIPE_RESIDUAL_` and better than a flat field does. Else the
440
+ * coverage determines nothing (a dot, stripes crossing, a uniform field) and
441
+ * the site is the texel's centre, a zero normal.
442
+ */
443
+ function locateStripe_(sites, at, coverage, value, x, y, width, height, xx, yy, xy4) {
444
+ sites[at] = 0;
445
+ sites[at + 1] = 0;
446
+ sites[at + 2] = 0;
447
+ const alpha = value / 255;
448
+ const left = Math.max(0, x - 1);
449
+ const right = Math.min(width - 1, x + 1);
450
+ const top = Math.max(0, y - 1);
451
+ const bottom = Math.min(height - 1, y + 1);
452
+ let best = 0;
453
+ for (let row = top; row <= bottom; row += 1) {
454
+ for (let column = left; column <= right; column += 1) {
455
+ best = Math.max(best, Math.abs(coverage[row * width + column] / 255 - alpha));
456
+ }
457
+ }
458
+ // the principal axis of the larger second difference, `xy` being a
459
+ // quarter of `xy4`; the stripe lies along one axis or the other. The rows,
460
+ // columns and diagonals are tried too: on the border, where samples are
461
+ // missing, the second differences may not tell them
462
+ const angle = Math.atan2(xy4 / 2, xx - yy) / 2;
463
+ STRIPE_NORMALS_[0] = Math.cos(angle);
464
+ STRIPE_NORMALS_[1] = Math.sin(angle);
465
+ STRIPE_NORMALS_[2] = -STRIPE_NORMALS_[1];
466
+ STRIPE_NORMALS_[3] = STRIPE_NORMALS_[0];
467
+ for (let candidate = 0; candidate < 12; candidate += 1) {
468
+ const normalX = STRIPE_NORMALS_[2 * (candidate >> 1)];
469
+ const normalY = STRIPE_NORMALS_[2 * (candidate >> 1) + 1];
470
+ const ink = (candidate & 1) === 0;
471
+ // the stripe covers 2 · E(halfWidth) − 1 of its texel, E the coverage
472
+ // of one edge at that offset; a gap leaves the rest
473
+ EDGE_[0] = normalX;
474
+ EDGE_[1] = normalY;
475
+ EDGE_[2] = ink ? (1 + alpha) / 2 : 1 - alpha / 2;
476
+ edgeOffset_();
477
+ const half = EDGE_[3];
478
+ let residual = 0;
479
+ for (let row = top; row <= bottom; row += 1) {
480
+ for (let column = left; column <= right; column += 1) {
481
+ const shift = normalX * (column - x) + normalY * (row - y);
482
+ EDGE_[2] = half - shift;
483
+ edgeCoverage_();
484
+ const inner = EDGE_[3];
485
+ EDGE_[2] = -half - shift;
486
+ edgeCoverage_();
487
+ const band = inner - EDGE_[3];
488
+ const predicted = ink ? band : 1 - band;
489
+ residual = Math.max(residual, Math.abs(predicted - coverage[row * width + column] / 255));
490
+ }
491
+ }
492
+ if (residual < best && residual <= STRIPE_RESIDUAL_) {
493
+ best = residual;
494
+ sites[at] = normalX;
495
+ sites[at + 1] = normalY;
496
+ sites[at + 2] = half;
497
+ sites[at + 4] = ink ? 1 : -1;
498
+ }
499
+ }
500
+ }
501
+ /**
502
+ * The arguments and result of {@link edgeOffset_} and {@link edgeCoverage_}:
503
+ * the unit outward normal, the coverage or offset, then the offset or coverage.
504
+ * A double passed to or returned from a call the engine does not inline is
505
+ * boxed, which a typed array avoids; the functions below pass their doubles so
506
+ * for that reason.
507
+ */
508
+ const EDGE_ = new Float64Array(4);
509
+ /**
510
+ * The offset, along the unit outward normal from the centre of a unit square,
511
+ * of the straight edge that covers `alpha` of it: the inverse of
512
+ * {@link edgeCoverage_}. Reads the normal and `alpha` from `EDGE_`, writes the
513
+ * offset after them.
514
+ */
515
+ function edgeOffset_() {
516
+ const normalX = EDGE_[0];
517
+ const normalY = EDGE_[1];
518
+ const alpha = EDGE_[2];
519
+ const a = Math.max(Math.abs(normalX), Math.abs(normalY));
520
+ const b = Math.min(Math.abs(normalX), Math.abs(normalY));
521
+ let offset;
522
+ if (b < 1e-6) {
523
+ offset = a * (alpha - 0.5);
524
+ }
525
+ else if (alpha <= b / (2 * a)) {
526
+ offset = -(a + b) / 2 + Math.sqrt(2 * a * b * alpha);
527
+ }
528
+ else if (alpha >= 1 - b / (2 * a)) {
529
+ offset = (a + b) / 2 - Math.sqrt(2 * a * b * (1 - alpha));
530
+ }
531
+ else {
532
+ offset = a * (alpha - 0.5);
533
+ }
534
+ EDGE_[3] = offset;
535
+ }
536
+ /**
537
+ * The fraction of a unit square covered by the half-plane behind a straight
538
+ * edge `offset` from its centre along the unit outward normal. Reads the normal
539
+ * and the offset from `EDGE_`, writes the fraction after them.
540
+ */
541
+ function edgeCoverage_() {
542
+ const normalX = EDGE_[0];
543
+ const normalY = EDGE_[1];
544
+ const offset = EDGE_[2];
545
+ const a = Math.max(Math.abs(normalX), Math.abs(normalY));
546
+ const b = Math.min(Math.abs(normalX), Math.abs(normalY));
547
+ const half = (a + b) / 2;
548
+ let covered;
549
+ if (offset <= -half) {
550
+ covered = 0;
551
+ }
552
+ else if (offset >= half) {
553
+ covered = 1;
554
+ }
555
+ else if (b >= 1e-6 && offset < -(a - b) / 2) {
556
+ covered = ((offset + half) * (offset + half)) / (2 * a * b);
557
+ }
558
+ else if (b >= 1e-6 && offset > (a - b) / 2) {
559
+ covered = 1 - ((half - offset) * (half - offset)) / (2 * a * b);
560
+ }
561
+ else {
562
+ covered = 0.5 + offset / a;
563
+ }
564
+ EDGE_[3] = covered;
565
+ }
566
+ /**
567
+ * Writes into `residuals[cell]` how far the coverage of the texels around
568
+ * antialiased texel `(x, y)`, as a fraction of a texel, strays from what its
569
+ * straight edge (at `sites[at]`) predicts; `NaN` for a texel without one (a
570
+ * zero gradient).
571
+ */
572
+ export function edgeResidual_(sites, at, coverage, x, y, width, height, residuals, cell) {
573
+ const normalX = sites[at];
574
+ const normalY = sites[at + 1];
575
+ // a stripe, or a texel whose coverage determines no feature, has no
576
+ // straight edge
577
+ if ((normalX === 0 && normalY === 0) || sites[at + 4] !== 0) {
578
+ residuals[cell] = Number.NaN;
579
+ return;
580
+ }
581
+ const offset = sites[at + 2];
582
+ EDGE_[0] = normalX;
583
+ EDGE_[1] = normalY;
584
+ let residual = 0;
585
+ for (let dy = -1; dy <= 1; dy += 1) {
586
+ const neighbourY = y + dy;
587
+ if (neighbourY < 0 || neighbourY >= height) {
588
+ continue;
589
+ }
590
+ for (let dx = -1; dx <= 1; dx += 1) {
591
+ const neighbourX = x + dx;
592
+ if (neighbourX < 0 || neighbourX >= width) {
593
+ continue;
594
+ }
595
+ EDGE_[2] = offset - normalX * dx - normalY * dy;
596
+ edgeCoverage_();
597
+ const actual = coverage[neighbourY * width + neighbourX] / 255;
598
+ residual = Math.max(residual, Math.abs(EDGE_[3] - actual));
599
+ }
600
+ }
601
+ residuals[cell] = residual;
602
+ }
603
+ /**
604
+ * The grid the contour is found in; the coverage is released at the end of
605
+ * {@link findContour_} so that no caller buffer stays referenced.
606
+ */
607
+ const NO_COVERAGE_ = new Uint8Array(0);
608
+ const GRID_ = {
609
+ width: 0,
610
+ height: 0,
611
+ base: 0,
612
+ coverage: NO_COVERAGE_,
613
+ };
614
+ /**
615
+ * Merges the straight pieces of contour of a coverage grid into runs, one
616
+ * segment site each, and places a corner where two runs meet at an angle (see
617
+ * the module notes). `scratch` holds each site cell's label in `[0, count)`
618
+ * (`UNASSIGNED_` on entry; afterwards its run's holder for a run's piece, its
619
+ * own cell for a corner's holder, the holder for a cell that took a corner,
620
+ * else negative), free room in `[count, 2 · count)`, and the site geometry from
621
+ * `2 · count`; `residuals` the straight-edge residual of each antialiased
622
+ * texel. Returns how many corners there are, their holders listed from
623
+ * `scratch[count]`.
624
+ */
625
+ export function findContour_(scratch, residuals, coverage, width, height, siteCells, siteCount) {
626
+ const count = width * height;
627
+ GRID_.width = width;
628
+ GRID_.height = height;
629
+ GRID_.base = 2 * count;
630
+ GRID_.coverage = coverage;
631
+ const runs = buildRuns_(scratch, residuals, siteCells, siteCount);
632
+ const corners = joinRuns_(scratch, residuals, runs);
633
+ spreadCorners_(scratch, corners);
634
+ GRID_.coverage = NO_COVERAGE_;
635
+ return corners;
636
+ }
637
+ /**
638
+ * Whether cell `cell` holds contour: an antialiased texel, or a full or empty
639
+ * texel with an opposite neighbour to the right or below.
640
+ */
641
+ export function isSiteCell_(coverage, cell, width, count) {
642
+ const value = coverage[cell];
643
+ if (value !== 0 && value !== 255) {
644
+ return true;
645
+ }
646
+ const opposite = 255 - value;
647
+ return (((cell % width) + 1 < width && coverage[cell + 1] === opposite) ||
648
+ (cell + width < count && coverage[cell + width] === opposite));
649
+ }
650
+ const PIECE_ = new Float64Array(4);
651
+ const SEED_PIECE_ = new Float64Array(4);
652
+ /**
653
+ * Writes into `piece` the contour point and unit outward normal `(pointX,
654
+ * pointY, normalX, normalY)` of cell `cell` when it holds one straight piece of
655
+ * contour that no run has taken yet: an antialiased texel whose 3 × 3 coverage
656
+ * is one straight edge, or a full or empty texel with a single binary
657
+ * transition (right or below).
658
+ */
659
+ function straightPiece_(scratch, residuals, cell, piece) {
660
+ const { width, height, base, coverage } = GRID_;
661
+ const value = coverage[cell];
662
+ const column = cell % width;
663
+ const row = (cell - column) / width;
664
+ if (value === 0 || value === 255) {
665
+ const opposite = 255 - value;
666
+ const right = column + 1 < width && coverage[cell + 1] === opposite;
667
+ const down = row + 1 < height && coverage[cell + width] === opposite;
668
+ if (right === down) {
669
+ return false;
670
+ }
671
+ // the flag's sign is the direction of the outward normal
672
+ const outward = value === 255 ? 1 : -1;
673
+ piece[0] = right ? column + 0.5 : column;
674
+ piece[1] = down ? row + 0.5 : row;
675
+ piece[2] = right ? outward : 0;
676
+ piece[3] = down ? outward : 0;
677
+ return true;
678
+ }
679
+ if (!(residuals[cell] <= STRAIGHT_RESIDUAL_)) {
680
+ return false;
681
+ }
682
+ const at = base + COVERAGE_STRIDE_ * cell;
683
+ const normalX = scratch[at];
684
+ const normalY = scratch[at + 1];
685
+ const offset = scratch[at + 2];
686
+ piece[0] = column + normalX * offset;
687
+ piece[1] = row + normalY * offset;
688
+ piece[2] = normalX;
689
+ piece[3] = normalY;
690
+ return true;
691
+ }
692
+ /**
693
+ * Grows a run from each straight piece no run has taken, in raster order: the
694
+ * 8-connected straight pieces whose normals turn less than `SAME_RUN_COSINE_`
695
+ * from the piece before and less than `CORNER_COSINE_` from the first, then
696
+ * fitted (see {@link fitRun_}). Returns how many runs there are; their holders
697
+ * are listed downward from `scratch[2 · count − 1]`, and each run's pieces are
698
+ * labelled with its holder, the others `LONE_`.
699
+ */
700
+ function buildRuns_(scratch, residuals, siteCells, siteCount) {
701
+ const { width, height } = GRID_;
702
+ const count = width * height;
703
+ let runs = 0;
704
+ for (let siteIndex = 0; siteIndex < siteCount; siteIndex += 1) {
705
+ const seed = siteCells[siteIndex];
706
+ if (scratch[seed] !== UNASSIGNED_ ||
707
+ !straightPiece_(scratch, residuals, seed, SEED_PIECE_)) {
708
+ continue;
709
+ }
710
+ // the run's pieces queue in [count, 2 · count), below the holders, and
711
+ // their geometry in RUN_PIECES_; a run stops growing at
712
+ // MAX_RUN_PIECES_ (the pieces past it start the next)
713
+ const queue = count;
714
+ let head = 0;
715
+ let tail = 1;
716
+ scratch[queue] = seed;
717
+ scratch[seed] = seed;
718
+ cachePiece_(0, seed, SEED_PIECE_);
719
+ const seedNormalX = SEED_PIECE_[2];
720
+ const seedNormalY = SEED_PIECE_[3];
721
+ while (head < tail) {
722
+ const reached = scratch[queue + head];
723
+ const reachedNormalX = RUN_PIECES_[5 * head + 2];
724
+ const reachedNormalY = RUN_PIECES_[5 * head + 3];
725
+ head += 1;
726
+ const column = reached % width;
727
+ const row = (reached - column) / width;
728
+ for (let nextRow = Math.max(0, row - 1); nextRow <= Math.min(height - 1, row + 1); nextRow += 1) {
729
+ for (let nextColumn = Math.max(0, column - 1); nextColumn <= Math.min(width - 1, column + 1); nextColumn += 1) {
730
+ const next = nextRow * width + nextColumn;
731
+ if (tail === MAX_RUN_PIECES_ ||
732
+ scratch[next] !== UNASSIGNED_ ||
733
+ !straightPiece_(scratch, residuals, next, PIECE_)) {
734
+ continue;
735
+ }
736
+ const normalX = PIECE_[2];
737
+ const normalY = PIECE_[3];
738
+ if (normalX * reachedNormalX + normalY * reachedNormalY <
739
+ SAME_RUN_COSINE_ ||
740
+ normalX * seedNormalX + normalY * seedNormalY < CORNER_COSINE_) {
741
+ continue;
742
+ }
743
+ scratch[next] = seed;
744
+ scratch[queue + tail] = next;
745
+ cachePiece_(tail, next, PIECE_);
746
+ tail += 1;
747
+ }
748
+ }
749
+ }
750
+ if (fitRun_(scratch, tail)) {
751
+ scratch[2 * count - 1 - runs] = RUN_HOLDER_[0];
752
+ runs += 1;
753
+ }
754
+ }
755
+ return runs;
756
+ }
757
+ const RUN_ = line2Create();
758
+ /** The holder {@link fitRun_} chose. */
759
+ const RUN_HOLDER_ = new Float64Array(1);
760
+ /**
761
+ * The most pieces one run grows to; a longer straight edge makes several runs,
762
+ * which meet at no corner (their normals agree).
763
+ */
764
+ const MAX_RUN_PIECES_ = 1024;
765
+ /**
766
+ * The pieces of the run being grown, `(pointX, pointY, normalX, normalY,
767
+ * alpha)` each in queue order, `alpha` the coverage of an antialiased piece and
768
+ * `-1` for a binary one: every step of the fit reads them again.
769
+ */
770
+ const RUN_PIECES_ = new Float64Array(5 * MAX_RUN_PIECES_);
771
+ const RUN_KEPT_ = new Uint8Array(MAX_RUN_PIECES_);
772
+ const RUN_ALONG_ = new Float64Array(MAX_RUN_PIECES_);
773
+ /** Stores `piece`, of cell `cell`, as the `index`-th of `RUN_PIECES_`. */
774
+ function cachePiece_(index, cell, piece) {
775
+ const value = GRID_.coverage[cell];
776
+ const at = 5 * index;
777
+ RUN_PIECES_[at] = piece[0];
778
+ RUN_PIECES_[at + 1] = piece[1];
779
+ RUN_PIECES_[at + 2] = piece[2];
780
+ RUN_PIECES_[at + 3] = piece[3];
781
+ RUN_PIECES_[at + 4] = value === 0 || value === 255 ? -1 : value / 255;
782
+ }
783
+ /**
784
+ * Fits a line, by total least squares, through the contour points of the
785
+ * `members` pieces queued from `scratch[count]` (labelled with their seed): a
786
+ * first fit through all of them, then three fits each keeping the pieces near
787
+ * the last line (a quarter texel, then twice and once `RUN_TOLERANCE_`), so the
788
+ * pieces a neighbouring corner bends drop out; an antialiased piece is moved
789
+ * onto the line's normal by inverting its coverage, which the run's normal
790
+ * estimates better than the texel's Sobel gradient. A run shorter than a texel
791
+ * and a half takes its direction from its normals. When the pieces kept span
792
+ * `MIN_RUN_SPAN_`, the first of them holds the run's segment, which spans them
793
+ * and half a piece beyond (see {@link COVERAGE_STRIDE_}), the others lose their
794
+ * own, and all are labelled with the holder; the other pieces are labelled
795
+ * `LONE_`. Returns whether there is a run, its holder in `RUN_HOLDER_`.
796
+ */
797
+ function fitRun_(scratch, members) {
798
+ const { width, base } = GRID_;
799
+ const count = GRID_.width * GRID_.height;
800
+ SEED_PIECE_[0] = RUN_PIECES_[0];
801
+ SEED_PIECE_[1] = RUN_PIECES_[1];
802
+ SEED_PIECE_[2] = RUN_PIECES_[2];
803
+ SEED_PIECE_[3] = RUN_PIECES_[3];
804
+ line2Set(RUN_, SEED_PIECE_[0], SEED_PIECE_[1], -SEED_PIECE_[3], SEED_PIECE_[2]);
805
+ const fitted = fitRunPass_(scratch, members, 0) &&
806
+ fitRunPass_(scratch, members, 1) &&
807
+ fitRunPass_(scratch, members, 2) &&
808
+ fitRunPass_(scratch, members, RUN_PASS_);
809
+ let holder = -1;
810
+ let low = Infinity;
811
+ let high = -Infinity;
812
+ let lowMember = -1;
813
+ let highMember = -1;
814
+ let kept = 0;
815
+ if (fitted) {
816
+ for (let index = 0; index < members; index += 1) {
817
+ const member = scratch[count + index];
818
+ const isKept = runMember_(scratch, index, RUN_PASS_);
819
+ const along = RUN_[2] * (PIECE_[0] - RUN_[0]) + RUN_[3] * (PIECE_[1] - RUN_[1]);
820
+ RUN_KEPT_[index] = isKept ? 1 : 0;
821
+ RUN_ALONG_[index] = along;
822
+ if (isKept) {
823
+ kept += 1;
824
+ if (along < low) {
825
+ low = along;
826
+ lowMember = member;
827
+ }
828
+ if (along > high) {
829
+ high = along;
830
+ highMember = member;
831
+ }
832
+ }
833
+ }
834
+ }
835
+ if (kept < 3 || !(high - low >= MIN_RUN_SPAN_)) {
836
+ for (let index = 0; index < members; index += 1) {
837
+ scratch[scratch[count + index]] = LONE_;
838
+ }
839
+ return false;
840
+ }
841
+ // a piece left out between the kept ones means the contour bends away
842
+ // from the line there (an arc whose two flanks are near one chord): not a
843
+ // straight run
844
+ for (let index = 0; index < members; index += 1) {
845
+ if (RUN_KEPT_[index] === 1) {
846
+ continue;
847
+ }
848
+ const along = RUN_ALONG_[index];
849
+ if (along > low && along < high) {
850
+ for (let other = 0; other < members; other += 1) {
851
+ scratch[scratch[count + other]] = LONE_;
852
+ }
853
+ return false;
854
+ }
855
+ }
856
+ // label the pieces before any geometry moves, membership reading it: the
857
+ // kept pieces between the extreme two merge into the run, which the one
858
+ // nearest its middle holds (farthest from the corners that may end it);
859
+ // the extreme two keep their own pieces, so that the run's ends follow the
860
+ // contour's own direction there, not the fitted line's
861
+ const middle = (low + high) / 2;
862
+ let holderGap = Infinity;
863
+ for (let index = 0; index < members; index += 1) {
864
+ const member = scratch[count + index];
865
+ const inner = member !== lowMember && member !== highMember && RUN_KEPT_[index] === 1;
866
+ scratch[member] = inner ? INNER_ : LONE_;
867
+ if (inner) {
868
+ const gap = Math.abs(RUN_ALONG_[index] - middle);
869
+ if (gap < holderGap) {
870
+ holderGap = gap;
871
+ holder = member;
872
+ }
873
+ }
874
+ }
875
+ for (let index = 0; index < members; index += 1) {
876
+ const member = scratch[count + index];
877
+ if (scratch[member] === LONE_) {
878
+ continue;
879
+ }
880
+ scratch[member] = holder;
881
+ if (member !== holder) {
882
+ const at = base + COVERAGE_STRIDE_ * member;
883
+ scratch[at] = Number.NaN;
884
+ scratch[at + 1] = 0;
885
+ scratch[at + 2] = 0;
886
+ }
887
+ }
888
+ // the segment runs along the outward normal turned a quarter clockwise, so
889
+ // its normal is (directionY, −directionX), between the extreme points
890
+ let directionX = RUN_[2];
891
+ let directionY = RUN_[3];
892
+ const normalX = directionY;
893
+ const normalY = -directionX;
894
+ if (normalX * SEED_PIECE_[2] + normalY * SEED_PIECE_[3] < 0) {
895
+ directionX = -directionX;
896
+ directionY = -directionY;
897
+ const flipped = -low;
898
+ low = -high;
899
+ high = flipped;
900
+ }
901
+ const holderColumn = holder % width;
902
+ const holderRow = (holder - holderColumn) / width;
903
+ const at = base + COVERAGE_STRIDE_ * holder;
904
+ scratch[at] = RUN_[0] + directionX * low - holderColumn;
905
+ scratch[at + 1] = RUN_[1] + directionY * low - holderRow;
906
+ scratch[at + 2] = RUN_[0] + directionX * high - holderColumn;
907
+ scratch[at + 3] = RUN_[1] + directionY * high - holderRow;
908
+ scratch[at + 4] = Number.NaN;
909
+ scratch[at + 5] = 0;
910
+ RUN_HOLDER_[0] = holder;
911
+ return true;
912
+ }
913
+ /** A kept piece between a run's extreme two, before the holder is known. */
914
+ const INNER_ = -3;
915
+ /**
916
+ * Whether queued piece `member` (labelled with its seed or kept) is within
917
+ * `TOLERANCES_[pass]` of `RUN_`, with a normal turned less than
918
+ * `SAME_RUN_COSINE_` from the run's on the seed's side; pass `ALL_PIECES_`
919
+ * takes every queued piece as it is. Leaves the piece in `PIECE_`, an
920
+ * antialiased one moved onto the run's normal.
921
+ */
922
+ function runMember_(scratch, index, pass) {
923
+ const at = 5 * index;
924
+ PIECE_[0] = RUN_PIECES_[at];
925
+ PIECE_[1] = RUN_PIECES_[at + 1];
926
+ PIECE_[2] = RUN_PIECES_[at + 2];
927
+ PIECE_[3] = RUN_PIECES_[at + 3];
928
+ if (pass === ALL_PIECES_) {
929
+ return true;
930
+ }
931
+ let normalX = -RUN_[3];
932
+ let normalY = RUN_[2];
933
+ if (normalX * SEED_PIECE_[2] + normalY * SEED_PIECE_[3] < 0) {
934
+ normalX = -normalX;
935
+ normalY = -normalY;
936
+ }
937
+ if (normalX * PIECE_[2] + normalY * PIECE_[3] < SAME_RUN_COSINE_) {
938
+ return false;
939
+ }
940
+ const alpha = RUN_PIECES_[at + 4];
941
+ if (alpha >= 0) {
942
+ const { width } = GRID_;
943
+ const member = scratch[width * GRID_.height + index];
944
+ EDGE_[0] = normalX;
945
+ EDGE_[1] = normalY;
946
+ EDGE_[2] = alpha;
947
+ edgeOffset_();
948
+ const offset = EDGE_[3];
949
+ const column = member % width;
950
+ PIECE_[0] = column + normalX * offset;
951
+ PIECE_[1] = (member - column) / width + normalY * offset;
952
+ }
953
+ return (Math.abs(RUN_[2] * (PIECE_[1] - RUN_[1]) - RUN_[3] * (PIECE_[0] - RUN_[0])) <= TOLERANCES_[pass]);
954
+ }
955
+ /**
956
+ * The tolerances of {@link fitRun_}'s passes, in texels, by pass: every piece,
957
+ * a quarter texel, then twice and once `RUN_TOLERANCE_`. Passes are named by
958
+ * index, as a double passed to a call the engine does not inline is boxed.
959
+ */
960
+ const TOLERANCES_ = new Float64Array([
961
+ Infinity,
962
+ 0.25,
963
+ 2 * RUN_TOLERANCE_,
964
+ RUN_TOLERANCE_,
965
+ ]);
966
+ const ALL_PIECES_ = 0;
967
+ const RUN_PASS_ = 3;
968
+ /**
969
+ * One fit of {@link fitRun_} over the queued pieces within `TOLERANCES_[pass]`
970
+ * of `RUN_`; returns whether there was any.
971
+ */
972
+ function fitRunPass_(scratch, members, pass) {
973
+ let kept = 0;
974
+ let sumX = 0;
975
+ let sumY = 0;
976
+ let sumXX = 0;
977
+ let sumXY = 0;
978
+ let sumYY = 0;
979
+ let normalX = 0;
980
+ let normalY = 0;
981
+ let low = Infinity;
982
+ let high = -Infinity;
983
+ // moments about the run's current point keep the sums small
984
+ const originX = RUN_[0];
985
+ const originY = RUN_[1];
986
+ const dirX = RUN_[2];
987
+ const dirY = RUN_[3];
988
+ const { width, height } = GRID_;
989
+ const count = width * height;
990
+ const tol = TOLERANCES_[pass];
991
+ let runNX = -dirY;
992
+ let runNY = dirX;
993
+ if (runNX * SEED_PIECE_[2] + runNY * SEED_PIECE_[3] < 0) {
994
+ runNX = -runNX;
995
+ runNY = -runNY;
996
+ }
997
+ const absNX = runNX < 0 ? -runNX : runNX;
998
+ const absNY = runNY < 0 ? -runNY : runNY;
999
+ const a = absNX >= absNY ? absNX : absNY;
1000
+ const b = absNX >= absNY ? absNY : absNX;
1001
+ const half = (a + b) * 0.5;
1002
+ const bOver2a = b >= 1e-6 ? b / (2 * a) : -1;
1003
+ const twoAB = 2 * a * b;
1004
+ for (let index = 0; index < members; index += 1) {
1005
+ const at = 5 * index;
1006
+ let px = RUN_PIECES_[at];
1007
+ let py = RUN_PIECES_[at + 1];
1008
+ const pnx = RUN_PIECES_[at + 2];
1009
+ const pny = RUN_PIECES_[at + 3];
1010
+ if (pass !== ALL_PIECES_) {
1011
+ if (runNX * pnx + runNY * pny < SAME_RUN_COSINE_) {
1012
+ continue;
1013
+ }
1014
+ const alpha = RUN_PIECES_[at + 4];
1015
+ if (alpha >= 0) {
1016
+ let offset;
1017
+ if (bOver2a < 0) {
1018
+ offset = a * (alpha - 0.5);
1019
+ }
1020
+ else if (alpha <= bOver2a) {
1021
+ offset = -half + Math.sqrt(twoAB * alpha);
1022
+ }
1023
+ else if (alpha >= 1 - bOver2a) {
1024
+ offset = half - Math.sqrt(twoAB * (1 - alpha));
1025
+ }
1026
+ else {
1027
+ offset = a * (alpha - 0.5);
1028
+ }
1029
+ const member = scratch[count + index];
1030
+ const column = member % width;
1031
+ px = column + runNX * offset;
1032
+ py = (member - column) / width + runNY * offset;
1033
+ }
1034
+ const dist = dirX * (py - originY) - dirY * (px - originX);
1035
+ if (dist > tol || dist < -tol) {
1036
+ continue;
1037
+ }
1038
+ }
1039
+ const dx = px - originX;
1040
+ const dy = py - originY;
1041
+ kept += 1;
1042
+ sumX += dx;
1043
+ sumY += dy;
1044
+ sumXX += dx * dx;
1045
+ sumXY += dx * dy;
1046
+ sumYY += dy * dy;
1047
+ normalX += pnx;
1048
+ normalY += pny;
1049
+ const along = dirX * dx + dirY * dy;
1050
+ if (along < low) {
1051
+ low = along;
1052
+ }
1053
+ if (along > high) {
1054
+ high = along;
1055
+ }
1056
+ }
1057
+ if (kept === 0) {
1058
+ return false;
1059
+ }
1060
+ const meanX = sumX / kept;
1061
+ const meanY = sumY / kept;
1062
+ const xx = sumXX - kept * meanX * meanX;
1063
+ const xy = sumXY - kept * meanX * meanY;
1064
+ const yy = sumYY - kept * meanY * meanY;
1065
+ let directionX;
1066
+ let directionY;
1067
+ if (high - low < 1.5) {
1068
+ // too short a run for its points to give the direction: its normals do
1069
+ const length = Math.sqrt(normalX * normalX + normalY * normalY);
1070
+ directionX = -normalY / length;
1071
+ directionY = normalX / length;
1072
+ }
1073
+ else {
1074
+ const angle = Math.atan2(2 * xy, xx - yy) / 2;
1075
+ directionX = Math.cos(angle);
1076
+ directionY = Math.sin(angle);
1077
+ }
1078
+ line2Set(RUN_, originX + meanX, originY + meanY, directionX, directionY);
1079
+ return true;
1080
+ }
1081
+ /**
1082
+ * The outward normals of the corner being tried, the first run's then the
1083
+ * second's.
1084
+ */
1085
+ const CORNER_NORMALS_ = new Float64Array(4);
1086
+ /**
1087
+ * The vertex the corner functions below measure at, then their scalar results:
1088
+ * a double passed to or returned from a call the engine does not inline is
1089
+ * boxed, which a typed array avoids, so these functions pass their doubles
1090
+ * through `CORNER_AT_` and `RESULT_`.
1091
+ */
1092
+ const CORNER_AT_ = new Float64Array(2);
1093
+ const RESULT_ = new Float64Array(1);
1094
+ const RUN_A_ = line2Create();
1095
+ const RUN_B_ = line2Create();
1096
+ const VERTEX_ = vec2Create();
1097
+ /** The window of {@link joinRuns_}'s walk: visited cells, and its queue. */
1098
+ const WALK_SPAN_ = 2 * JUNCTION_REACH_ + 1;
1099
+ const WALK_SEEN_ = new Uint8Array(WALK_SPAN_ * WALK_SPAN_);
1100
+ const WALK_QUEUE_ = new Int32Array(WALK_SPAN_ * WALK_SPAN_);
1101
+ /** The runs one walk met, by holder. */
1102
+ const MET_ = new Float64Array(WALK_SPAN_ * WALK_SPAN_);
1103
+ /**
1104
+ * Tries a corner between each run and the runs met by walking, from either end
1105
+ * of it, through up to `JUNCTION_REACH_` texels of contour that belong to no
1106
+ * run (see {@link tryCorner_}). Returns how many corners there are, their
1107
+ * holders listed from `scratch[count]`.
1108
+ */
1109
+ function joinRuns_(scratch, residuals, runs) {
1110
+ const { width, height, base } = GRID_;
1111
+ const count = width * height;
1112
+ let corners = 0;
1113
+ for (let index = 0; index < runs; index += 1) {
1114
+ const run = scratch[2 * count - 1 - index];
1115
+ const runColumn = run % width;
1116
+ const runRow = (run - runColumn) / width;
1117
+ const at = base + COVERAGE_STRIDE_ * run;
1118
+ for (let end = 0; end < 2; end += 1) {
1119
+ const endX = runColumn + scratch[at + 2 * end];
1120
+ const endY = runRow + scratch[at + 2 * end + 1];
1121
+ // `| 0`: a cell index, never a boxed −0
1122
+ const met = walkFrom_(scratch, run, Math.round(endX) | 0, Math.round(endY) | 0);
1123
+ for (let other = 0; other < met; other += 1) {
1124
+ const holder = tryCorner_(scratch, residuals, run, MET_[other], corners);
1125
+ if (holder >= 0) {
1126
+ scratch[count + corners] = holder;
1127
+ corners += 1;
1128
+ }
1129
+ }
1130
+ }
1131
+ }
1132
+ return corners;
1133
+ }
1134
+ /**
1135
+ * Walks, breadth first, from cell `(startX, startY)` through the contour cells
1136
+ * within `JUNCTION_REACH_` of it that belong to no run, and lists in `MET_` the
1137
+ * other runs than `run` it reaches; returns how many.
1138
+ */
1139
+ function walkFrom_(scratch, run, startX, startY) {
1140
+ const { width, height, base, coverage } = GRID_;
1141
+ const count = width * height;
1142
+ if (startX < 0 || startX >= width || startY < 0 || startY >= height) {
1143
+ return 0;
1144
+ }
1145
+ WALK_SEEN_.fill(0);
1146
+ let head = 0;
1147
+ let tail = 1;
1148
+ let met = 0;
1149
+ WALK_QUEUE_[0] = startY * width + startX;
1150
+ WALK_SEEN_[JUNCTION_REACH_ * WALK_SPAN_ + JUNCTION_REACH_] = 1;
1151
+ while (head < tail) {
1152
+ const cell = WALK_QUEUE_[head];
1153
+ head += 1;
1154
+ const column = cell % width;
1155
+ const row = (cell - column) / width;
1156
+ for (let nextRow = Math.max(0, row - 1, startY - JUNCTION_REACH_); nextRow <= Math.min(height - 1, row + 1, startY + JUNCTION_REACH_); nextRow += 1) {
1157
+ for (let nextColumn = Math.max(0, column - 1, startX - JUNCTION_REACH_); nextColumn <= Math.min(width - 1, column + 1, startX + JUNCTION_REACH_); nextColumn += 1) {
1158
+ const local = (nextRow - startY + JUNCTION_REACH_) * WALK_SPAN_ +
1159
+ nextColumn -
1160
+ startX +
1161
+ JUNCTION_REACH_;
1162
+ if (WALK_SEEN_[local] === 1) {
1163
+ continue;
1164
+ }
1165
+ WALK_SEEN_[local] = 1;
1166
+ const next = nextRow * width + nextColumn;
1167
+ if (!isSiteCell_(coverage, next, width, count)) {
1168
+ continue;
1169
+ }
1170
+ const label = scratch[next];
1171
+ if (label >= 0 && isRun_(scratch, base, label)) {
1172
+ if (label !== run && !listed_(met, label)) {
1173
+ MET_[met] = label;
1174
+ met += 1;
1175
+ }
1176
+ continue;
1177
+ }
1178
+ WALK_QUEUE_[tail] = next;
1179
+ tail += 1;
1180
+ }
1181
+ }
1182
+ }
1183
+ return met;
1184
+ }
1185
+ function listed_(met, holder) {
1186
+ for (let index = 0; index < met; index += 1) {
1187
+ if (MET_[index] === holder) {
1188
+ return true;
1189
+ }
1190
+ }
1191
+ return false;
1192
+ }
1193
+ /** Whether the site of cell `cell` is a run's segment. */
1194
+ function isRun_(scratch, base, cell) {
1195
+ const at = base + COVERAGE_STRIDE_ * cell;
1196
+ // NaN differs from itself (Number.isNaN boxes in an engine tier)
1197
+ const first = scratch[at];
1198
+ const fourth = scratch[at + 3];
1199
+ const fifth = scratch[at + 4];
1200
+ return first === first && fourth === fourth && fifth !== fifth;
1201
+ }
1202
+ /** Whether the site of cell `cell` is a corner. */
1203
+ export function isCorner_(scratch, base, cell) {
1204
+ const at = base + COVERAGE_STRIDE_ * cell;
1205
+ // NaN differs from itself (Number.isNaN boxes in an engine tier)
1206
+ const first = scratch[at];
1207
+ const fourth = scratch[at + 3];
1208
+ const fifth = scratch[at + 4];
1209
+ return first === first && fourth === fourth && fifth === fifth;
1210
+ }
1211
+ /**
1212
+ * Loads the segment of run `run` into `line` (from its start, unit direction)
1213
+ * and writes its length into `RESULT_`.
1214
+ */
1215
+ function loadRun_(scratch, run, line) {
1216
+ const { width, base } = GRID_;
1217
+ const at = base + COVERAGE_STRIDE_ * run;
1218
+ const column = run % width;
1219
+ const row = (run - column) / width;
1220
+ const startX = column + scratch[at];
1221
+ const startY = row + scratch[at + 1];
1222
+ const directionX = column + scratch[at + 2] - startX;
1223
+ const directionY = row + scratch[at + 3] - startY;
1224
+ const length = Math.sqrt(directionX * directionX + directionY * directionY);
1225
+ line2Set(line, startX, startY, directionX / length, directionY / length);
1226
+ RESULT_[0] = length;
1227
+ }
1228
+ /**
1229
+ * A run leaving a corner: see {@link armOf_}, which reads the run's length and
1230
+ * the vertex's parameter from the last two entries.
1231
+ */
1232
+ const ARM_ = new Float64Array(5);
1233
+ /**
1234
+ * How a run (from its start, of length `ARM_[3]`, between its inner extreme
1235
+ * points) leaves the vertex at parameter `ARM_[4]` along it: into `ARM_`, the
1236
+ * direction sign (+1 along the run, −1 against), the distance from the vertex
1237
+ * to half a texel past its far end, and to its near end. Returns false when the
1238
+ * run lies on both sides of the vertex (more than half a texel past it).
1239
+ */
1240
+ function armOf_() {
1241
+ const length = ARM_[3];
1242
+ const vertex = ARM_[4];
1243
+ if (vertex <= 0.5) {
1244
+ ARM_[0] = 1;
1245
+ ARM_[1] = length - vertex + 0.5;
1246
+ ARM_[2] = -vertex;
1247
+ return true;
1248
+ }
1249
+ if (vertex >= length - 0.5) {
1250
+ ARM_[0] = -1;
1251
+ ARM_[1] = vertex + 0.5;
1252
+ ARM_[2] = vertex - length;
1253
+ return true;
1254
+ }
1255
+ return false;
1256
+ }
1257
+ /**
1258
+ * Places the corner of runs `first` and `second` when they make one: their
1259
+ * normals differ by `CORNER_COSINE_`, their lines cross within `VERTEX_REACH_`
1260
+ * of both near ends, beyond neither, and the corner predicts the coverage
1261
+ * around the vertex (see the acceptance below). The corner's site goes to the
1262
+ * contour cell nearest the vertex that belongs to no run and holds no corner,
1263
+ * its runs end at the vertex, and its edges reach their far ends. Returns the
1264
+ * holder, or `-1`.
1265
+ */
1266
+ function tryCorner_(scratch, residuals, first, second, corners) {
1267
+ const { width, base } = GRID_;
1268
+ loadRun_(scratch, first, RUN_A_);
1269
+ const firstLength = RESULT_[0];
1270
+ loadRun_(scratch, second, RUN_B_);
1271
+ const secondLength = RESULT_[0];
1272
+ // outward normals (directionY, −directionX), see fitRun_
1273
+ const firstNormalX = RUN_A_[3];
1274
+ const firstNormalY = -RUN_A_[2];
1275
+ const secondNormalX = RUN_B_[3];
1276
+ const secondNormalY = -RUN_B_[2];
1277
+ if (firstNormalX * secondNormalX + firstNormalY * secondNormalY >
1278
+ CORNER_COSINE_ ||
1279
+ !line2IntersectLine2(VERTEX_, RUN_A_, RUN_B_, 0)) {
1280
+ return -1;
1281
+ }
1282
+ const vertexX = VERTEX_[0];
1283
+ const vertexY = VERTEX_[1];
1284
+ ARM_[3] = firstLength;
1285
+ ARM_[4] =
1286
+ RUN_A_[2] * (vertexX - RUN_A_[0]) + RUN_A_[3] * (vertexY - RUN_A_[1]);
1287
+ if (!armOf_()) {
1288
+ return -1;
1289
+ }
1290
+ const firstSign = ARM_[0];
1291
+ const firstReach = ARM_[1];
1292
+ const firstNear = ARM_[2];
1293
+ ARM_[3] = secondLength;
1294
+ ARM_[4] =
1295
+ RUN_B_[2] * (vertexX - RUN_B_[0]) + RUN_B_[3] * (vertexY - RUN_B_[1]);
1296
+ if (!armOf_()) {
1297
+ return -1;
1298
+ }
1299
+ const secondSign = ARM_[0];
1300
+ const secondReach = ARM_[1];
1301
+ const secondNear = ARM_[2];
1302
+ if (firstNear > VERTEX_REACH_ ||
1303
+ secondNear > VERTEX_REACH_ ||
1304
+ cornered_(scratch, first, firstSign > 0) ||
1305
+ cornered_(scratch, second, secondSign > 0)) {
1306
+ return -1;
1307
+ }
1308
+ // the edges leaving the vertex
1309
+ const firstArmX = firstSign * RUN_A_[2];
1310
+ const firstArmY = firstSign * RUN_A_[3];
1311
+ const secondArmX = secondSign * RUN_B_[2];
1312
+ const secondArmY = secondSign * RUN_B_[3];
1313
+ CORNER_NORMALS_[0] = firstNormalX;
1314
+ CORNER_NORMALS_[1] = firstNormalY;
1315
+ CORNER_NORMALS_[2] = secondNormalX;
1316
+ CORNER_NORMALS_[3] = secondNormalY;
1317
+ // convex: the second edge, leaving the vertex, goes behind the first, so
1318
+ // the shape is the intersection of the two half-planes, not their union
1319
+ const convex = firstNormalX * secondArmX + firstNormalY * secondArmY <= 0;
1320
+ // `| 0`: cell coordinates, never a boxed −0
1321
+ const crossingColumn = Math.round(vertexX) | 0;
1322
+ const crossingRow = Math.round(vertexY) | 0;
1323
+ CORNER_AT_[0] = vertexX;
1324
+ CORNER_AT_[1] = vertexY;
1325
+ const holder = cornerHolder_(scratch);
1326
+ if (holder < 0) {
1327
+ return -1;
1328
+ }
1329
+ const holderColumn = holder % width;
1330
+ const holderRow = (holder - holderColumn) / width;
1331
+ bendNear_(residuals, crossingColumn, crossingRow);
1332
+ const bent = RESULT_[0] >= BENT_RESIDUAL_;
1333
+ let bisectorX = firstArmX + secondArmX;
1334
+ let bisectorY = firstArmY + secondArmY;
1335
+ const bisectorLength = Math.sqrt(bisectorX * bisectorX + bisectorY * bisectorY);
1336
+ bisectorX /= bisectorLength;
1337
+ bisectorY /= bisectorLength;
1338
+ const halfSine = Math.abs(bisectorX * firstNormalX + bisectorY * firstNormalY);
1339
+ // a corner is clear when its crossing predicts the coverage closely; else
1340
+ // the texels next to it must bend as a smooth curve's do not, and the
1341
+ // corner predict the coverage: from its crossing, or, at a tip sharper
1342
+ // than `SHARP_TIP_HALF_SINE_` allows (where the crossing is
1343
+ // ill-conditioned), placed and over the 5 × 5 texels around (a curve's
1344
+ // tangents fit it to about 0.03–0.05 near where they meet, not farther);
1345
+ // the misfit is measured only as far as the decision needs
1346
+ cornerMisfit_(convex, holderColumn, holderRow, crossingColumn, crossingRow, 1, !bent);
1347
+ const misfit = RESULT_[0];
1348
+ if (misfit > CLEAR_CORNER_RESIDUAL_ &&
1349
+ (!bent || (misfit > CORNER_RESIDUAL_ && halfSine > SHARP_TIP_HALF_SINE_))) {
1350
+ return -1;
1351
+ }
1352
+ // the runs' lines cross at a shallow angle at a sharp tip, where a small
1353
+ // error in either moves the crossing far: the coverage around the vertex
1354
+ // places it along the bisector, the lines moving at most
1355
+ // 2 · RUN_TOLERANCE_ across themselves
1356
+ TIP_[0] = vertexX;
1357
+ TIP_[1] = vertexY;
1358
+ TIP_[2] = bisectorX;
1359
+ TIP_[3] = bisectorY;
1360
+ TIP_[4] = (2 * RUN_TOLERANCE_) / halfSine;
1361
+ placeTip_(convex);
1362
+ const shift = RESULT_[0];
1363
+ const placedX = vertexX + shift * bisectorX;
1364
+ const placedY = vertexY + shift * bisectorY;
1365
+ CORNER_AT_[0] = placedX;
1366
+ CORNER_AT_[1] = placedY;
1367
+ if (misfit > CORNER_RESIDUAL_) {
1368
+ cornerMisfit_(convex, holderColumn, holderRow, Math.round(placedX) | 0, Math.round(placedY) | 0, 2, false);
1369
+ if (RESULT_[0] > CORNER_RESIDUAL_) {
1370
+ return -1;
1371
+ }
1372
+ }
1373
+ const halfCosine = bisectorX * firstArmX + bisectorY * firstArmY;
1374
+ ARM_LENGTH_[0] = firstArmX;
1375
+ ARM_LENGTH_[1] = firstArmY;
1376
+ ARM_LENGTH_[2] = firstReach;
1377
+ ARM_LENGTH_[3] = firstNear;
1378
+ armLength_(first);
1379
+ const firstEnd = RESULT_[0] - shift * halfCosine;
1380
+ ARM_LENGTH_[0] = secondArmX;
1381
+ ARM_LENGTH_[1] = secondArmY;
1382
+ ARM_LENGTH_[2] = secondReach;
1383
+ ARM_LENGTH_[3] = secondNear;
1384
+ armLength_(second);
1385
+ const secondEnd = RESULT_[0] - shift * halfCosine;
1386
+ // the ends are ordered so that the turn from the first to the second is
1387
+ // counter-clockwise (positive cross product) exactly when the corner is
1388
+ // convex, which tells inside from outside
1389
+ const firstX = firstArmX * firstEnd;
1390
+ const firstY = firstArmY * firstEnd;
1391
+ const secondX = secondArmX * secondEnd;
1392
+ const secondY = secondArmY * secondEnd;
1393
+ const swap = firstX * secondY - firstY * secondX > 0 !== convex;
1394
+ const at = base + COVERAGE_STRIDE_ * holder;
1395
+ scratch[at] = placedX - holderColumn;
1396
+ scratch[at + 1] = placedY - holderRow;
1397
+ scratch[at + 2] = placedX + (swap ? secondX : firstX) - holderColumn;
1398
+ scratch[at + 3] = placedY + (swap ? secondY : firstY) - holderRow;
1399
+ scratch[at + 4] = placedX + (swap ? firstX : secondX) - holderColumn;
1400
+ scratch[at + 5] = placedY + (swap ? firstY : secondY) - holderRow;
1401
+ scratch[holder] = holder;
1402
+ // the runs end at the vertex, which their last pieces may overshoot
1403
+ endRunAt_(scratch, first, firstSign > 0, corners);
1404
+ endRunAt_(scratch, second, secondSign > 0, corners);
1405
+ return holder;
1406
+ }
1407
+ /**
1408
+ * The inputs of {@link placeTip_}: the crossing, the unit bisector, and the
1409
+ * largest shift along it.
1410
+ */
1411
+ const TIP_ = new Float64Array(5);
1412
+ /**
1413
+ * The inputs of {@link armLength_}: the edge's unit direction leaving the
1414
+ * vertex, the distance to half a texel past the run's far end and to its near
1415
+ * end.
1416
+ */
1417
+ const ARM_LENGTH_ = new Float64Array(4);
1418
+ /**
1419
+ * How far from the vertex `CORNER_AT_` a corner's edge along run `run`, leaving
1420
+ * the vertex along the direction in `ARM_LENGTH_`, reaches (into `RESULT_`):
1421
+ * past the texels the corner may replace, `near` being the distance to the
1422
+ * run's near end and `reach` half a texel past its far one; or over the whole
1423
+ * run when that would reach the run's holder, where the corner would tie with
1424
+ * the run and hide it from the vector propagation's neighbours (a corner later
1425
+ * placed at the far end shortens the edge to its vertex).
1426
+ */
1427
+ function armLength_(run) {
1428
+ const directionX = ARM_LENGTH_[0];
1429
+ const directionY = ARM_LENGTH_[1];
1430
+ const reach = ARM_LENGTH_[2];
1431
+ const near = ARM_LENGTH_[3];
1432
+ const vertexX = CORNER_AT_[0];
1433
+ const vertexY = CORNER_AT_[1];
1434
+ const whole = reach - 0.5;
1435
+ const short = Math.min(whole, near + SPREAD_REACH_ + 2);
1436
+ const { width } = GRID_;
1437
+ const column = run % width;
1438
+ const holder = directionX * (column - vertexX) +
1439
+ directionY * ((run - column) / width - vertexY);
1440
+ RESULT_[0] = holder <= short + 1 ? whole : short;
1441
+ }
1442
+ /**
1443
+ * Moves the end of run `run` next to a corner (its start when the run leaves
1444
+ * the vertex along its direction, `forward`, else its end) onto the vertex
1445
+ * `CORNER_AT_`, and marks that end as taken. When the far end has a corner
1446
+ * already (one of the `corners` listed from `scratch[count]`, its vertex
1447
+ * there), that corner's edge along the run stops at this vertex.
1448
+ */
1449
+ function endRunAt_(scratch, run, forward, corners) {
1450
+ const { width, height, base } = GRID_;
1451
+ const count = width * height;
1452
+ const vertexX = CORNER_AT_[0];
1453
+ const vertexY = CORNER_AT_[1];
1454
+ const record = base + COVERAGE_STRIDE_ * run;
1455
+ const at = record + (forward ? 0 : 2);
1456
+ const column = run % width;
1457
+ const row = (run - column) / width;
1458
+ scratch[at] = vertexX - column;
1459
+ scratch[at + 1] = vertexY - row;
1460
+ const flags = scratch[record + 5] | 0;
1461
+ scratch[record + 5] = flags | (forward ? 1 : 2);
1462
+ if ((flags & (forward ? 2 : 1)) === 0) {
1463
+ return;
1464
+ }
1465
+ const far = record + (forward ? 2 : 0);
1466
+ const farX = column + scratch[far];
1467
+ const farY = row + scratch[far + 1];
1468
+ const spanX = vertexX - farX;
1469
+ const spanY = vertexY - farY;
1470
+ const span = Math.sqrt(spanX * spanX + spanY * spanY);
1471
+ for (let index = 0; index < corners; index += 1) {
1472
+ const corner = scratch[count + index];
1473
+ const cornerAt = base + COVERAGE_STRIDE_ * corner;
1474
+ const cornerColumn = corner % width;
1475
+ const cornerRow = (corner - cornerColumn) / width;
1476
+ if (Math.abs(cornerColumn + scratch[cornerAt] - farX) > 1e-9 ||
1477
+ Math.abs(cornerRow + scratch[cornerAt + 1] - farY) > 1e-9) {
1478
+ continue;
1479
+ }
1480
+ for (let end = 2; end < COVERAGE_STRIDE_; end += 2) {
1481
+ const armX = scratch[cornerAt + end] - scratch[cornerAt];
1482
+ const armY = scratch[cornerAt + end + 1] - scratch[cornerAt + 1];
1483
+ const arm = Math.sqrt(armX * armX + armY * armY);
1484
+ // the edge along the run points at this vertex
1485
+ if (arm > span && armX * spanX + armY * spanY > 0.999 * arm * span) {
1486
+ scratch[cornerAt + end] = scratch[cornerAt] + spanX;
1487
+ scratch[cornerAt + end + 1] = scratch[cornerAt + 1] + spanY;
1488
+ }
1489
+ }
1490
+ return;
1491
+ }
1492
+ }
1493
+ /**
1494
+ * Whether the end of run `run` next to a corner (see {@link endRunAt_}) has one
1495
+ * already.
1496
+ */
1497
+ function cornered_(scratch, run, forward) {
1498
+ const record = GRID_.base + COVERAGE_STRIDE_ * run;
1499
+ return ((scratch[record + 5] | 0) & (forward ? 1 : 2)) !== 0;
1500
+ }
1501
+ /**
1502
+ * The contour cell nearest the vertex `CORNER_AT_`, within `SPREAD_REACH_` of
1503
+ * its texel, that belongs to no run and holds no corner, or `-1`.
1504
+ */
1505
+ function cornerHolder_(scratch) {
1506
+ const { width, height, base, coverage } = GRID_;
1507
+ const count = width * height;
1508
+ const vertexX = CORNER_AT_[0];
1509
+ const vertexY = CORNER_AT_[1];
1510
+ const column = Math.round(vertexX);
1511
+ const row = Math.round(vertexY);
1512
+ let holder = -1;
1513
+ let nearest = Infinity;
1514
+ for (let cellRow = Math.max(0, row - SPREAD_REACH_); cellRow <= Math.min(height - 1, row + SPREAD_REACH_); cellRow += 1) {
1515
+ for (let cellColumn = Math.max(0, column - SPREAD_REACH_); cellColumn <= Math.min(width - 1, column + SPREAD_REACH_); cellColumn += 1) {
1516
+ const cell = cellRow * width + cellColumn;
1517
+ if (!isSiteCell_(coverage, cell, width, count)) {
1518
+ continue;
1519
+ }
1520
+ const label = scratch[cell];
1521
+ if (label >= 0 && (isRun_(scratch, base, label) || label === cell)) {
1522
+ continue;
1523
+ }
1524
+ const distance = (cellColumn - vertexX) * (cellColumn - vertexX) +
1525
+ (cellRow - vertexY) * (cellRow - vertexY);
1526
+ if (distance < nearest) {
1527
+ nearest = distance;
1528
+ holder = cell;
1529
+ }
1530
+ }
1531
+ }
1532
+ return holder;
1533
+ }
1534
+ /** Steps of {@link placeTip_}'s bracketing: the bracket shrinks well below 1e-4. */
1535
+ const TIP_STEPS_ = 24;
1536
+ /**
1537
+ * The shift, within `±limit`, of the vertex from the crossing along the unit
1538
+ * bisector (all three in `TIP_`) at which the corner, keeping the directions of
1539
+ * its edges, covers as much of the 3 × 3 texels around the vertex as the
1540
+ * coverage says, into `RESULT_`: the area the corner leaves in a block grows
1541
+ * monotonically as the vertex moves along the bisector, so the shift is
1542
+ * bracketed (regula falsi, Illinois variant), one polygon clip per step. At the
1543
+ * end of the range when the coverage lies beyond it. Leaves `CORNER_AT_` at the
1544
+ * last vertex tried.
1545
+ */
1546
+ function placeTip_(convex) {
1547
+ const vertexX = TIP_[0];
1548
+ const vertexY = TIP_[1];
1549
+ const bisectorX = TIP_[2];
1550
+ const bisectorY = TIP_[3];
1551
+ const limit = TIP_[4];
1552
+ const { width, height, coverage } = GRID_;
1553
+ const column = Math.round(vertexX);
1554
+ const row = Math.round(vertexY);
1555
+ const left = Math.max(0, column - 1);
1556
+ const right = Math.min(width - 1, column + 1);
1557
+ const top = Math.max(0, row - 1);
1558
+ const bottom = Math.min(height - 1, row + 1);
1559
+ let covered = 0;
1560
+ for (let cellRow = top; cellRow <= bottom; cellRow += 1) {
1561
+ for (let cellColumn = left; cellColumn <= right; cellColumn += 1) {
1562
+ covered += coverage[cellRow * width + cellColumn] / 255;
1563
+ }
1564
+ }
1565
+ let low = -limit;
1566
+ let high = limit;
1567
+ CORNER_AT_[0] = vertexX;
1568
+ CORNER_AT_[1] = vertexY;
1569
+ blockArea_(convex, left, top, right, bottom);
1570
+ const zeroExcess = RESULT_[0] - covered;
1571
+ if (Math.abs(zeroExcess) < 1e-6) {
1572
+ RESULT_[0] = 0;
1573
+ return;
1574
+ }
1575
+ let lowExcess;
1576
+ let highExcess;
1577
+ CORNER_AT_[0] = vertexX + low * bisectorX;
1578
+ CORNER_AT_[1] = vertexY + low * bisectorY;
1579
+ blockArea_(convex, left, top, right, bottom);
1580
+ lowExcess = RESULT_[0] - covered;
1581
+ if (lowExcess === 0) {
1582
+ RESULT_[0] = low;
1583
+ return;
1584
+ }
1585
+ if (lowExcess * zeroExcess < 0) {
1586
+ high = 0;
1587
+ highExcess = zeroExcess;
1588
+ }
1589
+ else {
1590
+ CORNER_AT_[0] = vertexX + high * bisectorX;
1591
+ CORNER_AT_[1] = vertexY + high * bisectorY;
1592
+ blockArea_(convex, left, top, right, bottom);
1593
+ highExcess = RESULT_[0] - covered;
1594
+ if (highExcess === 0) {
1595
+ RESULT_[0] = high;
1596
+ return;
1597
+ }
1598
+ if (zeroExcess * highExcess < 0) {
1599
+ low = 0;
1600
+ lowExcess = zeroExcess;
1601
+ }
1602
+ else {
1603
+ RESULT_[0] = Math.abs(lowExcess) < Math.abs(highExcess) ? low : high;
1604
+ return;
1605
+ }
1606
+ }
1607
+ let side = 0;
1608
+ let shift = 0;
1609
+ for (let step = 0; step < TIP_STEPS_; step += 1) {
1610
+ shift = (low * highExcess - high * lowExcess) / (highExcess - lowExcess);
1611
+ CORNER_AT_[0] = vertexX + shift * bisectorX;
1612
+ CORNER_AT_[1] = vertexY + shift * bisectorY;
1613
+ blockArea_(convex, left, top, right, bottom);
1614
+ const excess = RESULT_[0] - covered;
1615
+ if (Math.abs(excess) < 1e-6 || high - low < 1e-5) {
1616
+ break;
1617
+ }
1618
+ if (excess * highExcess > 0) {
1619
+ high = shift;
1620
+ highExcess = excess;
1621
+ if (side === 1) {
1622
+ lowExcess /= 2;
1623
+ }
1624
+ side = 1;
1625
+ }
1626
+ else {
1627
+ low = shift;
1628
+ lowExcess = excess;
1629
+ if (side === -1) {
1630
+ highExcess /= 2;
1631
+ }
1632
+ side = -1;
1633
+ }
1634
+ }
1635
+ RESULT_[0] = shift;
1636
+ }
1637
+ const BLOCK_ = new Float64Array(16);
1638
+ /**
1639
+ * The area, in texels, that the corner at `CORNER_AT_` with the
1640
+ * `CORNER_NORMALS_` covers in the texels from `(left, top)` to `(right,
1641
+ * bottom)`, into `RESULT_`: behind both edges where the corner is convex,
1642
+ * behind either where it is concave.
1643
+ */
1644
+ function blockArea_(convex, left, top, right, bottom) {
1645
+ clippedBlock_(left, top, right, bottom, 0, 2);
1646
+ if (convex) {
1647
+ return;
1648
+ }
1649
+ const both = RESULT_[0];
1650
+ clippedBlock_(left, top, right, bottom, 0, 0);
1651
+ const first = RESULT_[0];
1652
+ clippedBlock_(left, top, right, bottom, 2, 2);
1653
+ RESULT_[0] = first + RESULT_[0] - both;
1654
+ }
1655
+ /**
1656
+ * The area of the texels from `(left, top)` to `(right, bottom)` behind both
1657
+ * lines through `CORNER_AT_` whose unit outward normals start at
1658
+ * `CORNER_NORMALS_[first]` and `CORNER_NORMALS_[second]`, into `RESULT_`.
1659
+ */
1660
+ function clippedBlock_(left, top, right, bottom, first, second) {
1661
+ const vertexX = CORNER_AT_[0];
1662
+ const vertexY = CORNER_AT_[1];
1663
+ // the block's corners, relative to the vertex, where both lines pass
1664
+ let lowX = left - 0.5 - vertexX;
1665
+ let highX = right + 0.5 - vertexX;
1666
+ let lowY = top - 0.5 - vertexY;
1667
+ let highY = bottom + 0.5 - vertexY;
1668
+ const n1x = CORNER_NORMALS_[first];
1669
+ const n1y = CORNER_NORMALS_[first + 1];
1670
+ const n2x = CORNER_NORMALS_[second];
1671
+ const n2y = CORNER_NORMALS_[second + 1];
1672
+ const a1H = Math.abs(n1x) < 1e-9;
1673
+ const a1V = !a1H && Math.abs(n1y) < 1e-9;
1674
+ const a2H = first === second ? a1H : Math.abs(n2x) < 1e-9;
1675
+ const a2V = first === second ? a1V : !a2H && Math.abs(n2y) < 1e-9;
1676
+ if ((a1H || a1V) && (a2H || a2V)) {
1677
+ if (a1H) {
1678
+ if (n1y > 0) {
1679
+ if (highY > 0) {
1680
+ highY = 0;
1681
+ }
1682
+ }
1683
+ else if (lowY < 0) {
1684
+ lowY = 0;
1685
+ }
1686
+ }
1687
+ else if (n1x > 0) {
1688
+ if (highX > 0) {
1689
+ highX = 0;
1690
+ }
1691
+ }
1692
+ else if (lowX < 0) {
1693
+ lowX = 0;
1694
+ }
1695
+ if (first !== second) {
1696
+ if (a2H) {
1697
+ if (n2y > 0) {
1698
+ if (highY > 0) {
1699
+ highY = 0;
1700
+ }
1701
+ }
1702
+ else if (lowY < 0) {
1703
+ lowY = 0;
1704
+ }
1705
+ }
1706
+ else if (n2x > 0) {
1707
+ if (highX > 0) {
1708
+ highX = 0;
1709
+ }
1710
+ }
1711
+ else if (lowX < 0) {
1712
+ lowX = 0;
1713
+ }
1714
+ }
1715
+ RESULT_[0] =
1716
+ highX > lowX && highY > lowY ? (highX - lowX) * (highY - lowY) : 0;
1717
+ return;
1718
+ }
1719
+ BLOCK_[0] = lowX;
1720
+ BLOCK_[1] = lowY;
1721
+ BLOCK_[2] = highX;
1722
+ BLOCK_[3] = lowY;
1723
+ BLOCK_[4] = highX;
1724
+ BLOCK_[5] = highY;
1725
+ BLOCK_[6] = lowX;
1726
+ BLOCK_[7] = highY;
1727
+ HALF_PLANES_[0] = n1x;
1728
+ HALF_PLANES_[1] = n1y;
1729
+ HALF_PLANES_[2] = 0;
1730
+ const vertices = polygon2ClipHalfPlane(CLIP_OUT_, BLOCK_, 4, HALF_PLANES_, 0);
1731
+ // behind one line only: a second clip by it would change nothing
1732
+ if (first === second) {
1733
+ RESULT_[0] = polygon2Area(CLIP_OUT_, vertices);
1734
+ return;
1735
+ }
1736
+ HALF_PLANES_[3] = n2x;
1737
+ HALF_PLANES_[4] = n2y;
1738
+ HALF_PLANES_[5] = 0;
1739
+ RESULT_[0] = polygon2Area(CLIP_IN_, polygon2ClipHalfPlane(CLIP_IN_, CLIP_OUT_, vertices, HALF_PLANES_, 3));
1740
+ }
1741
+ /**
1742
+ * The coverage of the texel at `(column, row)` that the corner at `CORNER_AT_`
1743
+ * with the `CORNER_NORMALS_` predicts, into `RESULT_`.
1744
+ */
1745
+ function predictCorner_(convex, column, row) {
1746
+ const vertexX = CORNER_AT_[0];
1747
+ const vertexY = CORNER_AT_[1];
1748
+ const firstNormalX = CORNER_NORMALS_[0];
1749
+ const firstNormalY = CORNER_NORMALS_[1];
1750
+ const secondNormalX = CORNER_NORMALS_[2];
1751
+ const secondNormalY = CORNER_NORMALS_[3];
1752
+ const firstLimit = firstNormalX * (vertexX - column) + firstNormalY * (vertexY - row);
1753
+ const secondLimit = secondNormalX * (vertexX - column) + secondNormalY * (vertexY - row);
1754
+ const half1 = ((firstNormalX < 0 ? -firstNormalX : firstNormalX) +
1755
+ (firstNormalY < 0 ? -firstNormalY : firstNormalY)) *
1756
+ 0.5;
1757
+ const half2 = ((secondNormalX < 0 ? -secondNormalX : secondNormalX) +
1758
+ (secondNormalY < 0 ? -secondNormalY : secondNormalY)) *
1759
+ 0.5;
1760
+ if (convex) {
1761
+ if (firstLimit <= -half1 || secondLimit <= -half2) {
1762
+ RESULT_[0] = 0;
1763
+ return;
1764
+ }
1765
+ if (firstLimit >= half1) {
1766
+ EDGE_[0] = secondNormalX;
1767
+ EDGE_[1] = secondNormalY;
1768
+ EDGE_[2] = secondLimit;
1769
+ edgeCoverage_();
1770
+ RESULT_[0] = EDGE_[3];
1771
+ return;
1772
+ }
1773
+ if (secondLimit >= half2) {
1774
+ EDGE_[0] = firstNormalX;
1775
+ EDGE_[1] = firstNormalY;
1776
+ EDGE_[2] = firstLimit;
1777
+ edgeCoverage_();
1778
+ RESULT_[0] = EDGE_[3];
1779
+ return;
1780
+ }
1781
+ HALF_PLANES_[2] = firstLimit;
1782
+ HALF_PLANES_[5] = secondLimit;
1783
+ wedgeArea_();
1784
+ return;
1785
+ }
1786
+ if (firstLimit >= half1 || secondLimit >= half2) {
1787
+ RESULT_[0] = 1;
1788
+ return;
1789
+ }
1790
+ if (firstLimit <= -half1) {
1791
+ EDGE_[0] = secondNormalX;
1792
+ EDGE_[1] = secondNormalY;
1793
+ EDGE_[2] = secondLimit;
1794
+ edgeCoverage_();
1795
+ RESULT_[0] = EDGE_[3];
1796
+ return;
1797
+ }
1798
+ if (secondLimit <= -half2) {
1799
+ EDGE_[0] = firstNormalX;
1800
+ EDGE_[1] = firstNormalY;
1801
+ EDGE_[2] = firstLimit;
1802
+ edgeCoverage_();
1803
+ RESULT_[0] = EDGE_[3];
1804
+ return;
1805
+ }
1806
+ HALF_PLANES_[2] = firstLimit;
1807
+ HALF_PLANES_[5] = secondLimit;
1808
+ wedgeArea_();
1809
+ const both = RESULT_[0];
1810
+ EDGE_[0] = firstNormalX;
1811
+ EDGE_[1] = firstNormalY;
1812
+ EDGE_[2] = firstLimit;
1813
+ edgeCoverage_();
1814
+ const first = EDGE_[3];
1815
+ EDGE_[0] = secondNormalX;
1816
+ EDGE_[1] = secondNormalY;
1817
+ EDGE_[2] = secondLimit;
1818
+ edgeCoverage_();
1819
+ RESULT_[0] = first + EDGE_[3] - both;
1820
+ }
1821
+ /**
1822
+ * The largest straight-edge residual of the antialiased texels around `(x, y)`,
1823
+ * into `RESULT_`; a residual of `NaN` (a zero gradient) counts as none.
1824
+ */
1825
+ function bendNear_(residuals, x, y) {
1826
+ const { width, height, coverage } = GRID_;
1827
+ let bend = 0;
1828
+ for (let row = Math.max(0, y - 1); row <= Math.min(height - 1, y + 1); row += 1) {
1829
+ for (let column = Math.max(0, x - 1); column <= Math.min(width - 1, x + 1); column += 1) {
1830
+ const cell = row * width + column;
1831
+ const value = coverage[cell];
1832
+ if (value === 0 || value === 255) {
1833
+ continue;
1834
+ }
1835
+ const residual = residuals[cell];
1836
+ if (residual > bend) {
1837
+ bend = residual;
1838
+ }
1839
+ }
1840
+ }
1841
+ RESULT_[0] = bend;
1842
+ }
1843
+ /**
1844
+ * How far, as a fraction of a texel, the coverage of the texels within `radius`
1845
+ * (Chebyshev) of `(x, y)` and of the vertex texel `(vertexColumn, vertexRow)`
1846
+ * strays from what the corner at `CORNER_AT_` with the `CORNER_NORMALS_`
1847
+ * predicts, into `RESULT_`; once past the limit (`CLEAR_CORNER_RESIDUAL_` when
1848
+ * `clear`, else `CORNER_RESIDUAL_`), the first value found past it.
1849
+ */
1850
+ function cornerMisfit_(convex, x, y, vertexColumn, vertexRow, radius, clear) {
1851
+ const { width, height, coverage } = GRID_;
1852
+ const limit = clear ? CLEAR_CORNER_RESIDUAL_ : CORNER_RESIDUAL_;
1853
+ let misfit = 0;
1854
+ const sameCentre = x === vertexColumn && y === vertexRow;
1855
+ const passes = sameCentre ? 1 : 2;
1856
+ for (let around = 0; around < passes; around += 1) {
1857
+ const centreX = around === 0 ? x : vertexColumn;
1858
+ const centreY = around === 0 ? y : vertexRow;
1859
+ for (let row = Math.max(0, centreY - radius); row <= Math.min(height - 1, centreY + radius); row += 1) {
1860
+ for (let column = Math.max(0, centreX - radius); column <= Math.min(width - 1, centreX + radius); column += 1) {
1861
+ predictCorner_(convex, column, row);
1862
+ misfit = Math.max(misfit, Math.abs(RESULT_[0] - coverage[row * width + column] / 255));
1863
+ if (misfit > limit) {
1864
+ RESULT_[0] = misfit;
1865
+ return;
1866
+ }
1867
+ }
1868
+ }
1869
+ }
1870
+ RESULT_[0] = misfit;
1871
+ }
1872
+ const CLIP_IN_ = new Float64Array(16);
1873
+ const CLIP_OUT_ = new Float64Array(16);
1874
+ /**
1875
+ * The two half-planes a clip cuts to, `(normalX, normalY, limit)` each, as
1876
+ * `polygon2ClipHalfPlane` reads them.
1877
+ */
1878
+ const HALF_PLANES_ = new Float64Array(6);
1879
+ /**
1880
+ * The area of the unit square centred at the origin behind both edges `normal ·
1881
+ * q = limit`, the `CORNER_NORMALS_` (unit and outward) with the limits in
1882
+ * `HALF_PLANES_`, into `RESULT_`.
1883
+ */
1884
+ function wedgeArea_() {
1885
+ CLIP_IN_[0] = -0.5;
1886
+ CLIP_IN_[1] = -0.5;
1887
+ CLIP_IN_[2] = 0.5;
1888
+ CLIP_IN_[3] = -0.5;
1889
+ CLIP_IN_[4] = 0.5;
1890
+ CLIP_IN_[5] = 0.5;
1891
+ CLIP_IN_[6] = -0.5;
1892
+ CLIP_IN_[7] = 0.5;
1893
+ HALF_PLANES_[0] = CORNER_NORMALS_[0];
1894
+ HALF_PLANES_[1] = CORNER_NORMALS_[1];
1895
+ HALF_PLANES_[3] = CORNER_NORMALS_[2];
1896
+ HALF_PLANES_[4] = CORNER_NORMALS_[3];
1897
+ let vertices = polygon2ClipHalfPlane(CLIP_OUT_, CLIP_IN_, 4, HALF_PLANES_, 0);
1898
+ vertices = polygon2ClipHalfPlane(CLIP_IN_, CLIP_OUT_, vertices, HALF_PLANES_, 3);
1899
+ RESULT_[0] = polygon2Area(CLIP_IN_, vertices);
1900
+ }
1901
+ /**
1902
+ * Gives each corner's geometry to the other contour cells within
1903
+ * `SPREAD_REACH_` of its vertex that belong to no run and that it explains (see
1904
+ * {@link spreadMisfit_}), so that no straight piece there overshoots the
1905
+ * vertex; where several corners explain a cell, the best fit wins. The labels
1906
+ * record the choice before any geometry moves, so the order of the corners does
1907
+ * not matter. The `corners` holders are listed from `scratch[count]`.
1908
+ */
1909
+ let spreadCells_ = new Int32Array(0);
1910
+ function spreadCorners_(scratch, corners) {
1911
+ const { width, height, base, coverage } = GRID_;
1912
+ const count = width * height;
1913
+ let spreadCount = 0;
1914
+ for (let index = 0; index < corners; index += 1) {
1915
+ // `| 0`: integers the engine keeps as such, which a call never boxes
1916
+ const corner = scratch[count + index] | 0;
1917
+ const at = base + COVERAGE_STRIDE_ * corner;
1918
+ const cornerColumn = corner % width;
1919
+ const cornerRow = (corner - cornerColumn) / width;
1920
+ const vertexColumn = Math.round(cornerColumn + scratch[at]) | 0;
1921
+ const vertexRow = Math.round(cornerRow + scratch[at + 1]) | 0;
1922
+ const rowStart = Math.max(0, vertexRow - EDGE_SPREAD_REACH_);
1923
+ const rowEnd = Math.min(height - 1, vertexRow + EDGE_SPREAD_REACH_);
1924
+ const colStart = Math.max(0, vertexColumn - EDGE_SPREAD_REACH_);
1925
+ const colEnd = Math.min(width - 1, vertexColumn + EDGE_SPREAD_REACH_);
1926
+ for (let row = rowStart; row <= rowEnd; row += 1) {
1927
+ const dy = row >= vertexRow ? row - vertexRow : vertexRow - row;
1928
+ const rowBase = row * width;
1929
+ for (let column = colStart; column <= colEnd; column += 1) {
1930
+ const cell = rowBase + column;
1931
+ if (cell === corner) {
1932
+ continue;
1933
+ }
1934
+ const value = coverage[cell];
1935
+ if (value === 0 || value === 255) {
1936
+ const dx = column >= vertexColumn
1937
+ ? column - vertexColumn
1938
+ : vertexColumn - column;
1939
+ if (dy > SPREAD_REACH_ || dx > SPREAD_REACH_) {
1940
+ continue;
1941
+ }
1942
+ const opposite = 255 - value;
1943
+ if (!(column + 1 < width && coverage[cell + 1] === opposite) &&
1944
+ !(cell + width < count && coverage[cell + width] === opposite)) {
1945
+ continue;
1946
+ }
1947
+ }
1948
+ const held = scratch[cell];
1949
+ if (held >= 0 && (held === cell || isRun_(scratch, base, held))) {
1950
+ continue;
1951
+ }
1952
+ spreadMisfit_(scratch, corner, cell);
1953
+ const misfit = RESULT_[0];
1954
+ if (misfit < Infinity) {
1955
+ let better = held < 0;
1956
+ if (!better) {
1957
+ spreadMisfit_(scratch, held, cell);
1958
+ better = misfit < RESULT_[0];
1959
+ }
1960
+ if (better) {
1961
+ if (held < 0) {
1962
+ if (spreadCount === spreadCells_.length) {
1963
+ const grown = new Int32Array(Math.max(64, spreadCells_.length * 2));
1964
+ grown.set(spreadCells_);
1965
+ spreadCells_ = grown;
1966
+ }
1967
+ spreadCells_[spreadCount] = cell;
1968
+ spreadCount += 1;
1969
+ }
1970
+ scratch[cell] = corner;
1971
+ }
1972
+ }
1973
+ }
1974
+ }
1975
+ }
1976
+ for (let index = 0; index < spreadCount; index += 1) {
1977
+ const cell = spreadCells_[index];
1978
+ copyCorner_(scratch, scratch[cell] | 0, cell);
1979
+ }
1980
+ }
1981
+ /** Copies the corner site of cell `corner` into cell `cell`. */
1982
+ function copyCorner_(scratch, corner, cell) {
1983
+ const { width, base } = GRID_;
1984
+ const from = base + COVERAGE_STRIDE_ * corner;
1985
+ const to = base + COVERAGE_STRIDE_ * cell;
1986
+ const cellColumn = cell % width;
1987
+ const cornerColumn = corner % width;
1988
+ const shiftX = cornerColumn - cellColumn;
1989
+ const shiftY = (corner - cornerColumn) / width - (cell - cellColumn) / width;
1990
+ for (let index = 0; index < COVERAGE_STRIDE_; index += 2) {
1991
+ scratch[to + index] = scratch[from + index] + shiftX;
1992
+ scratch[to + index + 1] = scratch[from + index + 1] + shiftY;
1993
+ }
1994
+ }
1995
+ /**
1996
+ * How well the corner site of cell `corner` explains the contour of cell
1997
+ * `cell`, into `RESULT_`: smaller is better, `Infinity` when it does not. An
1998
+ * antialiased texel's coverage must be what the corner predicts, to
1999
+ * `CORNER_RESIDUAL_`, with the corner crossing it (its own straight edge may be
2000
+ * a poor estimate, as in a sliver beside a sharp tip); a full or empty texel's
2001
+ * midpoints must lie within `SPREAD_TOLERANCE_` of the corner's edges.
2002
+ */
2003
+ function spreadMisfit_(scratch, corner, cell) {
2004
+ const { width, base, coverage } = GRID_;
2005
+ const column = cell % width;
2006
+ const row = (cell - column) / width;
2007
+ const value = coverage[cell];
2008
+ if (value !== 0 && value !== 255) {
2009
+ cornerCoverage_(scratch, corner, column, row);
2010
+ const predicted = RESULT_[0];
2011
+ const misfit = Math.abs(predicted - value / 255);
2012
+ // stored per branch: a value merged from a double and `Infinity` is
2013
+ // boxed
2014
+ if (predicted > 0 && predicted < 1 && misfit <= CORNER_RESIDUAL_) {
2015
+ RESULT_[0] = misfit;
2016
+ }
2017
+ else {
2018
+ RESULT_[0] = Infinity;
2019
+ }
2020
+ return;
2021
+ }
2022
+ const at = base + COVERAGE_STRIDE_ * cell;
2023
+ let misfit = 0;
2024
+ if (scratch[at + 1] !== 0) {
2025
+ SITE_QUERY_[0] = column + 0.5;
2026
+ SITE_QUERY_[1] = row;
2027
+ siteDistanceSquared_(scratch, base, width, corner);
2028
+ misfit = Math.sqrt(SITE_QUERY_[2]);
2029
+ }
2030
+ if (scratch[at + 2] !== 0) {
2031
+ SITE_QUERY_[0] = column;
2032
+ SITE_QUERY_[1] = row + 0.5;
2033
+ siteDistanceSquared_(scratch, base, width, corner);
2034
+ misfit = Math.max(misfit, Math.sqrt(SITE_QUERY_[2]));
2035
+ }
2036
+ if (misfit <= SPREAD_TOLERANCE_) {
2037
+ RESULT_[0] = misfit;
2038
+ }
2039
+ else {
2040
+ RESULT_[0] = Infinity;
2041
+ }
2042
+ }
2043
+ /**
2044
+ * The coverage that the corner site of cell `corner` predicts for the texel at
2045
+ * `column`, `row`, into `RESULT_`: its edges as whole lines, the shape behind
2046
+ * both of them where the corner is convex, behind either where it is concave.
2047
+ */
2048
+ function cornerCoverage_(scratch, corner, column, row) {
2049
+ const { width, base } = GRID_;
2050
+ const at = base + COVERAGE_STRIDE_ * corner;
2051
+ const cornerColumn = corner % width;
2052
+ CORNER_AT_[0] = cornerColumn + scratch[at];
2053
+ CORNER_AT_[1] = (corner - cornerColumn) / width + scratch[at + 1];
2054
+ const firstX = scratch[at + 2] - scratch[at];
2055
+ const firstY = scratch[at + 3] - scratch[at + 1];
2056
+ const secondX = scratch[at + 4] - scratch[at];
2057
+ const secondY = scratch[at + 5] - scratch[at + 1];
2058
+ const firstLength = Math.sqrt(firstX * firstX + firstY * firstY);
2059
+ const secondLength = Math.sqrt(secondX * secondX + secondY * secondY);
2060
+ // inside is left of the first end and right of the second (see
2061
+ // coverageSiteSide_): these normals point outward
2062
+ CORNER_NORMALS_[0] = firstY / firstLength;
2063
+ CORNER_NORMALS_[1] = -firstX / firstLength;
2064
+ CORNER_NORMALS_[2] = -secondY / secondLength;
2065
+ CORNER_NORMALS_[3] = secondX / secondLength;
2066
+ predictCorner_(firstX * secondY - firstY * secondX > 0, column, row);
2067
+ }
2068
+ //# sourceMappingURL=_coverage-contour2.js.map