@ac-kit/math-grid 0.3.0 → 0.4.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.
@@ -0,0 +1,1670 @@
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.
91
+ */
92
+ export function locateEdge_(sites, at, coverage, value, x, y, width, height) {
93
+ sites[at + 3] = Number.NaN;
94
+ sites[at + 4] = 0;
95
+ // on the border, a centred stripe's missing samples are its own,
96
+ // reflected through the texel's centre; clamping them instead would give
97
+ // it a gradient it does not have, so the stripe is tried first there
98
+ const border = x === 0 || y === 0 || x === width - 1 || y === height - 1;
99
+ if (border &&
100
+ borderStripe_(sites, at, coverage, value, x, y, width, height)) {
101
+ return;
102
+ }
103
+ let topLeft;
104
+ let top;
105
+ let topRight;
106
+ let middleLeft;
107
+ let middleRight;
108
+ let bottomLeft;
109
+ let bottom;
110
+ let bottomRight;
111
+ if (border) {
112
+ // a missing sample continues the texels on the other side linearly
113
+ // (a one-sided difference): clamped, it would bend the gradient
114
+ topLeft = borderSample_(coverage, x, y, -1, -1, width, height, true);
115
+ top = borderSample_(coverage, x, y, 0, -1, width, height, true);
116
+ topRight = borderSample_(coverage, x, y, 1, -1, width, height, true);
117
+ middleLeft = borderSample_(coverage, x, y, -1, 0, width, height, true);
118
+ middleRight = borderSample_(coverage, x, y, 1, 0, width, height, true);
119
+ bottomLeft = borderSample_(coverage, x, y, -1, 1, width, height, true);
120
+ bottom = borderSample_(coverage, x, y, 0, 1, width, height, true);
121
+ bottomRight = borderSample_(coverage, x, y, 1, 1, width, height, true);
122
+ }
123
+ else {
124
+ const above = (y - 1) * width;
125
+ const middle = y * width;
126
+ const below = (y + 1) * width;
127
+ topLeft = coverage[above + x - 1];
128
+ top = coverage[above + x];
129
+ topRight = coverage[above + x + 1];
130
+ middleLeft = coverage[middle + x - 1];
131
+ middleRight = coverage[middle + x + 1];
132
+ bottomLeft = coverage[below + x - 1];
133
+ bottom = coverage[below + x];
134
+ bottomRight = coverage[below + x + 1];
135
+ }
136
+ // the Sobel gradient points toward more coverage; the outward normal is
137
+ // its opposite
138
+ const gradientX = topRight +
139
+ 2 * middleRight +
140
+ bottomRight -
141
+ topLeft -
142
+ 2 * middleLeft -
143
+ bottomLeft;
144
+ const gradientY = bottomLeft + 2 * bottom + bottomRight - topLeft - 2 * top - topRight;
145
+ // not Math.hypot, which the engine's middle tier calls with its doubles
146
+ // boxed
147
+ const length = Math.sqrt(gradientX * gradientX + gradientY * gradientY);
148
+ if (length === 0) {
149
+ locateStripe_(sites, at, coverage, value, x, y, width, height, middleLeft + middleRight - 2 * value, top + bottom - 2 * value, topLeft + bottomRight - topRight - bottomLeft);
150
+ return;
151
+ }
152
+ const normalX = -gradientX / length;
153
+ const normalY = -gradientY / length;
154
+ sites[at] = normalX;
155
+ sites[at + 1] = normalY;
156
+ EDGE_[0] = normalX;
157
+ EDGE_[1] = normalY;
158
+ EDGE_[2] = value / 255;
159
+ edgeOffset_();
160
+ sites[at + 2] = EDGE_[3];
161
+ }
162
+ /**
163
+ * The coverage of the texel `(dx, dy)` from `(x, y)`; outside the grid, from
164
+ * the texel opposite it through `(x, y)`: that texel's own coverage when
165
+ * `extrapolate` is false (a stripe centred on `(x, y)` repeats there), else the
166
+ * linear continuation `2 · c(x, y) − c(opposite)`; `(x, y)`'s own coverage when
167
+ * both are outside.
168
+ */
169
+ function borderSample_(coverage, x, y, dx, dy, width, height, extrapolate) {
170
+ const column = x + dx;
171
+ const row = y + dy;
172
+ if (column >= 0 && column < width && row >= 0 && row < height) {
173
+ return coverage[row * width + column];
174
+ }
175
+ const centre = coverage[y * width + x];
176
+ const oppositeColumn = x - dx;
177
+ const oppositeRow = y - dy;
178
+ if (oppositeColumn < 0 ||
179
+ oppositeColumn >= width ||
180
+ oppositeRow < 0 ||
181
+ oppositeRow >= height) {
182
+ return centre;
183
+ }
184
+ const opposite = coverage[oppositeRow * width + oppositeColumn];
185
+ return extrapolate ? 2 * centre - opposite : opposite;
186
+ }
187
+ /**
188
+ * Tries a stripe for border texel `(x, y)` (see {@link locateStripe_}), its
189
+ * missing samples reflected through its centre; returns whether one fits, as
190
+ * the samples inside the grid tell, its site then written.
191
+ */
192
+ function borderStripe_(sites, at, coverage, value, x, y, width, height) {
193
+ const topLeft = borderSample_(coverage, x, y, -1, -1, width, height, false);
194
+ const top = borderSample_(coverage, x, y, 0, -1, width, height, false);
195
+ const topRight = borderSample_(coverage, x, y, 1, -1, width, height, false);
196
+ const middleLeft = borderSample_(coverage, x, y, -1, 0, width, height, false);
197
+ const middleRight = borderSample_(coverage, x, y, 1, 0, width, height, false);
198
+ const bottomLeft = borderSample_(coverage, x, y, -1, 1, width, height, false);
199
+ const bottom = borderSample_(coverage, x, y, 0, 1, width, height, false);
200
+ const bottomRight = borderSample_(coverage, x, y, 1, 1, width, height, false);
201
+ if (topRight + 2 * middleRight + bottomRight !==
202
+ topLeft + 2 * middleLeft + bottomLeft ||
203
+ bottomLeft + 2 * bottom + bottomRight !== topLeft + 2 * top + topRight) {
204
+ return false;
205
+ }
206
+ locateStripe_(sites, at, coverage, value, x, y, width, height, middleLeft + middleRight - 2 * value, top + bottom - 2 * value, topLeft + bottomRight - topRight - bottomLeft);
207
+ return sites[at + 4] !== 0;
208
+ }
209
+ /**
210
+ * The largest coverage error, as a fraction of a texel, of a stripe's
211
+ * prediction over the texels around its own: a centred stripe of exact area
212
+ * coverage predicts them to the bytes' rounding, and a feature it does not
213
+ * describe (a dot, a crossing) misses by about its own coverage.
214
+ */
215
+ const STRIPE_RESIDUAL_ = 0.02;
216
+ /**
217
+ * The unit normals {@link locateStripe_} tries: the two principal axes of the
218
+ * second differences (written per texel), then the rows, columns and
219
+ * diagonals.
220
+ */
221
+ const STRIPE_NORMALS_ = new Float64Array([
222
+ 0,
223
+ 0,
224
+ 0,
225
+ 0,
226
+ 1,
227
+ 0,
228
+ 0,
229
+ 1,
230
+ Math.SQRT1_2,
231
+ Math.SQRT1_2,
232
+ Math.SQRT1_2,
233
+ -Math.SQRT1_2,
234
+ ]);
235
+ /**
236
+ * Writes the site of antialiased texel `(x, y)`, of coverage `value`, whose 3 ×
237
+ * 3 coverage has no gradient: symmetric about its centre, so that no straight
238
+ * edge crosses it. A stripe through its centre thinner than a texel (a
239
+ * hairline, or a thin gap in ink) is the straight feature that leaves it so: it
240
+ * runs along a principal axis of the coverage's second differences (`xx`, `yy`
241
+ * and four times `xy`, in bytes), and its width follows from the coverage. The
242
+ * stripe is kept, as `(normalX, normalY, halfWidth, NaN, kind)` with `kind` 1
243
+ * for ink between its edges and −1 for a gap, when it predicts the texels
244
+ * around to `STRIPE_RESIDUAL_` and better than a flat field does. Else the
245
+ * coverage determines nothing (a dot, stripes crossing, a uniform field) and
246
+ * the site is the texel's centre, a zero normal.
247
+ */
248
+ function locateStripe_(sites, at, coverage, value, x, y, width, height, xx, yy, xy4) {
249
+ sites[at] = 0;
250
+ sites[at + 1] = 0;
251
+ sites[at + 2] = 0;
252
+ const alpha = value / 255;
253
+ const left = Math.max(0, x - 1);
254
+ const right = Math.min(width - 1, x + 1);
255
+ const top = Math.max(0, y - 1);
256
+ const bottom = Math.min(height - 1, y + 1);
257
+ let best = 0;
258
+ for (let row = top; row <= bottom; row += 1) {
259
+ for (let column = left; column <= right; column += 1) {
260
+ best = Math.max(best, Math.abs(coverage[row * width + column] / 255 - alpha));
261
+ }
262
+ }
263
+ // the principal axis of the larger second difference, `xy` being a
264
+ // quarter of `xy4`; the stripe lies along one axis or the other. The rows,
265
+ // columns and diagonals are tried too: on the border, where samples are
266
+ // missing, the second differences may not tell them
267
+ const angle = Math.atan2(xy4 / 2, xx - yy) / 2;
268
+ STRIPE_NORMALS_[0] = Math.cos(angle);
269
+ STRIPE_NORMALS_[1] = Math.sin(angle);
270
+ STRIPE_NORMALS_[2] = -STRIPE_NORMALS_[1];
271
+ STRIPE_NORMALS_[3] = STRIPE_NORMALS_[0];
272
+ for (let candidate = 0; candidate < 12; candidate += 1) {
273
+ const normalX = STRIPE_NORMALS_[2 * (candidate >> 1)];
274
+ const normalY = STRIPE_NORMALS_[2 * (candidate >> 1) + 1];
275
+ const ink = (candidate & 1) === 0;
276
+ // the stripe covers 2 · E(halfWidth) − 1 of its texel, E the coverage
277
+ // of one edge at that offset; a gap leaves the rest
278
+ EDGE_[0] = normalX;
279
+ EDGE_[1] = normalY;
280
+ EDGE_[2] = ink ? (1 + alpha) / 2 : 1 - alpha / 2;
281
+ edgeOffset_();
282
+ const half = EDGE_[3];
283
+ let residual = 0;
284
+ for (let row = top; row <= bottom; row += 1) {
285
+ for (let column = left; column <= right; column += 1) {
286
+ const shift = normalX * (column - x) + normalY * (row - y);
287
+ EDGE_[2] = half - shift;
288
+ edgeCoverage_();
289
+ const inner = EDGE_[3];
290
+ EDGE_[2] = -half - shift;
291
+ edgeCoverage_();
292
+ const band = inner - EDGE_[3];
293
+ const predicted = ink ? band : 1 - band;
294
+ residual = Math.max(residual, Math.abs(predicted - coverage[row * width + column] / 255));
295
+ }
296
+ }
297
+ if (residual < best && residual <= STRIPE_RESIDUAL_) {
298
+ best = residual;
299
+ sites[at] = normalX;
300
+ sites[at + 1] = normalY;
301
+ sites[at + 2] = half;
302
+ sites[at + 4] = ink ? 1 : -1;
303
+ }
304
+ }
305
+ }
306
+ /**
307
+ * The arguments and result of {@link edgeOffset_} and {@link edgeCoverage_}:
308
+ * the unit outward normal, the coverage or offset, then the offset or coverage.
309
+ * A double passed to or returned from a call the engine does not inline is
310
+ * boxed, which a typed array avoids; the functions below pass their doubles so
311
+ * for that reason.
312
+ */
313
+ const EDGE_ = new Float64Array(4);
314
+ /**
315
+ * The offset, along the unit outward normal from the centre of a unit square,
316
+ * of the straight edge that covers `alpha` of it: the inverse of
317
+ * {@link edgeCoverage_}. Reads the normal and `alpha` from `EDGE_`, writes the
318
+ * offset after them.
319
+ */
320
+ function edgeOffset_() {
321
+ const normalX = EDGE_[0];
322
+ const normalY = EDGE_[1];
323
+ const alpha = EDGE_[2];
324
+ const a = Math.max(Math.abs(normalX), Math.abs(normalY));
325
+ const b = Math.min(Math.abs(normalX), Math.abs(normalY));
326
+ let offset;
327
+ if (b < 1e-6) {
328
+ offset = a * (alpha - 0.5);
329
+ }
330
+ else if (alpha <= b / (2 * a)) {
331
+ offset = -(a + b) / 2 + Math.sqrt(2 * a * b * alpha);
332
+ }
333
+ else if (alpha >= 1 - b / (2 * a)) {
334
+ offset = (a + b) / 2 - Math.sqrt(2 * a * b * (1 - alpha));
335
+ }
336
+ else {
337
+ offset = a * (alpha - 0.5);
338
+ }
339
+ EDGE_[3] = offset;
340
+ }
341
+ /**
342
+ * The fraction of a unit square covered by the half-plane behind a straight
343
+ * edge `offset` from its centre along the unit outward normal. Reads the normal
344
+ * and the offset from `EDGE_`, writes the fraction after them.
345
+ */
346
+ function edgeCoverage_() {
347
+ const normalX = EDGE_[0];
348
+ const normalY = EDGE_[1];
349
+ const offset = EDGE_[2];
350
+ const a = Math.max(Math.abs(normalX), Math.abs(normalY));
351
+ const b = Math.min(Math.abs(normalX), Math.abs(normalY));
352
+ const half = (a + b) / 2;
353
+ let covered;
354
+ if (offset <= -half) {
355
+ covered = 0;
356
+ }
357
+ else if (offset >= half) {
358
+ covered = 1;
359
+ }
360
+ else if (b >= 1e-6 && offset < -(a - b) / 2) {
361
+ covered = ((offset + half) * (offset + half)) / (2 * a * b);
362
+ }
363
+ else if (b >= 1e-6 && offset > (a - b) / 2) {
364
+ covered = 1 - ((half - offset) * (half - offset)) / (2 * a * b);
365
+ }
366
+ else {
367
+ covered = 0.5 + offset / a;
368
+ }
369
+ EDGE_[3] = covered;
370
+ }
371
+ /**
372
+ * Writes into `residuals[cell]` how far the coverage of the texels around
373
+ * antialiased texel `(x, y)`, as a fraction of a texel, strays from what its
374
+ * straight edge (at `sites[at]`) predicts; `NaN` for a texel without one (a
375
+ * zero gradient).
376
+ */
377
+ export function edgeResidual_(sites, at, coverage, x, y, width, height, residuals, cell) {
378
+ const normalX = sites[at];
379
+ const normalY = sites[at + 1];
380
+ // a stripe, or a texel whose coverage determines no feature, has no
381
+ // straight edge
382
+ if ((normalX === 0 && normalY === 0) || sites[at + 4] !== 0) {
383
+ residuals[cell] = Number.NaN;
384
+ return;
385
+ }
386
+ const offset = sites[at + 2];
387
+ EDGE_[0] = normalX;
388
+ EDGE_[1] = normalY;
389
+ let residual = 0;
390
+ for (let dy = -1; dy <= 1; dy += 1) {
391
+ const neighbourY = y + dy;
392
+ if (neighbourY < 0 || neighbourY >= height) {
393
+ continue;
394
+ }
395
+ for (let dx = -1; dx <= 1; dx += 1) {
396
+ const neighbourX = x + dx;
397
+ if (neighbourX < 0 || neighbourX >= width) {
398
+ continue;
399
+ }
400
+ EDGE_[2] = offset - normalX * dx - normalY * dy;
401
+ edgeCoverage_();
402
+ const actual = coverage[neighbourY * width + neighbourX] / 255;
403
+ residual = Math.max(residual, Math.abs(EDGE_[3] - actual));
404
+ }
405
+ }
406
+ residuals[cell] = residual;
407
+ }
408
+ /**
409
+ * The grid the contour is found in; the coverage is released at the end of
410
+ * {@link findContour_} so that no caller buffer stays referenced.
411
+ */
412
+ const NO_COVERAGE_ = new Uint8Array(0);
413
+ const GRID_ = {
414
+ width: 0,
415
+ height: 0,
416
+ base: 0,
417
+ coverage: NO_COVERAGE_,
418
+ };
419
+ /**
420
+ * Merges the straight pieces of contour of a coverage grid into runs, one
421
+ * segment site each, and places a corner where two runs meet at an angle (see
422
+ * the module notes). `scratch` holds each site cell's label in `[0, count)`
423
+ * (`UNASSIGNED_` on entry; afterwards its run's holder for a run's piece, its
424
+ * own cell for a corner's holder, the holder for a cell that took a corner,
425
+ * else negative), free room in `[count, 2 · count)`, and the site geometry from
426
+ * `2 · count`; `residuals` the straight-edge residual of each antialiased
427
+ * texel. Returns how many corners there are, their holders listed from
428
+ * `scratch[count]`.
429
+ */
430
+ export function findContour_(scratch, residuals, coverage, width, height) {
431
+ const count = width * height;
432
+ GRID_.width = width;
433
+ GRID_.height = height;
434
+ GRID_.base = 2 * count;
435
+ GRID_.coverage = coverage;
436
+ const runs = buildRuns_(scratch, residuals);
437
+ const corners = joinRuns_(scratch, residuals, runs);
438
+ spreadCorners_(scratch, corners);
439
+ GRID_.coverage = NO_COVERAGE_;
440
+ return corners;
441
+ }
442
+ /**
443
+ * Whether cell `cell` holds contour: an antialiased texel, or a full or empty
444
+ * texel with an opposite neighbour to the right or below.
445
+ */
446
+ export function isSiteCell_(coverage, cell, width, count) {
447
+ const value = coverage[cell];
448
+ if (value !== 0 && value !== 255) {
449
+ return true;
450
+ }
451
+ const opposite = 255 - value;
452
+ return (((cell % width) + 1 < width && coverage[cell + 1] === opposite) ||
453
+ (cell + width < count && coverage[cell + width] === opposite));
454
+ }
455
+ const PIECE_ = new Float64Array(4);
456
+ const SEED_PIECE_ = new Float64Array(4);
457
+ /**
458
+ * Writes into `piece` the contour point and unit outward normal `(pointX,
459
+ * pointY, normalX, normalY)` of cell `cell` when it holds one straight piece of
460
+ * contour that no run has taken yet: an antialiased texel whose 3 × 3 coverage
461
+ * is one straight edge, or a full or empty texel with a single binary
462
+ * transition (right or below).
463
+ */
464
+ function straightPiece_(scratch, residuals, cell, piece) {
465
+ const { width, height, base, coverage } = GRID_;
466
+ const value = coverage[cell];
467
+ const column = cell % width;
468
+ const row = (cell - column) / width;
469
+ if (value === 0 || value === 255) {
470
+ const opposite = 255 - value;
471
+ const right = column + 1 < width && coverage[cell + 1] === opposite;
472
+ const down = row + 1 < height && coverage[cell + width] === opposite;
473
+ if (right === down) {
474
+ return false;
475
+ }
476
+ // the flag's sign is the direction of the outward normal
477
+ const outward = value === 255 ? 1 : -1;
478
+ piece[0] = right ? column + 0.5 : column;
479
+ piece[1] = down ? row + 0.5 : row;
480
+ piece[2] = right ? outward : 0;
481
+ piece[3] = down ? outward : 0;
482
+ return true;
483
+ }
484
+ if (!(residuals[cell] <= STRAIGHT_RESIDUAL_)) {
485
+ return false;
486
+ }
487
+ const at = base + COVERAGE_STRIDE_ * cell;
488
+ const normalX = scratch[at];
489
+ const normalY = scratch[at + 1];
490
+ const offset = scratch[at + 2];
491
+ piece[0] = column + normalX * offset;
492
+ piece[1] = row + normalY * offset;
493
+ piece[2] = normalX;
494
+ piece[3] = normalY;
495
+ return true;
496
+ }
497
+ /**
498
+ * Grows a run from each straight piece no run has taken, in raster order: the
499
+ * 8-connected straight pieces whose normals turn less than `SAME_RUN_COSINE_`
500
+ * from the piece before and less than `CORNER_COSINE_` from the first, then
501
+ * fitted (see {@link fitRun_}). Returns how many runs there are; their holders
502
+ * are listed downward from `scratch[2 · count − 1]`, and each run's pieces are
503
+ * labelled with its holder, the others `LONE_`.
504
+ */
505
+ function buildRuns_(scratch, residuals) {
506
+ const { width, height } = GRID_;
507
+ const count = width * height;
508
+ let runs = 0;
509
+ for (let seed = 0; seed < count; seed += 1) {
510
+ if (scratch[seed] !== UNASSIGNED_ ||
511
+ !straightPiece_(scratch, residuals, seed, SEED_PIECE_)) {
512
+ continue;
513
+ }
514
+ // the run's pieces queue in [count, 2 · count), below the holders, and
515
+ // their geometry in RUN_PIECES_; a run stops growing at
516
+ // MAX_RUN_PIECES_ (the pieces past it start the next)
517
+ const queue = count;
518
+ let head = 0;
519
+ let tail = 1;
520
+ scratch[queue] = seed;
521
+ scratch[seed] = seed;
522
+ cachePiece_(0, seed, SEED_PIECE_);
523
+ const seedNormalX = SEED_PIECE_[2];
524
+ const seedNormalY = SEED_PIECE_[3];
525
+ while (head < tail) {
526
+ const reached = scratch[queue + head];
527
+ const reachedNormalX = RUN_PIECES_[5 * head + 2];
528
+ const reachedNormalY = RUN_PIECES_[5 * head + 3];
529
+ head += 1;
530
+ const column = reached % width;
531
+ const row = (reached - column) / width;
532
+ for (let nextRow = Math.max(0, row - 1); nextRow <= Math.min(height - 1, row + 1); nextRow += 1) {
533
+ for (let nextColumn = Math.max(0, column - 1); nextColumn <= Math.min(width - 1, column + 1); nextColumn += 1) {
534
+ const next = nextRow * width + nextColumn;
535
+ if (tail === MAX_RUN_PIECES_ ||
536
+ scratch[next] !== UNASSIGNED_ ||
537
+ !straightPiece_(scratch, residuals, next, PIECE_)) {
538
+ continue;
539
+ }
540
+ const normalX = PIECE_[2];
541
+ const normalY = PIECE_[3];
542
+ if (normalX * reachedNormalX + normalY * reachedNormalY <
543
+ SAME_RUN_COSINE_ ||
544
+ normalX * seedNormalX + normalY * seedNormalY < CORNER_COSINE_) {
545
+ continue;
546
+ }
547
+ scratch[next] = seed;
548
+ scratch[queue + tail] = next;
549
+ cachePiece_(tail, next, PIECE_);
550
+ tail += 1;
551
+ }
552
+ }
553
+ }
554
+ if (fitRun_(scratch, tail)) {
555
+ scratch[2 * count - 1 - runs] = RUN_HOLDER_[0];
556
+ runs += 1;
557
+ }
558
+ }
559
+ return runs;
560
+ }
561
+ const RUN_ = line2Create();
562
+ /** The holder {@link fitRun_} chose. */
563
+ const RUN_HOLDER_ = new Float64Array(1);
564
+ /**
565
+ * The most pieces one run grows to; a longer straight edge makes several runs,
566
+ * which meet at no corner (their normals agree).
567
+ */
568
+ const MAX_RUN_PIECES_ = 1024;
569
+ /**
570
+ * The pieces of the run being grown, `(pointX, pointY, normalX, normalY,
571
+ * alpha)` each in queue order, `alpha` the coverage of an antialiased piece and
572
+ * `-1` for a binary one: every step of the fit reads them again.
573
+ */
574
+ const RUN_PIECES_ = new Float64Array(5 * MAX_RUN_PIECES_);
575
+ /** Stores `piece`, of cell `cell`, as the `index`-th of `RUN_PIECES_`. */
576
+ function cachePiece_(index, cell, piece) {
577
+ const value = GRID_.coverage[cell];
578
+ const at = 5 * index;
579
+ RUN_PIECES_[at] = piece[0];
580
+ RUN_PIECES_[at + 1] = piece[1];
581
+ RUN_PIECES_[at + 2] = piece[2];
582
+ RUN_PIECES_[at + 3] = piece[3];
583
+ RUN_PIECES_[at + 4] = value === 0 || value === 255 ? -1 : value / 255;
584
+ }
585
+ /**
586
+ * Fits a line, by total least squares, through the contour points of the
587
+ * `members` pieces queued from `scratch[count]` (labelled with their seed): a
588
+ * first fit through all of them, then three fits each keeping the pieces near
589
+ * the last line (a quarter texel, then twice and once `RUN_TOLERANCE_`), so the
590
+ * pieces a neighbouring corner bends drop out; an antialiased piece is moved
591
+ * onto the line's normal by inverting its coverage, which the run's normal
592
+ * estimates better than the texel's Sobel gradient. A run shorter than a texel
593
+ * and a half takes its direction from its normals. When the pieces kept span
594
+ * `MIN_RUN_SPAN_`, the first of them holds the run's segment, which spans them
595
+ * and half a piece beyond (see {@link COVERAGE_STRIDE_}), the others lose their
596
+ * own, and all are labelled with the holder; the other pieces are labelled
597
+ * `LONE_`. Returns whether there is a run, its holder in `RUN_HOLDER_`.
598
+ */
599
+ function fitRun_(scratch, members) {
600
+ const { width, base } = GRID_;
601
+ const count = GRID_.width * GRID_.height;
602
+ SEED_PIECE_[0] = RUN_PIECES_[0];
603
+ SEED_PIECE_[1] = RUN_PIECES_[1];
604
+ SEED_PIECE_[2] = RUN_PIECES_[2];
605
+ SEED_PIECE_[3] = RUN_PIECES_[3];
606
+ line2Set(RUN_, SEED_PIECE_[0], SEED_PIECE_[1], -SEED_PIECE_[3], SEED_PIECE_[2]);
607
+ const fitted = fitRunPass_(scratch, members, 0) &&
608
+ fitRunPass_(scratch, members, 1) &&
609
+ fitRunPass_(scratch, members, 2) &&
610
+ fitRunPass_(scratch, members, RUN_PASS_);
611
+ let holder = -1;
612
+ let low = Infinity;
613
+ let high = -Infinity;
614
+ let lowMember = -1;
615
+ let highMember = -1;
616
+ let kept = 0;
617
+ if (fitted) {
618
+ for (let index = 0; index < members; index += 1) {
619
+ const member = scratch[count + index];
620
+ if (runMember_(scratch, index, RUN_PASS_)) {
621
+ const along = RUN_[2] * (PIECE_[0] - RUN_[0]) + RUN_[3] * (PIECE_[1] - RUN_[1]);
622
+ kept += 1;
623
+ if (along < low) {
624
+ low = along;
625
+ lowMember = member;
626
+ }
627
+ if (along > high) {
628
+ high = along;
629
+ highMember = member;
630
+ }
631
+ }
632
+ }
633
+ }
634
+ if (kept < 3 || !(high - low >= MIN_RUN_SPAN_)) {
635
+ for (let index = 0; index < members; index += 1) {
636
+ scratch[scratch[count + index]] = LONE_;
637
+ }
638
+ return false;
639
+ }
640
+ // a piece left out between the kept ones means the contour bends away
641
+ // from the line there (an arc whose two flanks are near one chord): not a
642
+ // straight run
643
+ for (let index = 0; index < members; index += 1) {
644
+ if (runMember_(scratch, index, RUN_PASS_)) {
645
+ continue;
646
+ }
647
+ const along = RUN_[2] * (PIECE_[0] - RUN_[0]) + RUN_[3] * (PIECE_[1] - RUN_[1]);
648
+ if (along > low && along < high) {
649
+ for (let other = 0; other < members; other += 1) {
650
+ scratch[scratch[count + other]] = LONE_;
651
+ }
652
+ return false;
653
+ }
654
+ }
655
+ // label the pieces before any geometry moves, membership reading it: the
656
+ // kept pieces between the extreme two merge into the run, which the one
657
+ // nearest its middle holds (farthest from the corners that may end it);
658
+ // the extreme two keep their own pieces, so that the run's ends follow the
659
+ // contour's own direction there, not the fitted line's
660
+ const middle = (low + high) / 2;
661
+ let holderGap = Infinity;
662
+ for (let index = 0; index < members; index += 1) {
663
+ const member = scratch[count + index];
664
+ const inner = member !== lowMember &&
665
+ member !== highMember &&
666
+ runMember_(scratch, index, RUN_PASS_);
667
+ scratch[member] = inner ? INNER_ : LONE_;
668
+ if (inner) {
669
+ const gap = Math.abs(RUN_[2] * (PIECE_[0] - RUN_[0]) +
670
+ RUN_[3] * (PIECE_[1] - RUN_[1]) -
671
+ middle);
672
+ if (gap < holderGap) {
673
+ holderGap = gap;
674
+ holder = member;
675
+ }
676
+ }
677
+ }
678
+ for (let index = 0; index < members; index += 1) {
679
+ const member = scratch[count + index];
680
+ if (scratch[member] === LONE_) {
681
+ continue;
682
+ }
683
+ scratch[member] = holder;
684
+ if (member !== holder) {
685
+ const at = base + COVERAGE_STRIDE_ * member;
686
+ scratch[at] = Number.NaN;
687
+ scratch[at + 1] = 0;
688
+ scratch[at + 2] = 0;
689
+ }
690
+ }
691
+ // the segment runs along the outward normal turned a quarter clockwise, so
692
+ // its normal is (directionY, −directionX), between the extreme points
693
+ let directionX = RUN_[2];
694
+ let directionY = RUN_[3];
695
+ const normalX = directionY;
696
+ const normalY = -directionX;
697
+ if (normalX * SEED_PIECE_[2] + normalY * SEED_PIECE_[3] < 0) {
698
+ directionX = -directionX;
699
+ directionY = -directionY;
700
+ const flipped = -low;
701
+ low = -high;
702
+ high = flipped;
703
+ }
704
+ const holderColumn = holder % width;
705
+ const holderRow = (holder - holderColumn) / width;
706
+ const at = base + COVERAGE_STRIDE_ * holder;
707
+ scratch[at] = RUN_[0] + directionX * low - holderColumn;
708
+ scratch[at + 1] = RUN_[1] + directionY * low - holderRow;
709
+ scratch[at + 2] = RUN_[0] + directionX * high - holderColumn;
710
+ scratch[at + 3] = RUN_[1] + directionY * high - holderRow;
711
+ scratch[at + 4] = Number.NaN;
712
+ scratch[at + 5] = 0;
713
+ RUN_HOLDER_[0] = holder;
714
+ return true;
715
+ }
716
+ /** A kept piece between a run's extreme two, before the holder is known. */
717
+ const INNER_ = -3;
718
+ /**
719
+ * Whether queued piece `member` (labelled with its seed or kept) is within
720
+ * `TOLERANCES_[pass]` of `RUN_`, with a normal turned less than
721
+ * `SAME_RUN_COSINE_` from the run's on the seed's side; pass `ALL_PIECES_`
722
+ * takes every queued piece as it is. Leaves the piece in `PIECE_`, an
723
+ * antialiased one moved onto the run's normal.
724
+ */
725
+ function runMember_(scratch, index, pass) {
726
+ const at = 5 * index;
727
+ PIECE_[0] = RUN_PIECES_[at];
728
+ PIECE_[1] = RUN_PIECES_[at + 1];
729
+ PIECE_[2] = RUN_PIECES_[at + 2];
730
+ PIECE_[3] = RUN_PIECES_[at + 3];
731
+ if (pass === ALL_PIECES_) {
732
+ return true;
733
+ }
734
+ let normalX = -RUN_[3];
735
+ let normalY = RUN_[2];
736
+ if (normalX * SEED_PIECE_[2] + normalY * SEED_PIECE_[3] < 0) {
737
+ normalX = -normalX;
738
+ normalY = -normalY;
739
+ }
740
+ if (normalX * PIECE_[2] + normalY * PIECE_[3] < SAME_RUN_COSINE_) {
741
+ return false;
742
+ }
743
+ const alpha = RUN_PIECES_[at + 4];
744
+ if (alpha >= 0) {
745
+ const { width } = GRID_;
746
+ const member = scratch[width * GRID_.height + index];
747
+ EDGE_[0] = normalX;
748
+ EDGE_[1] = normalY;
749
+ EDGE_[2] = alpha;
750
+ edgeOffset_();
751
+ const offset = EDGE_[3];
752
+ const column = member % width;
753
+ PIECE_[0] = column + normalX * offset;
754
+ PIECE_[1] = (member - column) / width + normalY * offset;
755
+ }
756
+ return (Math.abs(RUN_[2] * (PIECE_[1] - RUN_[1]) - RUN_[3] * (PIECE_[0] - RUN_[0])) <= TOLERANCES_[pass]);
757
+ }
758
+ /**
759
+ * The tolerances of {@link fitRun_}'s passes, in texels, by pass: every piece,
760
+ * a quarter texel, then twice and once `RUN_TOLERANCE_`. Passes are named by
761
+ * index, as a double passed to a call the engine does not inline is boxed.
762
+ */
763
+ const TOLERANCES_ = new Float64Array([
764
+ Infinity,
765
+ 0.25,
766
+ 2 * RUN_TOLERANCE_,
767
+ RUN_TOLERANCE_,
768
+ ]);
769
+ const ALL_PIECES_ = 0;
770
+ const RUN_PASS_ = 3;
771
+ /**
772
+ * One fit of {@link fitRun_} over the queued pieces within `TOLERANCES_[pass]`
773
+ * of `RUN_`; returns whether there was any.
774
+ */
775
+ function fitRunPass_(scratch, members, pass) {
776
+ let kept = 0;
777
+ let sumX = 0;
778
+ let sumY = 0;
779
+ let sumXX = 0;
780
+ let sumXY = 0;
781
+ let sumYY = 0;
782
+ let normalX = 0;
783
+ let normalY = 0;
784
+ let low = Infinity;
785
+ let high = -Infinity;
786
+ // moments about the run's current point keep the sums small
787
+ const originX = RUN_[0];
788
+ const originY = RUN_[1];
789
+ for (let index = 0; index < members; index += 1) {
790
+ if (!runMember_(scratch, index, pass)) {
791
+ continue;
792
+ }
793
+ const dx = PIECE_[0] - originX;
794
+ const dy = PIECE_[1] - originY;
795
+ kept += 1;
796
+ sumX += dx;
797
+ sumY += dy;
798
+ sumXX += dx * dx;
799
+ sumXY += dx * dy;
800
+ sumYY += dy * dy;
801
+ normalX += PIECE_[2];
802
+ normalY += PIECE_[3];
803
+ const along = RUN_[2] * dx + RUN_[3] * dy;
804
+ low = Math.min(low, along);
805
+ high = Math.max(high, along);
806
+ }
807
+ if (kept === 0) {
808
+ return false;
809
+ }
810
+ const meanX = sumX / kept;
811
+ const meanY = sumY / kept;
812
+ const xx = sumXX - kept * meanX * meanX;
813
+ const xy = sumXY - kept * meanX * meanY;
814
+ const yy = sumYY - kept * meanY * meanY;
815
+ let directionX;
816
+ let directionY;
817
+ if (high - low < 1.5) {
818
+ // too short a run for its points to give the direction: its normals do
819
+ const length = Math.sqrt(normalX * normalX + normalY * normalY);
820
+ directionX = -normalY / length;
821
+ directionY = normalX / length;
822
+ }
823
+ else {
824
+ const angle = Math.atan2(2 * xy, xx - yy) / 2;
825
+ directionX = Math.cos(angle);
826
+ directionY = Math.sin(angle);
827
+ }
828
+ line2Set(RUN_, originX + meanX, originY + meanY, directionX, directionY);
829
+ return true;
830
+ }
831
+ /**
832
+ * The outward normals of the corner being tried, the first run's then the
833
+ * second's.
834
+ */
835
+ const CORNER_NORMALS_ = new Float64Array(4);
836
+ /**
837
+ * The vertex the corner functions below measure at, then their scalar results:
838
+ * a double passed to or returned from a call the engine does not inline is
839
+ * boxed, which a typed array avoids, so these functions pass their doubles
840
+ * through `CORNER_AT_` and `RESULT_`.
841
+ */
842
+ const CORNER_AT_ = new Float64Array(2);
843
+ const RESULT_ = new Float64Array(1);
844
+ const RUN_A_ = line2Create();
845
+ const RUN_B_ = line2Create();
846
+ const VERTEX_ = vec2Create();
847
+ /** The window of {@link joinRuns_}'s walk: visited cells, and its queue. */
848
+ const WALK_SPAN_ = 2 * JUNCTION_REACH_ + 1;
849
+ const WALK_SEEN_ = new Uint8Array(WALK_SPAN_ * WALK_SPAN_);
850
+ const WALK_QUEUE_ = new Int32Array(WALK_SPAN_ * WALK_SPAN_);
851
+ /** The runs one walk met, by holder. */
852
+ const MET_ = new Float64Array(WALK_SPAN_ * WALK_SPAN_);
853
+ /**
854
+ * Tries a corner between each run and the runs met by walking, from either end
855
+ * of it, through up to `JUNCTION_REACH_` texels of contour that belong to no
856
+ * run (see {@link tryCorner_}). Returns how many corners there are, their
857
+ * holders listed from `scratch[count]`.
858
+ */
859
+ function joinRuns_(scratch, residuals, runs) {
860
+ const { width, height, base } = GRID_;
861
+ const count = width * height;
862
+ let corners = 0;
863
+ for (let index = 0; index < runs; index += 1) {
864
+ const run = scratch[2 * count - 1 - index];
865
+ const runColumn = run % width;
866
+ const runRow = (run - runColumn) / width;
867
+ const at = base + COVERAGE_STRIDE_ * run;
868
+ for (let end = 0; end < 2; end += 1) {
869
+ const endX = runColumn + scratch[at + 2 * end];
870
+ const endY = runRow + scratch[at + 2 * end + 1];
871
+ // `| 0`: a cell index, never a boxed −0
872
+ const met = walkFrom_(scratch, run, Math.round(endX) | 0, Math.round(endY) | 0);
873
+ for (let other = 0; other < met; other += 1) {
874
+ const holder = tryCorner_(scratch, residuals, run, MET_[other], corners);
875
+ if (holder >= 0) {
876
+ scratch[count + corners] = holder;
877
+ corners += 1;
878
+ }
879
+ }
880
+ }
881
+ }
882
+ return corners;
883
+ }
884
+ /**
885
+ * Walks, breadth first, from cell `(startX, startY)` through the contour cells
886
+ * within `JUNCTION_REACH_` of it that belong to no run, and lists in `MET_` the
887
+ * other runs than `run` it reaches; returns how many.
888
+ */
889
+ function walkFrom_(scratch, run, startX, startY) {
890
+ const { width, height, base, coverage } = GRID_;
891
+ const count = width * height;
892
+ if (startX < 0 || startX >= width || startY < 0 || startY >= height) {
893
+ return 0;
894
+ }
895
+ WALK_SEEN_.fill(0);
896
+ let head = 0;
897
+ let tail = 1;
898
+ let met = 0;
899
+ WALK_QUEUE_[0] = startY * width + startX;
900
+ WALK_SEEN_[JUNCTION_REACH_ * WALK_SPAN_ + JUNCTION_REACH_] = 1;
901
+ while (head < tail) {
902
+ const cell = WALK_QUEUE_[head];
903
+ head += 1;
904
+ const column = cell % width;
905
+ const row = (cell - column) / width;
906
+ for (let nextRow = Math.max(0, row - 1, startY - JUNCTION_REACH_); nextRow <= Math.min(height - 1, row + 1, startY + JUNCTION_REACH_); nextRow += 1) {
907
+ for (let nextColumn = Math.max(0, column - 1, startX - JUNCTION_REACH_); nextColumn <= Math.min(width - 1, column + 1, startX + JUNCTION_REACH_); nextColumn += 1) {
908
+ const local = (nextRow - startY + JUNCTION_REACH_) * WALK_SPAN_ +
909
+ nextColumn -
910
+ startX +
911
+ JUNCTION_REACH_;
912
+ if (WALK_SEEN_[local] === 1) {
913
+ continue;
914
+ }
915
+ WALK_SEEN_[local] = 1;
916
+ const next = nextRow * width + nextColumn;
917
+ if (!isSiteCell_(coverage, next, width, count)) {
918
+ continue;
919
+ }
920
+ const label = scratch[next];
921
+ if (label >= 0 && isRun_(scratch, base, label)) {
922
+ if (label !== run && !listed_(met, label)) {
923
+ MET_[met] = label;
924
+ met += 1;
925
+ }
926
+ continue;
927
+ }
928
+ WALK_QUEUE_[tail] = next;
929
+ tail += 1;
930
+ }
931
+ }
932
+ }
933
+ return met;
934
+ }
935
+ function listed_(met, holder) {
936
+ for (let index = 0; index < met; index += 1) {
937
+ if (MET_[index] === holder) {
938
+ return true;
939
+ }
940
+ }
941
+ return false;
942
+ }
943
+ /** Whether the site of cell `cell` is a run's segment. */
944
+ function isRun_(scratch, base, cell) {
945
+ const at = base + COVERAGE_STRIDE_ * cell;
946
+ // NaN differs from itself (Number.isNaN boxes in an engine tier)
947
+ const first = scratch[at];
948
+ const fourth = scratch[at + 3];
949
+ const fifth = scratch[at + 4];
950
+ return first === first && fourth === fourth && fifth !== fifth;
951
+ }
952
+ /** Whether the site of cell `cell` is a corner. */
953
+ export function isCorner_(scratch, base, cell) {
954
+ const at = base + COVERAGE_STRIDE_ * cell;
955
+ // NaN differs from itself (Number.isNaN boxes in an engine tier)
956
+ const first = scratch[at];
957
+ const fourth = scratch[at + 3];
958
+ const fifth = scratch[at + 4];
959
+ return first === first && fourth === fourth && fifth === fifth;
960
+ }
961
+ /**
962
+ * Loads the segment of run `run` into `line` (from its start, unit direction)
963
+ * and writes its length into `RESULT_`.
964
+ */
965
+ function loadRun_(scratch, run, line) {
966
+ const { width, base } = GRID_;
967
+ const at = base + COVERAGE_STRIDE_ * run;
968
+ const column = run % width;
969
+ const row = (run - column) / width;
970
+ const startX = column + scratch[at];
971
+ const startY = row + scratch[at + 1];
972
+ const directionX = column + scratch[at + 2] - startX;
973
+ const directionY = row + scratch[at + 3] - startY;
974
+ const length = Math.sqrt(directionX * directionX + directionY * directionY);
975
+ line2Set(line, startX, startY, directionX / length, directionY / length);
976
+ RESULT_[0] = length;
977
+ }
978
+ /**
979
+ * A run leaving a corner: see {@link armOf_}, which reads the run's length and
980
+ * the vertex's parameter from the last two entries.
981
+ */
982
+ const ARM_ = new Float64Array(5);
983
+ /**
984
+ * How a run (from its start, of length `ARM_[3]`, between its inner extreme
985
+ * points) leaves the vertex at parameter `ARM_[4]` along it: into `ARM_`, the
986
+ * direction sign (+1 along the run, −1 against), the distance from the vertex
987
+ * to half a texel past its far end, and to its near end. Returns false when the
988
+ * run lies on both sides of the vertex (more than half a texel past it).
989
+ */
990
+ function armOf_() {
991
+ const length = ARM_[3];
992
+ const vertex = ARM_[4];
993
+ if (vertex <= 0.5) {
994
+ ARM_[0] = 1;
995
+ ARM_[1] = length - vertex + 0.5;
996
+ ARM_[2] = -vertex;
997
+ return true;
998
+ }
999
+ if (vertex >= length - 0.5) {
1000
+ ARM_[0] = -1;
1001
+ ARM_[1] = vertex + 0.5;
1002
+ ARM_[2] = vertex - length;
1003
+ return true;
1004
+ }
1005
+ return false;
1006
+ }
1007
+ /**
1008
+ * Places the corner of runs `first` and `second` when they make one: their
1009
+ * normals differ by `CORNER_COSINE_`, their lines cross within `VERTEX_REACH_`
1010
+ * of both near ends, beyond neither, and the corner predicts the coverage
1011
+ * around the vertex (see the acceptance below). The corner's site goes to the
1012
+ * contour cell nearest the vertex that belongs to no run and holds no corner,
1013
+ * its runs end at the vertex, and its edges reach their far ends. Returns the
1014
+ * holder, or `-1`.
1015
+ */
1016
+ function tryCorner_(scratch, residuals, first, second, corners) {
1017
+ const { width, base } = GRID_;
1018
+ loadRun_(scratch, first, RUN_A_);
1019
+ const firstLength = RESULT_[0];
1020
+ loadRun_(scratch, second, RUN_B_);
1021
+ const secondLength = RESULT_[0];
1022
+ // outward normals (directionY, −directionX), see fitRun_
1023
+ const firstNormalX = RUN_A_[3];
1024
+ const firstNormalY = -RUN_A_[2];
1025
+ const secondNormalX = RUN_B_[3];
1026
+ const secondNormalY = -RUN_B_[2];
1027
+ if (firstNormalX * secondNormalX + firstNormalY * secondNormalY >
1028
+ CORNER_COSINE_ ||
1029
+ !line2IntersectLine2(VERTEX_, RUN_A_, RUN_B_, 0)) {
1030
+ return -1;
1031
+ }
1032
+ const vertexX = VERTEX_[0];
1033
+ const vertexY = VERTEX_[1];
1034
+ ARM_[3] = firstLength;
1035
+ ARM_[4] =
1036
+ RUN_A_[2] * (vertexX - RUN_A_[0]) + RUN_A_[3] * (vertexY - RUN_A_[1]);
1037
+ if (!armOf_()) {
1038
+ return -1;
1039
+ }
1040
+ const firstSign = ARM_[0];
1041
+ const firstReach = ARM_[1];
1042
+ const firstNear = ARM_[2];
1043
+ ARM_[3] = secondLength;
1044
+ ARM_[4] =
1045
+ RUN_B_[2] * (vertexX - RUN_B_[0]) + RUN_B_[3] * (vertexY - RUN_B_[1]);
1046
+ if (!armOf_()) {
1047
+ return -1;
1048
+ }
1049
+ const secondSign = ARM_[0];
1050
+ const secondReach = ARM_[1];
1051
+ const secondNear = ARM_[2];
1052
+ if (firstNear > VERTEX_REACH_ ||
1053
+ secondNear > VERTEX_REACH_ ||
1054
+ cornered_(scratch, first, firstSign > 0) ||
1055
+ cornered_(scratch, second, secondSign > 0)) {
1056
+ return -1;
1057
+ }
1058
+ // the edges leaving the vertex
1059
+ const firstArmX = firstSign * RUN_A_[2];
1060
+ const firstArmY = firstSign * RUN_A_[3];
1061
+ const secondArmX = secondSign * RUN_B_[2];
1062
+ const secondArmY = secondSign * RUN_B_[3];
1063
+ CORNER_NORMALS_[0] = firstNormalX;
1064
+ CORNER_NORMALS_[1] = firstNormalY;
1065
+ CORNER_NORMALS_[2] = secondNormalX;
1066
+ CORNER_NORMALS_[3] = secondNormalY;
1067
+ // convex: the second edge, leaving the vertex, goes behind the first, so
1068
+ // the shape is the intersection of the two half-planes, not their union
1069
+ const convex = firstNormalX * secondArmX + firstNormalY * secondArmY <= 0;
1070
+ // `| 0`: cell coordinates, never a boxed −0
1071
+ const crossingColumn = Math.round(vertexX) | 0;
1072
+ const crossingRow = Math.round(vertexY) | 0;
1073
+ CORNER_AT_[0] = vertexX;
1074
+ CORNER_AT_[1] = vertexY;
1075
+ const holder = cornerHolder_(scratch);
1076
+ if (holder < 0) {
1077
+ return -1;
1078
+ }
1079
+ const holderColumn = holder % width;
1080
+ const holderRow = (holder - holderColumn) / width;
1081
+ bendNear_(residuals, crossingColumn, crossingRow);
1082
+ const bent = RESULT_[0] >= BENT_RESIDUAL_;
1083
+ let bisectorX = firstArmX + secondArmX;
1084
+ let bisectorY = firstArmY + secondArmY;
1085
+ const bisectorLength = Math.sqrt(bisectorX * bisectorX + bisectorY * bisectorY);
1086
+ bisectorX /= bisectorLength;
1087
+ bisectorY /= bisectorLength;
1088
+ const halfSine = Math.abs(bisectorX * firstNormalX + bisectorY * firstNormalY);
1089
+ // a corner is clear when its crossing predicts the coverage closely; else
1090
+ // the texels next to it must bend as a smooth curve's do not, and the
1091
+ // corner predict the coverage: from its crossing, or, at a tip sharper
1092
+ // than `SHARP_TIP_HALF_SINE_` allows (where the crossing is
1093
+ // ill-conditioned), placed and over the 5 × 5 texels around (a curve's
1094
+ // tangents fit it to about 0.03–0.05 near where they meet, not farther);
1095
+ // the misfit is measured only as far as the decision needs
1096
+ cornerMisfit_(convex, holderColumn, holderRow, crossingColumn, crossingRow, 1, !bent);
1097
+ const misfit = RESULT_[0];
1098
+ if (misfit > CLEAR_CORNER_RESIDUAL_ &&
1099
+ (!bent || (misfit > CORNER_RESIDUAL_ && halfSine > SHARP_TIP_HALF_SINE_))) {
1100
+ return -1;
1101
+ }
1102
+ // the runs' lines cross at a shallow angle at a sharp tip, where a small
1103
+ // error in either moves the crossing far: the coverage around the vertex
1104
+ // places it along the bisector, the lines moving at most
1105
+ // 2 · RUN_TOLERANCE_ across themselves
1106
+ TIP_[0] = vertexX;
1107
+ TIP_[1] = vertexY;
1108
+ TIP_[2] = bisectorX;
1109
+ TIP_[3] = bisectorY;
1110
+ TIP_[4] = (2 * RUN_TOLERANCE_) / halfSine;
1111
+ placeTip_(convex);
1112
+ const shift = RESULT_[0];
1113
+ const placedX = vertexX + shift * bisectorX;
1114
+ const placedY = vertexY + shift * bisectorY;
1115
+ CORNER_AT_[0] = placedX;
1116
+ CORNER_AT_[1] = placedY;
1117
+ if (misfit > CORNER_RESIDUAL_) {
1118
+ cornerMisfit_(convex, holderColumn, holderRow, Math.round(placedX) | 0, Math.round(placedY) | 0, 2, false);
1119
+ if (RESULT_[0] > CORNER_RESIDUAL_) {
1120
+ return -1;
1121
+ }
1122
+ }
1123
+ const halfCosine = bisectorX * firstArmX + bisectorY * firstArmY;
1124
+ ARM_LENGTH_[0] = firstArmX;
1125
+ ARM_LENGTH_[1] = firstArmY;
1126
+ ARM_LENGTH_[2] = firstReach;
1127
+ ARM_LENGTH_[3] = firstNear;
1128
+ armLength_(first);
1129
+ const firstEnd = RESULT_[0] - shift * halfCosine;
1130
+ ARM_LENGTH_[0] = secondArmX;
1131
+ ARM_LENGTH_[1] = secondArmY;
1132
+ ARM_LENGTH_[2] = secondReach;
1133
+ ARM_LENGTH_[3] = secondNear;
1134
+ armLength_(second);
1135
+ const secondEnd = RESULT_[0] - shift * halfCosine;
1136
+ // the ends are ordered so that the turn from the first to the second is
1137
+ // counter-clockwise (positive cross product) exactly when the corner is
1138
+ // convex, which tells inside from outside
1139
+ const firstX = firstArmX * firstEnd;
1140
+ const firstY = firstArmY * firstEnd;
1141
+ const secondX = secondArmX * secondEnd;
1142
+ const secondY = secondArmY * secondEnd;
1143
+ const swap = firstX * secondY - firstY * secondX > 0 !== convex;
1144
+ const at = base + COVERAGE_STRIDE_ * holder;
1145
+ scratch[at] = placedX - holderColumn;
1146
+ scratch[at + 1] = placedY - holderRow;
1147
+ scratch[at + 2] = placedX + (swap ? secondX : firstX) - holderColumn;
1148
+ scratch[at + 3] = placedY + (swap ? secondY : firstY) - holderRow;
1149
+ scratch[at + 4] = placedX + (swap ? firstX : secondX) - holderColumn;
1150
+ scratch[at + 5] = placedY + (swap ? firstY : secondY) - holderRow;
1151
+ scratch[holder] = holder;
1152
+ // the runs end at the vertex, which their last pieces may overshoot
1153
+ endRunAt_(scratch, first, firstSign > 0, corners);
1154
+ endRunAt_(scratch, second, secondSign > 0, corners);
1155
+ return holder;
1156
+ }
1157
+ /**
1158
+ * The inputs of {@link placeTip_}: the crossing, the unit bisector, and the
1159
+ * largest shift along it.
1160
+ */
1161
+ const TIP_ = new Float64Array(5);
1162
+ /**
1163
+ * The inputs of {@link armLength_}: the edge's unit direction leaving the
1164
+ * vertex, the distance to half a texel past the run's far end and to its near
1165
+ * end.
1166
+ */
1167
+ const ARM_LENGTH_ = new Float64Array(4);
1168
+ /**
1169
+ * How far from the vertex `CORNER_AT_` a corner's edge along run `run`, leaving
1170
+ * the vertex along the direction in `ARM_LENGTH_`, reaches (into `RESULT_`):
1171
+ * past the texels the corner may replace, `near` being the distance to the
1172
+ * run's near end and `reach` half a texel past its far one; or over the whole
1173
+ * run when that would reach the run's holder, where the corner would tie with
1174
+ * the run and hide it from the vector propagation's neighbours (a corner later
1175
+ * placed at the far end shortens the edge to its vertex).
1176
+ */
1177
+ function armLength_(run) {
1178
+ const directionX = ARM_LENGTH_[0];
1179
+ const directionY = ARM_LENGTH_[1];
1180
+ const reach = ARM_LENGTH_[2];
1181
+ const near = ARM_LENGTH_[3];
1182
+ const vertexX = CORNER_AT_[0];
1183
+ const vertexY = CORNER_AT_[1];
1184
+ const whole = reach - 0.5;
1185
+ const short = Math.min(whole, near + SPREAD_REACH_ + 2);
1186
+ const { width } = GRID_;
1187
+ const column = run % width;
1188
+ const holder = directionX * (column - vertexX) +
1189
+ directionY * ((run - column) / width - vertexY);
1190
+ RESULT_[0] = holder <= short + 1 ? whole : short;
1191
+ }
1192
+ /**
1193
+ * Moves the end of run `run` next to a corner (its start when the run leaves
1194
+ * the vertex along its direction, `forward`, else its end) onto the vertex
1195
+ * `CORNER_AT_`, and marks that end as taken. When the far end has a corner
1196
+ * already (one of the `corners` listed from `scratch[count]`, its vertex
1197
+ * there), that corner's edge along the run stops at this vertex.
1198
+ */
1199
+ function endRunAt_(scratch, run, forward, corners) {
1200
+ const { width, height, base } = GRID_;
1201
+ const count = width * height;
1202
+ const vertexX = CORNER_AT_[0];
1203
+ const vertexY = CORNER_AT_[1];
1204
+ const record = base + COVERAGE_STRIDE_ * run;
1205
+ const at = record + (forward ? 0 : 2);
1206
+ const column = run % width;
1207
+ const row = (run - column) / width;
1208
+ scratch[at] = vertexX - column;
1209
+ scratch[at + 1] = vertexY - row;
1210
+ const flags = scratch[record + 5] | 0;
1211
+ scratch[record + 5] = flags | (forward ? 1 : 2);
1212
+ if ((flags & (forward ? 2 : 1)) === 0) {
1213
+ return;
1214
+ }
1215
+ const far = record + (forward ? 2 : 0);
1216
+ const farX = column + scratch[far];
1217
+ const farY = row + scratch[far + 1];
1218
+ const spanX = vertexX - farX;
1219
+ const spanY = vertexY - farY;
1220
+ const span = Math.sqrt(spanX * spanX + spanY * spanY);
1221
+ for (let index = 0; index < corners; index += 1) {
1222
+ const corner = scratch[count + index];
1223
+ const cornerAt = base + COVERAGE_STRIDE_ * corner;
1224
+ const cornerColumn = corner % width;
1225
+ const cornerRow = (corner - cornerColumn) / width;
1226
+ if (Math.abs(cornerColumn + scratch[cornerAt] - farX) > 1e-9 ||
1227
+ Math.abs(cornerRow + scratch[cornerAt + 1] - farY) > 1e-9) {
1228
+ continue;
1229
+ }
1230
+ for (let end = 2; end < COVERAGE_STRIDE_; end += 2) {
1231
+ const armX = scratch[cornerAt + end] - scratch[cornerAt];
1232
+ const armY = scratch[cornerAt + end + 1] - scratch[cornerAt + 1];
1233
+ const arm = Math.sqrt(armX * armX + armY * armY);
1234
+ // the edge along the run points at this vertex
1235
+ if (arm > span && armX * spanX + armY * spanY > 0.999 * arm * span) {
1236
+ scratch[cornerAt + end] = scratch[cornerAt] + spanX;
1237
+ scratch[cornerAt + end + 1] = scratch[cornerAt + 1] + spanY;
1238
+ }
1239
+ }
1240
+ return;
1241
+ }
1242
+ }
1243
+ /**
1244
+ * Whether the end of run `run` next to a corner (see {@link endRunAt_}) has one
1245
+ * already.
1246
+ */
1247
+ function cornered_(scratch, run, forward) {
1248
+ const record = GRID_.base + COVERAGE_STRIDE_ * run;
1249
+ return ((scratch[record + 5] | 0) & (forward ? 1 : 2)) !== 0;
1250
+ }
1251
+ /**
1252
+ * The contour cell nearest the vertex `CORNER_AT_`, within `SPREAD_REACH_` of
1253
+ * its texel, that belongs to no run and holds no corner, or `-1`.
1254
+ */
1255
+ function cornerHolder_(scratch) {
1256
+ const { width, height, base, coverage } = GRID_;
1257
+ const count = width * height;
1258
+ const vertexX = CORNER_AT_[0];
1259
+ const vertexY = CORNER_AT_[1];
1260
+ const column = Math.round(vertexX);
1261
+ const row = Math.round(vertexY);
1262
+ let holder = -1;
1263
+ let nearest = Infinity;
1264
+ for (let cellRow = Math.max(0, row - SPREAD_REACH_); cellRow <= Math.min(height - 1, row + SPREAD_REACH_); cellRow += 1) {
1265
+ for (let cellColumn = Math.max(0, column - SPREAD_REACH_); cellColumn <= Math.min(width - 1, column + SPREAD_REACH_); cellColumn += 1) {
1266
+ const cell = cellRow * width + cellColumn;
1267
+ if (!isSiteCell_(coverage, cell, width, count)) {
1268
+ continue;
1269
+ }
1270
+ const label = scratch[cell];
1271
+ if (label >= 0 && (isRun_(scratch, base, label) || label === cell)) {
1272
+ continue;
1273
+ }
1274
+ const distance = (cellColumn - vertexX) * (cellColumn - vertexX) +
1275
+ (cellRow - vertexY) * (cellRow - vertexY);
1276
+ if (distance < nearest) {
1277
+ nearest = distance;
1278
+ holder = cell;
1279
+ }
1280
+ }
1281
+ }
1282
+ return holder;
1283
+ }
1284
+ /** Steps of {@link placeTip_}'s bracketing: the bracket shrinks well below 1e-4. */
1285
+ const TIP_STEPS_ = 24;
1286
+ /**
1287
+ * The shift, within `±limit`, of the vertex from the crossing along the unit
1288
+ * bisector (all three in `TIP_`) at which the corner, keeping the directions of
1289
+ * its edges, covers as much of the 3 × 3 texels around the vertex as the
1290
+ * coverage says, into `RESULT_`: the area the corner leaves in a block grows
1291
+ * monotonically as the vertex moves along the bisector, so the shift is
1292
+ * bracketed (regula falsi, Illinois variant), one polygon clip per step. At the
1293
+ * end of the range when the coverage lies beyond it. Leaves `CORNER_AT_` at the
1294
+ * last vertex tried.
1295
+ */
1296
+ function placeTip_(convex) {
1297
+ const vertexX = TIP_[0];
1298
+ const vertexY = TIP_[1];
1299
+ const bisectorX = TIP_[2];
1300
+ const bisectorY = TIP_[3];
1301
+ const limit = TIP_[4];
1302
+ const { width, height, coverage } = GRID_;
1303
+ const column = Math.round(vertexX);
1304
+ const row = Math.round(vertexY);
1305
+ const left = Math.max(0, column - 1);
1306
+ const right = Math.min(width - 1, column + 1);
1307
+ const top = Math.max(0, row - 1);
1308
+ const bottom = Math.min(height - 1, row + 1);
1309
+ let covered = 0;
1310
+ for (let cellRow = top; cellRow <= bottom; cellRow += 1) {
1311
+ for (let cellColumn = left; cellColumn <= right; cellColumn += 1) {
1312
+ covered += coverage[cellRow * width + cellColumn] / 255;
1313
+ }
1314
+ }
1315
+ let low = -limit;
1316
+ let high = limit;
1317
+ CORNER_AT_[0] = vertexX + low * bisectorX;
1318
+ CORNER_AT_[1] = vertexY + low * bisectorY;
1319
+ blockArea_(convex, left, top, right, bottom);
1320
+ let lowExcess = RESULT_[0] - covered;
1321
+ CORNER_AT_[0] = vertexX + high * bisectorX;
1322
+ CORNER_AT_[1] = vertexY + high * bisectorY;
1323
+ blockArea_(convex, left, top, right, bottom);
1324
+ let highExcess = RESULT_[0] - covered;
1325
+ if (lowExcess === 0) {
1326
+ RESULT_[0] = low;
1327
+ return;
1328
+ }
1329
+ if (highExcess === 0 || lowExcess * highExcess > 0) {
1330
+ RESULT_[0] = Math.abs(lowExcess) < Math.abs(highExcess) ? low : high;
1331
+ return;
1332
+ }
1333
+ let side = 0;
1334
+ let shift = 0;
1335
+ for (let step = 0; step < TIP_STEPS_; step += 1) {
1336
+ shift = (low * highExcess - high * lowExcess) / (highExcess - lowExcess);
1337
+ CORNER_AT_[0] = vertexX + shift * bisectorX;
1338
+ CORNER_AT_[1] = vertexY + shift * bisectorY;
1339
+ blockArea_(convex, left, top, right, bottom);
1340
+ const excess = RESULT_[0] - covered;
1341
+ if (Math.abs(excess) < 1e-9 || high - low < 1e-6) {
1342
+ break;
1343
+ }
1344
+ if (excess * highExcess > 0) {
1345
+ high = shift;
1346
+ highExcess = excess;
1347
+ if (side === 1) {
1348
+ lowExcess /= 2;
1349
+ }
1350
+ side = 1;
1351
+ }
1352
+ else {
1353
+ low = shift;
1354
+ lowExcess = excess;
1355
+ if (side === -1) {
1356
+ highExcess /= 2;
1357
+ }
1358
+ side = -1;
1359
+ }
1360
+ }
1361
+ RESULT_[0] = shift;
1362
+ }
1363
+ const BLOCK_ = new Float64Array(16);
1364
+ /**
1365
+ * The area, in texels, that the corner at `CORNER_AT_` with the
1366
+ * `CORNER_NORMALS_` covers in the texels from `(left, top)` to `(right,
1367
+ * bottom)`, into `RESULT_`: behind both edges where the corner is convex,
1368
+ * behind either where it is concave.
1369
+ */
1370
+ function blockArea_(convex, left, top, right, bottom) {
1371
+ clippedBlock_(left, top, right, bottom, 0, 2);
1372
+ if (convex) {
1373
+ return;
1374
+ }
1375
+ const both = RESULT_[0];
1376
+ clippedBlock_(left, top, right, bottom, 0, 0);
1377
+ const first = RESULT_[0];
1378
+ clippedBlock_(left, top, right, bottom, 2, 2);
1379
+ RESULT_[0] = first + RESULT_[0] - both;
1380
+ }
1381
+ /**
1382
+ * The area of the texels from `(left, top)` to `(right, bottom)` behind both
1383
+ * lines through `CORNER_AT_` whose unit outward normals start at
1384
+ * `CORNER_NORMALS_[first]` and `CORNER_NORMALS_[second]`, into `RESULT_`.
1385
+ */
1386
+ function clippedBlock_(left, top, right, bottom, first, second) {
1387
+ const vertexX = CORNER_AT_[0];
1388
+ const vertexY = CORNER_AT_[1];
1389
+ // the block's corners, relative to the vertex, where both lines pass
1390
+ const lowX = left - 0.5 - vertexX;
1391
+ const highX = right + 0.5 - vertexX;
1392
+ const lowY = top - 0.5 - vertexY;
1393
+ const highY = bottom + 0.5 - vertexY;
1394
+ BLOCK_[0] = lowX;
1395
+ BLOCK_[1] = lowY;
1396
+ BLOCK_[2] = highX;
1397
+ BLOCK_[3] = lowY;
1398
+ BLOCK_[4] = highX;
1399
+ BLOCK_[5] = highY;
1400
+ BLOCK_[6] = lowX;
1401
+ BLOCK_[7] = highY;
1402
+ HALF_PLANES_[0] = CORNER_NORMALS_[first];
1403
+ HALF_PLANES_[1] = CORNER_NORMALS_[first + 1];
1404
+ HALF_PLANES_[2] = 0;
1405
+ const vertices = polygon2ClipHalfPlane(CLIP_OUT_, BLOCK_, 4, HALF_PLANES_, 0);
1406
+ // behind one line only: a second clip by it would change nothing
1407
+ if (first === second) {
1408
+ RESULT_[0] = polygon2Area(CLIP_OUT_, vertices);
1409
+ return;
1410
+ }
1411
+ HALF_PLANES_[3] = CORNER_NORMALS_[second];
1412
+ HALF_PLANES_[4] = CORNER_NORMALS_[second + 1];
1413
+ HALF_PLANES_[5] = 0;
1414
+ RESULT_[0] = polygon2Area(CLIP_IN_, polygon2ClipHalfPlane(CLIP_IN_, CLIP_OUT_, vertices, HALF_PLANES_, 3));
1415
+ }
1416
+ /**
1417
+ * The coverage of the texel at `(column, row)` that the corner at `CORNER_AT_`
1418
+ * with the `CORNER_NORMALS_` predicts, into `RESULT_`.
1419
+ */
1420
+ function predictCorner_(convex, column, row) {
1421
+ const vertexX = CORNER_AT_[0];
1422
+ const vertexY = CORNER_AT_[1];
1423
+ const firstNormalX = CORNER_NORMALS_[0];
1424
+ const firstNormalY = CORNER_NORMALS_[1];
1425
+ const secondNormalX = CORNER_NORMALS_[2];
1426
+ const secondNormalY = CORNER_NORMALS_[3];
1427
+ const firstLimit = firstNormalX * (vertexX - column) + firstNormalY * (vertexY - row);
1428
+ const secondLimit = secondNormalX * (vertexX - column) + secondNormalY * (vertexY - row);
1429
+ HALF_PLANES_[2] = firstLimit;
1430
+ HALF_PLANES_[5] = secondLimit;
1431
+ wedgeArea_();
1432
+ if (convex) {
1433
+ return;
1434
+ }
1435
+ const both = RESULT_[0];
1436
+ EDGE_[0] = firstNormalX;
1437
+ EDGE_[1] = firstNormalY;
1438
+ EDGE_[2] = firstLimit;
1439
+ edgeCoverage_();
1440
+ const first = EDGE_[3];
1441
+ EDGE_[0] = secondNormalX;
1442
+ EDGE_[1] = secondNormalY;
1443
+ EDGE_[2] = secondLimit;
1444
+ edgeCoverage_();
1445
+ RESULT_[0] = first + EDGE_[3] - both;
1446
+ }
1447
+ /**
1448
+ * The largest straight-edge residual of the antialiased texels around `(x, y)`,
1449
+ * into `RESULT_`; a residual of `NaN` (a zero gradient) counts as none.
1450
+ */
1451
+ function bendNear_(residuals, x, y) {
1452
+ const { width, height, coverage } = GRID_;
1453
+ let bend = 0;
1454
+ for (let row = Math.max(0, y - 1); row <= Math.min(height - 1, y + 1); row += 1) {
1455
+ for (let column = Math.max(0, x - 1); column <= Math.min(width - 1, x + 1); column += 1) {
1456
+ const cell = row * width + column;
1457
+ const value = coverage[cell];
1458
+ if (value === 0 || value === 255) {
1459
+ continue;
1460
+ }
1461
+ const residual = residuals[cell];
1462
+ if (residual > bend) {
1463
+ bend = residual;
1464
+ }
1465
+ }
1466
+ }
1467
+ RESULT_[0] = bend;
1468
+ }
1469
+ /**
1470
+ * How far, as a fraction of a texel, the coverage of the texels within `radius`
1471
+ * (Chebyshev) of `(x, y)` and of the vertex texel `(vertexColumn, vertexRow)`
1472
+ * strays from what the corner at `CORNER_AT_` with the `CORNER_NORMALS_`
1473
+ * predicts, into `RESULT_`; once past the limit (`CLEAR_CORNER_RESIDUAL_` when
1474
+ * `clear`, else `CORNER_RESIDUAL_`), the first value found past it.
1475
+ */
1476
+ function cornerMisfit_(convex, x, y, vertexColumn, vertexRow, radius, clear) {
1477
+ const { width, height, coverage } = GRID_;
1478
+ const limit = clear ? CLEAR_CORNER_RESIDUAL_ : CORNER_RESIDUAL_;
1479
+ let misfit = 0;
1480
+ for (let around = 0; around < 2; around += 1) {
1481
+ const centreX = around === 0 ? x : vertexColumn;
1482
+ const centreY = around === 0 ? y : vertexRow;
1483
+ for (let row = Math.max(0, centreY - radius); row <= Math.min(height - 1, centreY + radius); row += 1) {
1484
+ for (let column = Math.max(0, centreX - radius); column <= Math.min(width - 1, centreX + radius); column += 1) {
1485
+ predictCorner_(convex, column, row);
1486
+ misfit = Math.max(misfit, Math.abs(RESULT_[0] - coverage[row * width + column] / 255));
1487
+ if (misfit > limit) {
1488
+ RESULT_[0] = misfit;
1489
+ return;
1490
+ }
1491
+ }
1492
+ }
1493
+ }
1494
+ RESULT_[0] = misfit;
1495
+ }
1496
+ const CLIP_IN_ = new Float64Array(16);
1497
+ const CLIP_OUT_ = new Float64Array(16);
1498
+ /**
1499
+ * The two half-planes a clip cuts to, `(normalX, normalY, limit)` each, as
1500
+ * `polygon2ClipHalfPlane` reads them.
1501
+ */
1502
+ const HALF_PLANES_ = new Float64Array(6);
1503
+ /**
1504
+ * The area of the unit square centred at the origin behind both edges `normal ·
1505
+ * q = limit`, the `CORNER_NORMALS_` (unit and outward) with the limits in
1506
+ * `HALF_PLANES_`, into `RESULT_`.
1507
+ */
1508
+ function wedgeArea_() {
1509
+ CLIP_IN_[0] = -0.5;
1510
+ CLIP_IN_[1] = -0.5;
1511
+ CLIP_IN_[2] = 0.5;
1512
+ CLIP_IN_[3] = -0.5;
1513
+ CLIP_IN_[4] = 0.5;
1514
+ CLIP_IN_[5] = 0.5;
1515
+ CLIP_IN_[6] = -0.5;
1516
+ CLIP_IN_[7] = 0.5;
1517
+ HALF_PLANES_[0] = CORNER_NORMALS_[0];
1518
+ HALF_PLANES_[1] = CORNER_NORMALS_[1];
1519
+ HALF_PLANES_[3] = CORNER_NORMALS_[2];
1520
+ HALF_PLANES_[4] = CORNER_NORMALS_[3];
1521
+ let vertices = polygon2ClipHalfPlane(CLIP_OUT_, CLIP_IN_, 4, HALF_PLANES_, 0);
1522
+ vertices = polygon2ClipHalfPlane(CLIP_IN_, CLIP_OUT_, vertices, HALF_PLANES_, 3);
1523
+ RESULT_[0] = polygon2Area(CLIP_IN_, vertices);
1524
+ }
1525
+ /**
1526
+ * Gives each corner's geometry to the other contour cells within
1527
+ * `SPREAD_REACH_` of its vertex that belong to no run and that it explains (see
1528
+ * {@link spreadMisfit_}), so that no straight piece there overshoots the
1529
+ * vertex; where several corners explain a cell, the best fit wins. The labels
1530
+ * record the choice before any geometry moves, so the order of the corners does
1531
+ * not matter. The `corners` holders are listed from `scratch[count]`.
1532
+ */
1533
+ function spreadCorners_(scratch, corners) {
1534
+ const { width, height, base, coverage } = GRID_;
1535
+ const count = width * height;
1536
+ for (let pass = 0; pass < 2; pass += 1) {
1537
+ for (let index = 0; index < corners; index += 1) {
1538
+ // `| 0`: integers the engine keeps as such, which a call never boxes
1539
+ const corner = scratch[count + index] | 0;
1540
+ const at = base + COVERAGE_STRIDE_ * corner;
1541
+ const cornerColumn = corner % width;
1542
+ const cornerRow = (corner - cornerColumn) / width;
1543
+ const vertexColumn = Math.round(cornerColumn + scratch[at]) | 0;
1544
+ const vertexRow = Math.round(cornerRow + scratch[at + 1]) | 0;
1545
+ for (let row = Math.max(0, vertexRow - EDGE_SPREAD_REACH_); row <= Math.min(height - 1, vertexRow + EDGE_SPREAD_REACH_); row += 1) {
1546
+ for (let column = Math.max(0, vertexColumn - EDGE_SPREAD_REACH_); column <= Math.min(width - 1, vertexColumn + EDGE_SPREAD_REACH_); column += 1) {
1547
+ const cell = row * width + column;
1548
+ if (cell === corner || !isSiteCell_(coverage, cell, width, count)) {
1549
+ continue;
1550
+ }
1551
+ const value = coverage[cell];
1552
+ if ((value === 0 || value === 255) &&
1553
+ Math.max(Math.abs(row - vertexRow), Math.abs(column - vertexColumn)) > SPREAD_REACH_) {
1554
+ continue;
1555
+ }
1556
+ const held = scratch[cell];
1557
+ if (pass === 1) {
1558
+ if (held === corner) {
1559
+ copyCorner_(scratch, corner, cell);
1560
+ }
1561
+ continue;
1562
+ }
1563
+ if (held >= 0 && (held === cell || isRun_(scratch, base, held))) {
1564
+ continue;
1565
+ }
1566
+ spreadMisfit_(scratch, corner, cell);
1567
+ const misfit = RESULT_[0];
1568
+ if (misfit < Infinity) {
1569
+ let better = held < 0;
1570
+ if (!better) {
1571
+ spreadMisfit_(scratch, held, cell);
1572
+ better = misfit < RESULT_[0];
1573
+ }
1574
+ if (better) {
1575
+ scratch[cell] = corner;
1576
+ }
1577
+ }
1578
+ }
1579
+ }
1580
+ }
1581
+ }
1582
+ }
1583
+ /** Copies the corner site of cell `corner` into cell `cell`. */
1584
+ function copyCorner_(scratch, corner, cell) {
1585
+ const { width, base } = GRID_;
1586
+ const from = base + COVERAGE_STRIDE_ * corner;
1587
+ const to = base + COVERAGE_STRIDE_ * cell;
1588
+ const cellColumn = cell % width;
1589
+ const cornerColumn = corner % width;
1590
+ const shiftX = cornerColumn - cellColumn;
1591
+ const shiftY = (corner - cornerColumn) / width - (cell - cellColumn) / width;
1592
+ for (let index = 0; index < COVERAGE_STRIDE_; index += 2) {
1593
+ scratch[to + index] = scratch[from + index] + shiftX;
1594
+ scratch[to + index + 1] = scratch[from + index + 1] + shiftY;
1595
+ }
1596
+ }
1597
+ /**
1598
+ * How well the corner site of cell `corner` explains the contour of cell
1599
+ * `cell`, into `RESULT_`: smaller is better, `Infinity` when it does not. An
1600
+ * antialiased texel's coverage must be what the corner predicts, to
1601
+ * `CORNER_RESIDUAL_`, with the corner crossing it (its own straight edge may be
1602
+ * a poor estimate, as in a sliver beside a sharp tip); a full or empty texel's
1603
+ * midpoints must lie within `SPREAD_TOLERANCE_` of the corner's edges.
1604
+ */
1605
+ function spreadMisfit_(scratch, corner, cell) {
1606
+ const { width, base, coverage } = GRID_;
1607
+ const column = cell % width;
1608
+ const row = (cell - column) / width;
1609
+ const value = coverage[cell];
1610
+ if (value !== 0 && value !== 255) {
1611
+ cornerCoverage_(scratch, corner, column, row);
1612
+ const predicted = RESULT_[0];
1613
+ const misfit = Math.abs(predicted - value / 255);
1614
+ // stored per branch: a value merged from a double and `Infinity` is
1615
+ // boxed
1616
+ if (predicted > 0 && predicted < 1 && misfit <= CORNER_RESIDUAL_) {
1617
+ RESULT_[0] = misfit;
1618
+ }
1619
+ else {
1620
+ RESULT_[0] = Infinity;
1621
+ }
1622
+ return;
1623
+ }
1624
+ const at = base + COVERAGE_STRIDE_ * cell;
1625
+ let misfit = 0;
1626
+ if (scratch[at + 1] !== 0) {
1627
+ SITE_QUERY_[0] = column + 0.5;
1628
+ SITE_QUERY_[1] = row;
1629
+ siteDistanceSquared_(scratch, base, width, corner);
1630
+ misfit = Math.sqrt(SITE_QUERY_[2]);
1631
+ }
1632
+ if (scratch[at + 2] !== 0) {
1633
+ SITE_QUERY_[0] = column;
1634
+ SITE_QUERY_[1] = row + 0.5;
1635
+ siteDistanceSquared_(scratch, base, width, corner);
1636
+ misfit = Math.max(misfit, Math.sqrt(SITE_QUERY_[2]));
1637
+ }
1638
+ if (misfit <= SPREAD_TOLERANCE_) {
1639
+ RESULT_[0] = misfit;
1640
+ }
1641
+ else {
1642
+ RESULT_[0] = Infinity;
1643
+ }
1644
+ }
1645
+ /**
1646
+ * The coverage that the corner site of cell `corner` predicts for the texel at
1647
+ * `column`, `row`, into `RESULT_`: its edges as whole lines, the shape behind
1648
+ * both of them where the corner is convex, behind either where it is concave.
1649
+ */
1650
+ function cornerCoverage_(scratch, corner, column, row) {
1651
+ const { width, base } = GRID_;
1652
+ const at = base + COVERAGE_STRIDE_ * corner;
1653
+ const cornerColumn = corner % width;
1654
+ CORNER_AT_[0] = cornerColumn + scratch[at];
1655
+ CORNER_AT_[1] = (corner - cornerColumn) / width + scratch[at + 1];
1656
+ const firstX = scratch[at + 2] - scratch[at];
1657
+ const firstY = scratch[at + 3] - scratch[at + 1];
1658
+ const secondX = scratch[at + 4] - scratch[at];
1659
+ const secondY = scratch[at + 5] - scratch[at + 1];
1660
+ const firstLength = Math.sqrt(firstX * firstX + firstY * firstY);
1661
+ const secondLength = Math.sqrt(secondX * secondX + secondY * secondY);
1662
+ // inside is left of the first end and right of the second (see
1663
+ // coverageSiteSide_): these normals point outward
1664
+ CORNER_NORMALS_[0] = firstY / firstLength;
1665
+ CORNER_NORMALS_[1] = -firstX / firstLength;
1666
+ CORNER_NORMALS_[2] = -secondY / secondLength;
1667
+ CORNER_NORMALS_[3] = secondX / secondLength;
1668
+ predictCorner_(firstX * secondY - firstY * secondX > 0, column, row);
1669
+ }
1670
+ //# sourceMappingURL=_coverage-contour2.js.map