@ccpc/math 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +21 -0
  3. package/dist/constants/geom_type.d.ts +13 -0
  4. package/dist/constants/geom_type.d.ts.map +1 -0
  5. package/dist/constants/geom_type.js +17 -0
  6. package/dist/constants/math_const.d.ts +9 -0
  7. package/dist/constants/math_const.d.ts.map +1 -0
  8. package/dist/constants/math_const.js +12 -0
  9. package/dist/core/box2.d.ts +71 -0
  10. package/dist/core/box2.d.ts.map +1 -0
  11. package/dist/core/box2.js +243 -0
  12. package/dist/core/coord2d.d.ts +62 -0
  13. package/dist/core/coord2d.d.ts.map +1 -0
  14. package/dist/core/coord2d.js +155 -0
  15. package/dist/core/geom_base.d.ts +19 -0
  16. package/dist/core/geom_base.d.ts.map +1 -0
  17. package/dist/core/geom_base.js +18 -0
  18. package/dist/core/mat3.d.ts +101 -0
  19. package/dist/core/mat3.d.ts.map +1 -0
  20. package/dist/core/mat3.js +290 -0
  21. package/dist/core/vec2.d.ts +138 -0
  22. package/dist/core/vec2.d.ts.map +1 -0
  23. package/dist/core/vec2.js +297 -0
  24. package/dist/curves/arc2.d.ts +49 -0
  25. package/dist/curves/arc2.d.ts.map +1 -0
  26. package/dist/curves/arc2.js +265 -0
  27. package/dist/curves/bspline2.d.ts +150 -0
  28. package/dist/curves/bspline2.d.ts.map +1 -0
  29. package/dist/curves/bspline2.js +793 -0
  30. package/dist/curves/circle2.d.ts +42 -0
  31. package/dist/curves/circle2.d.ts.map +1 -0
  32. package/dist/curves/circle2.js +135 -0
  33. package/dist/curves/circle_curve2.d.ts +38 -0
  34. package/dist/curves/circle_curve2.d.ts.map +1 -0
  35. package/dist/curves/circle_curve2.js +112 -0
  36. package/dist/curves/curve2.d.ts +214 -0
  37. package/dist/curves/curve2.d.ts.map +1 -0
  38. package/dist/curves/curve2.js +238 -0
  39. package/dist/curves/ellipse2.d.ts +42 -0
  40. package/dist/curves/ellipse2.d.ts.map +1 -0
  41. package/dist/curves/ellipse2.js +125 -0
  42. package/dist/curves/ellipse_arc2.d.ts +49 -0
  43. package/dist/curves/ellipse_arc2.d.ts.map +1 -0
  44. package/dist/curves/ellipse_arc2.js +184 -0
  45. package/dist/curves/ellipse_curve2.d.ts +56 -0
  46. package/dist/curves/ellipse_curve2.d.ts.map +1 -0
  47. package/dist/curves/ellipse_curve2.js +262 -0
  48. package/dist/curves/interval.d.ts +112 -0
  49. package/dist/curves/interval.d.ts.map +1 -0
  50. package/dist/curves/interval.js +200 -0
  51. package/dist/curves/line2.d.ts +64 -0
  52. package/dist/curves/line2.d.ts.map +1 -0
  53. package/dist/curves/line2.js +193 -0
  54. package/dist/curves/period_interval.d.ts +129 -0
  55. package/dist/curves/period_interval.d.ts.map +1 -0
  56. package/dist/curves/period_interval.js +240 -0
  57. package/dist/discretize/discretize_defaults.d.ts +12 -0
  58. package/dist/discretize/discretize_defaults.d.ts.map +1 -0
  59. package/dist/discretize/discretize_defaults.js +12 -0
  60. package/dist/discretize/discretize_engine.d.ts +33 -0
  61. package/dist/discretize/discretize_engine.d.ts.map +1 -0
  62. package/dist/discretize/discretize_engine.js +347 -0
  63. package/dist/discretize/discretize_errors.d.ts +15 -0
  64. package/dist/discretize/discretize_errors.d.ts.map +1 -0
  65. package/dist/discretize/discretize_errors.js +30 -0
  66. package/dist/discretize/discretize_options.d.ts +18 -0
  67. package/dist/discretize/discretize_options.d.ts.map +1 -0
  68. package/dist/discretize/discretize_options.js +19 -0
  69. package/dist/discretize/discretize_types.d.ts +36 -0
  70. package/dist/discretize/discretize_types.d.ts.map +1 -0
  71. package/dist/discretize/discretize_types.js +1 -0
  72. package/dist/discretize/internal/curve_guards.d.ts +35 -0
  73. package/dist/discretize/internal/curve_guards.d.ts.map +1 -0
  74. package/dist/discretize/internal/curve_guards.js +62 -0
  75. package/dist/discretize/internal/postprocess.d.ts +5 -0
  76. package/dist/discretize/internal/postprocess.d.ts.map +1 -0
  77. package/dist/discretize/internal/postprocess.js +109 -0
  78. package/dist/discretize/internal/sampling_utils.d.ts +8 -0
  79. package/dist/discretize/internal/sampling_utils.d.ts.map +1 -0
  80. package/dist/discretize/internal/sampling_utils.js +36 -0
  81. package/dist/discretize/register_builtin_strategies.d.ts +3 -0
  82. package/dist/discretize/register_builtin_strategies.d.ts.map +1 -0
  83. package/dist/discretize/register_builtin_strategies.js +10 -0
  84. package/dist/discretize/strategies/bspline_strategy.d.ts +4 -0
  85. package/dist/discretize/strategies/bspline_strategy.d.ts.map +1 -0
  86. package/dist/discretize/strategies/bspline_strategy.js +115 -0
  87. package/dist/discretize/strategies/circle_strategy.d.ts +7 -0
  88. package/dist/discretize/strategies/circle_strategy.d.ts.map +1 -0
  89. package/dist/discretize/strategies/circle_strategy.js +55 -0
  90. package/dist/discretize/strategies/ellipse_strategy.d.ts +7 -0
  91. package/dist/discretize/strategies/ellipse_strategy.d.ts.map +1 -0
  92. package/dist/discretize/strategies/ellipse_strategy.js +86 -0
  93. package/dist/discretize/strategies/line_strategy.d.ts +4 -0
  94. package/dist/discretize/strategies/line_strategy.d.ts.map +1 -0
  95. package/dist/discretize/strategies/line_strategy.js +40 -0
  96. package/dist/discretize/strategy_registry.d.ts +9 -0
  97. package/dist/discretize/strategy_registry.d.ts.map +1 -0
  98. package/dist/discretize/strategy_registry.js +34 -0
  99. package/dist/index.d.ts +30 -0
  100. package/dist/index.d.ts.map +1 -0
  101. package/dist/index.js +24 -0
  102. package/dist/intersections/analytic_x_algorithm.d.ts +10 -0
  103. package/dist/intersections/analytic_x_algorithm.d.ts.map +1 -0
  104. package/dist/intersections/analytic_x_algorithm.js +83 -0
  105. package/dist/intersections/curve_x_engine.d.ts +9 -0
  106. package/dist/intersections/curve_x_engine.d.ts.map +1 -0
  107. package/dist/intersections/curve_x_engine.js +27 -0
  108. package/dist/intersections/index.d.ts +5 -0
  109. package/dist/intersections/index.d.ts.map +1 -0
  110. package/dist/intersections/index.js +11 -0
  111. package/dist/intersections/internal/certification.d.ts +34 -0
  112. package/dist/intersections/internal/certification.d.ts.map +1 -0
  113. package/dist/intersections/internal/certification.js +238 -0
  114. package/dist/intersections/internal/interval_clipping.d.ts +29 -0
  115. package/dist/intersections/internal/interval_clipping.d.ts.map +1 -0
  116. package/dist/intersections/internal/interval_clipping.js +123 -0
  117. package/dist/intersections/internal/kind.d.ts +4 -0
  118. package/dist/intersections/internal/kind.d.ts.map +1 -0
  119. package/dist/intersections/internal/kind.js +16 -0
  120. package/dist/intersections/internal/pair.d.ts +9 -0
  121. package/dist/intersections/internal/pair.d.ts.map +1 -0
  122. package/dist/intersections/internal/pair.js +14 -0
  123. package/dist/intersections/internal/result.d.ts +20 -0
  124. package/dist/intersections/internal/result.d.ts.map +1 -0
  125. package/dist/intersections/internal/result.js +125 -0
  126. package/dist/intersections/internal/sampling.d.ts +15 -0
  127. package/dist/intersections/internal/sampling.d.ts.map +1 -0
  128. package/dist/intersections/internal/sampling.js +131 -0
  129. package/dist/intersections/internal/segment.d.ts +32 -0
  130. package/dist/intersections/internal/segment.d.ts.map +1 -0
  131. package/dist/intersections/internal/segment.js +137 -0
  132. package/dist/intersections/internal/tolerance.d.ts +10 -0
  133. package/dist/intersections/internal/tolerance.d.ts.map +1 -0
  134. package/dist/intersections/internal/tolerance.js +20 -0
  135. package/dist/intersections/intersector.d.ts +6 -0
  136. package/dist/intersections/intersector.d.ts.map +1 -0
  137. package/dist/intersections/intersector.js +1 -0
  138. package/dist/intersections/numeric_x_algorithm.d.ts +10 -0
  139. package/dist/intersections/numeric_x_algorithm.d.ts.map +1 -0
  140. package/dist/intersections/numeric_x_algorithm.js +73 -0
  141. package/dist/intersections/solvers/bspline_self_solver.d.ts +7 -0
  142. package/dist/intersections/solvers/bspline_self_solver.d.ts.map +1 -0
  143. package/dist/intersections/solvers/bspline_self_solver.js +308 -0
  144. package/dist/intersections/solvers/line_line_pair_solver.d.ts +7 -0
  145. package/dist/intersections/solvers/line_line_pair_solver.d.ts.map +1 -0
  146. package/dist/intersections/solvers/line_line_pair_solver.js +35 -0
  147. package/dist/intersections/solvers/pair_solvers.d.ts +94 -0
  148. package/dist/intersections/solvers/pair_solvers.d.ts.map +1 -0
  149. package/dist/intersections/solvers/pair_solvers.js +1078 -0
  150. package/dist/intersections/solvers/polyline_pair_intersector.d.ts +51 -0
  151. package/dist/intersections/solvers/polyline_pair_intersector.d.ts.map +1 -0
  152. package/dist/intersections/solvers/polyline_pair_intersector.js +731 -0
  153. package/dist/intersections/types.d.ts +11 -0
  154. package/dist/intersections/types.d.ts.map +1 -0
  155. package/dist/intersections/types.js +1 -0
  156. package/dist/serialize/dump_types.d.ts +101 -0
  157. package/dist/serialize/dump_types.d.ts.map +1 -0
  158. package/dist/serialize/dump_types.js +5 -0
  159. package/dist/serialize/geom_mgr.d.ts +24 -0
  160. package/dist/serialize/geom_mgr.d.ts.map +1 -0
  161. package/dist/serialize/geom_mgr.js +30 -0
  162. package/dist/types/type_define.d.ts +29 -0
  163. package/dist/types/type_define.d.ts.map +1 -0
  164. package/dist/types/type_define.js +10 -0
  165. package/dist/types/type_guard.d.ts +46 -0
  166. package/dist/types/type_guard.d.ts.map +1 -0
  167. package/dist/types/type_guard.js +5 -0
  168. package/dist/utils/math_error.d.ts +16 -0
  169. package/dist/utils/math_error.d.ts.map +1 -0
  170. package/dist/utils/math_error.js +35 -0
  171. package/dist/utils/math_utils.d.ts +9 -0
  172. package/dist/utils/math_utils.d.ts.map +1 -0
  173. package/dist/utils/math_utils.js +25 -0
  174. package/dist/utils/precision.d.ts +29 -0
  175. package/dist/utils/precision.d.ts.map +1 -0
  176. package/dist/utils/precision.js +44 -0
  177. package/package.json +38 -0
@@ -0,0 +1,731 @@
1
+ import { Interval } from '../../curves/interval';
2
+ import { Precision } from '../../utils/precision';
3
+ import { certifyOverlapMonotone, certifyParamPair, projectRangeToCurve } from '../internal/certification';
4
+ import { collectIntervalClipSeeds } from '../internal/interval_clipping';
5
+ import { intersectSegments, lerp, makeSegment, segmentBoxesMayIntersect, segmentDistance } from '../internal/segment';
6
+ import { sampleCurveAdaptive } from '../internal/sampling';
7
+ import { makeIntersectionTolerance } from '../internal/tolerance';
8
+ class SegmentHashIndex {
9
+ constructor(segments, pad) {
10
+ this.segments = segments;
11
+ this.map = new Map();
12
+ this.overflow = [];
13
+ let minX = Number.POSITIVE_INFINITY;
14
+ let minY = Number.POSITIVE_INFINITY;
15
+ let maxX = Number.NEGATIVE_INFINITY;
16
+ let maxY = Number.NEGATIVE_INFINITY;
17
+ for (const s of segments) {
18
+ minX = Math.min(minX, s.seg.minX);
19
+ minY = Math.min(minY, s.seg.minY);
20
+ maxX = Math.max(maxX, s.seg.maxX);
21
+ maxY = Math.max(maxY, s.seg.maxY);
22
+ }
23
+ if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY)) {
24
+ minX = minY = 0;
25
+ maxX = maxY = 1;
26
+ }
27
+ const count = Math.max(1, segments.length);
28
+ const grid = clampInt(Math.round(Math.sqrt(count)), 8, 64);
29
+ const spanX = Math.max(maxX - minX, pad * 2, Precision.CURVE_LENGTH_EPS);
30
+ const spanY = Math.max(maxY - minY, pad * 2, Precision.CURVE_LENGTH_EPS);
31
+ this.minX = minX - pad;
32
+ this.minY = minY - pad;
33
+ this.gridX = grid;
34
+ this.gridY = grid;
35
+ this.cellSizeX = spanX / this.gridX;
36
+ this.cellSizeY = spanY / this.gridY;
37
+ const maxCellsPerSegment = 64;
38
+ for (let i = 0; i < segments.length; i++) {
39
+ const seg = segments[i].seg;
40
+ const ix0 = this.toX(seg.minX - pad);
41
+ const ix1 = this.toX(seg.maxX + pad);
42
+ const iy0 = this.toY(seg.minY - pad);
43
+ const iy1 = this.toY(seg.maxY + pad);
44
+ const cells = (ix1 - ix0 + 1) * (iy1 - iy0 + 1);
45
+ if (cells > maxCellsPerSegment) {
46
+ this.overflow.push(i);
47
+ continue;
48
+ }
49
+ for (let ix = ix0; ix <= ix1; ix++) {
50
+ for (let iy = iy0; iy <= iy1; iy++) {
51
+ const key = this.key(ix, iy);
52
+ const list = this.map.get(key);
53
+ if (list) {
54
+ list.push(i);
55
+ }
56
+ else {
57
+ this.map.set(key, [i]);
58
+ }
59
+ }
60
+ }
61
+ }
62
+ }
63
+ query(seg, pad, marks, stamp) {
64
+ const ret = [];
65
+ const ix0 = this.toX(seg.seg.minX - pad);
66
+ const ix1 = this.toX(seg.seg.maxX + pad);
67
+ const iy0 = this.toY(seg.seg.minY - pad);
68
+ const iy1 = this.toY(seg.seg.maxY + pad);
69
+ for (let ix = ix0; ix <= ix1; ix++) {
70
+ for (let iy = iy0; iy <= iy1; iy++) {
71
+ const list = this.map.get(this.key(ix, iy));
72
+ if (!list)
73
+ continue;
74
+ for (const j of list) {
75
+ if (marks[j] === stamp)
76
+ continue;
77
+ marks[j] = stamp;
78
+ ret.push(j);
79
+ }
80
+ }
81
+ }
82
+ for (const j of this.overflow) {
83
+ if (marks[j] === stamp)
84
+ continue;
85
+ marks[j] = stamp;
86
+ ret.push(j);
87
+ }
88
+ return ret;
89
+ }
90
+ toX(x) {
91
+ const raw = Math.floor((x - this.minX) / this.cellSizeX);
92
+ return clampInt(raw, 0, this.gridX - 1);
93
+ }
94
+ toY(y) {
95
+ const raw = Math.floor((y - this.minY) / this.cellSizeY);
96
+ return clampInt(raw, 0, this.gridY - 1);
97
+ }
98
+ key(ix, iy) {
99
+ return `${ix},${iy}`;
100
+ }
101
+ }
102
+ const polylineDiagnostics = {
103
+ numericClosestFallbackCount: 0,
104
+ analyticClosestFallbackCount: 0,
105
+ recursiveNodesVisited: 0,
106
+ recursiveAbortCount: 0,
107
+ refineFailureCount: 0,
108
+ certificationRejectCount: 0,
109
+ certificationMissCount: 0,
110
+ degenerateRescueCount: 0,
111
+ rescuePassCount: 0,
112
+ rescueSeedCount: 0,
113
+ rescueHitCount: 0,
114
+ candidateSeedCount: 0,
115
+ certifiedPointCount: 0,
116
+ certifiedOverlapCount: 0,
117
+ newtonIterationsTotal: 0,
118
+ projectionIterationsTotal: 0,
119
+ maxResidual: 0,
120
+ };
121
+ export class PolylinePairIntersector {
122
+ static resetDiagnostics() {
123
+ polylineDiagnostics.numericClosestFallbackCount = 0;
124
+ polylineDiagnostics.analyticClosestFallbackCount = 0;
125
+ polylineDiagnostics.recursiveNodesVisited = 0;
126
+ polylineDiagnostics.recursiveAbortCount = 0;
127
+ polylineDiagnostics.refineFailureCount = 0;
128
+ polylineDiagnostics.certificationRejectCount = 0;
129
+ polylineDiagnostics.certificationMissCount = 0;
130
+ polylineDiagnostics.degenerateRescueCount = 0;
131
+ polylineDiagnostics.rescuePassCount = 0;
132
+ polylineDiagnostics.rescueSeedCount = 0;
133
+ polylineDiagnostics.rescueHitCount = 0;
134
+ polylineDiagnostics.candidateSeedCount = 0;
135
+ polylineDiagnostics.certifiedPointCount = 0;
136
+ polylineDiagnostics.certifiedOverlapCount = 0;
137
+ polylineDiagnostics.newtonIterationsTotal = 0;
138
+ polylineDiagnostics.projectionIterationsTotal = 0;
139
+ polylineDiagnostics.maxResidual = 0;
140
+ }
141
+ static getDiagnostics() {
142
+ return { ...polylineDiagnostics };
143
+ }
144
+ static recordAnalyticClosestFallback() {
145
+ polylineDiagnostics.analyticClosestFallbackCount++;
146
+ }
147
+ constructor(segmentsPerCurve, maxNewtonIter = Precision.CURVE_MAX_ITER) {
148
+ this.segmentsPerCurve = segmentsPerCurve;
149
+ this.maxNewtonIter = maxNewtonIter;
150
+ this.runPointSeedLimit = 0;
151
+ this.runOverlapSeedLimit = 0;
152
+ }
153
+ intersect(c1, c2) {
154
+ const tol = makeIntersectionTolerance(c1, c2);
155
+ const pairTol = tol.pointTol;
156
+ const hasBSpline = c1.isBSpline() || c2.isBSpline();
157
+ // Keep strict certification only for BSpline-BSpline.
158
+ // Mixed pairs (Line/Circle/Arc/Ellipse with BSpline) prioritize recall first.
159
+ const strictCertify = c1.isBSpline() && c2.isBSpline();
160
+ const enableNearMissSeeding = hasBSpline || c1.isEllipseArc() || c2.isEllipseArc();
161
+ const nearSeedBudget = Math.max(48, Math.floor(this.segmentsPerCurve * 0.75));
162
+ this.runPointSeedLimit = Math.max(320, this.segmentsPerCurve * 2);
163
+ this.runOverlapSeedLimit = Math.max(24, Math.ceil(this.segmentsPerCurve / 8));
164
+ const s1 = sampleCurveAdaptive(c1, this.segmentsPerCurve, {
165
+ chordErrorTol: pairTol * 0.75,
166
+ maxSamples: this.segmentsPerCurve * 8,
167
+ });
168
+ const s2 = sampleCurveAdaptive(c2, this.segmentsPerCurve, {
169
+ chordErrorTol: pairTol * 0.75,
170
+ maxSamples: this.segmentsPerCurve * 8,
171
+ });
172
+ if (s1.length < 2 || s2.length < 2)
173
+ return [];
174
+ const segs1 = this.buildSegments(s1);
175
+ const segs2 = this.buildSegments(s2);
176
+ const candidates = this.buildPairCandidates(segs1, segs2, pairTol);
177
+ const pointSeeds = [];
178
+ const overlapSeeds = [];
179
+ let minNearDistance = Number.POSITIVE_INFINITY;
180
+ let nearSeedCount = 0;
181
+ const refineFailureBefore = polylineDiagnostics.refineFailureCount;
182
+ const ret = [];
183
+ for (const candidate of candidates) {
184
+ const sA = segs1[candidate.i];
185
+ const sB = segs2[candidate.j];
186
+ const hit = intersectSegments(sA.seg, sB.seg);
187
+ if (hit.kind === 'none') {
188
+ const near = segmentDistance(sA.seg, sB.seg);
189
+ minNearDistance = Math.min(minNearDistance, near);
190
+ if (enableNearMissSeeding &&
191
+ near <= pairTol * 0.8 &&
192
+ nearSeedCount < nearSeedBudget &&
193
+ pointSeeds.length <= nearSeedBudget * 2) {
194
+ this.addNearMissSeeds(pointSeeds, sA, sB, tol.seedParamTol);
195
+ nearSeedCount++;
196
+ }
197
+ continue;
198
+ }
199
+ minNearDistance = 0;
200
+ if (hit.kind === 'point') {
201
+ const u1 = lerp(sA.u0, sA.u1, hit.t1);
202
+ const u2 = lerp(sB.u0, sB.u1, hit.t2);
203
+ this.addPointSeed(pointSeeds, u1, u2, tol.seedParamTol);
204
+ continue;
205
+ }
206
+ const u1s = lerp(sA.u0, sA.u1, hit.t1s);
207
+ const u1e = lerp(sA.u0, sA.u1, hit.t1e);
208
+ const u2s = lerp(sB.u0, sB.u1, hit.t2s);
209
+ const u2e = lerp(sB.u0, sB.u1, hit.t2e);
210
+ this.addOverlapSeed(overlapSeeds, {
211
+ range1: new Interval(Math.min(u1s, u1e), Math.max(u1s, u1e)),
212
+ range2: new Interval(Math.min(u2s, u2e), Math.max(u2s, u2e)),
213
+ });
214
+ this.addPointSeed(pointSeeds, (u1s + u1e) * 0.5, (u2s + u2e) * 0.5, tol.seedParamTol);
215
+ this.addPointSeed(pointSeeds, u1s, u2s, tol.seedParamTol);
216
+ this.addPointSeed(pointSeeds, u1e, u2e, tol.seedParamTol);
217
+ }
218
+ if (pointSeeds.length <= 8 && overlapSeeds.length <= 4) {
219
+ const clipped = collectIntervalClipSeeds(c1, c2, {
220
+ pointTol: pairTol,
221
+ seedParamTol: tol.seedParamTol,
222
+ maxDepth: Math.max(8, Math.ceil(Math.log2(Math.max(8, this.segmentsPerCurve))) + 6),
223
+ maxNodes: this.recursiveMaxNodes(c1, c2),
224
+ pointSeedLimit: Math.max(8, this.runPointSeedLimit - pointSeeds.length),
225
+ overlapSeedLimit: Math.max(4, this.runOverlapSeedLimit - overlapSeeds.length),
226
+ });
227
+ polylineDiagnostics.recursiveNodesVisited += clipped.diagnostics.nodesVisited;
228
+ if (clipped.diagnostics.aborted) {
229
+ polylineDiagnostics.recursiveAbortCount++;
230
+ }
231
+ for (const seed of clipped.pointSeeds) {
232
+ this.addPointSeed(pointSeeds, seed.u1, seed.u2, tol.seedParamTol);
233
+ }
234
+ for (const overlap of clipped.overlapSeeds) {
235
+ this.addOverlapSeed(overlapSeeds, overlap);
236
+ }
237
+ }
238
+ polylineDiagnostics.candidateSeedCount += pointSeeds.length;
239
+ for (const seed of pointSeeds) {
240
+ const refined = this.refinePair(c1, c2, seed.u1, seed.u2, pairTol, strictCertify);
241
+ if (!refined)
242
+ continue;
243
+ this.pushUnique(ret, {
244
+ point: refined.point,
245
+ u1: refined.u1,
246
+ u2: refined.u2,
247
+ isOverlap: false,
248
+ });
249
+ polylineDiagnostics.certifiedPointCount++;
250
+ }
251
+ for (const overlap of overlapSeeds) {
252
+ const overlapInfo = this.refineOverlap(c1, c2, overlap, pairTol, tol.paramTol);
253
+ if (overlapInfo) {
254
+ this.pushUnique(ret, overlapInfo);
255
+ if (overlapInfo.isOverlap) {
256
+ polylineDiagnostics.certifiedOverlapCount++;
257
+ }
258
+ else {
259
+ polylineDiagnostics.certifiedPointCount++;
260
+ }
261
+ }
262
+ }
263
+ const refineFailureDelta = polylineDiagnostics.refineFailureCount - refineFailureBefore;
264
+ if (hasBSpline &&
265
+ ret.length === 0 &&
266
+ (pointSeeds.length > 0 || overlapSeeds.length > 0 || minNearDistance <= pairTol * 2)) {
267
+ const rescued = this.runRescuePass(c1, c2, pairTol, tol.seedParamTol, strictCertify);
268
+ if (rescued.length > 0) {
269
+ for (const hit of rescued) {
270
+ this.pushUnique(ret, hit);
271
+ }
272
+ polylineDiagnostics.rescueHitCount += rescued.length;
273
+ }
274
+ // For BSpline-BSpline, strict certification can reject true roots on noisy seeds.
275
+ // Add a non-strict rescue pass as a recall-oriented fallback.
276
+ if (ret.length === 0 && strictCertify) {
277
+ const relaxedRescued = this.runRescuePass(c1, c2, pairTol, tol.seedParamTol, false);
278
+ if (relaxedRescued.length > 0) {
279
+ for (const hit of relaxedRescued) {
280
+ this.pushUnique(ret, hit);
281
+ }
282
+ polylineDiagnostics.rescueHitCount += relaxedRescued.length;
283
+ }
284
+ }
285
+ }
286
+ if (hasBSpline && ret.length === 0) {
287
+ const relaxed = this.runPolylineRelaxedFallback(c1, c2, pairTol, tol.seedParamTol);
288
+ for (const hit of relaxed) {
289
+ this.pushUnique(ret, hit);
290
+ }
291
+ }
292
+ if (hasBSpline &&
293
+ ret.length === 0 &&
294
+ (pointSeeds.length > 0 || overlapSeeds.length > 0) &&
295
+ minNearDistance <= pairTol * 0.2 &&
296
+ refineFailureDelta >= 3) {
297
+ polylineDiagnostics.certificationMissCount++;
298
+ }
299
+ return ret;
300
+ }
301
+ runPolylineRelaxedFallback(c1, c2, pointTol, seedParamTol) {
302
+ const ret = [];
303
+ const dense = Math.min(2048, Math.max(512, this.segmentsPerCurve * 2));
304
+ const s1 = sampleCurveAdaptive(c1, dense, {
305
+ chordErrorTol: pointTol * 1.5,
306
+ maxSamples: dense * 8,
307
+ });
308
+ const s2 = sampleCurveAdaptive(c2, dense, {
309
+ chordErrorTol: pointTol * 1.5,
310
+ maxSamples: dense * 8,
311
+ });
312
+ if (s1.length < 2 || s2.length < 2)
313
+ return ret;
314
+ const seeds = [];
315
+ const segs1 = this.buildSegments(s1);
316
+ const segs2 = this.buildSegments(s2);
317
+ const candidates = this.buildPairCandidates(segs1, segs2, pointTol * 4);
318
+ for (const candidate of candidates) {
319
+ const a = segs1[candidate.i];
320
+ const b = segs2[candidate.j];
321
+ const hit = intersectSegments(a.seg, b.seg);
322
+ if (hit.kind === 'none')
323
+ continue;
324
+ if (hit.kind === 'point') {
325
+ this.addPointSeed(seeds, lerp(a.u0, a.u1, hit.t1), lerp(b.u0, b.u1, hit.t2), seedParamTol * 4);
326
+ continue;
327
+ }
328
+ this.addPointSeed(seeds, lerp(a.u0, a.u1, 0.5 * (hit.t1s + hit.t1e)), lerp(b.u0, b.u1, 0.5 * (hit.t2s + hit.t2e)), seedParamTol * 4);
329
+ }
330
+ for (const seed of seeds) {
331
+ const refined = this.refinePair(c1, c2, seed.u1, seed.u2, pointTol, false);
332
+ if (!refined)
333
+ continue;
334
+ this.pushUnique(ret, {
335
+ point: refined.point,
336
+ u1: refined.u1,
337
+ u2: refined.u2,
338
+ isOverlap: false,
339
+ });
340
+ }
341
+ return ret;
342
+ }
343
+ buildSegments(samples) {
344
+ const ret = [];
345
+ for (let i = 0; i < samples.length - 1; i++) {
346
+ const a = samples[i];
347
+ const b = samples[i + 1];
348
+ ret.push({
349
+ u0: a.u,
350
+ u1: b.u,
351
+ seg: makeSegment(a.p, b.p),
352
+ });
353
+ }
354
+ return ret;
355
+ }
356
+ addNearMissSeeds(seeds, a, b, paramTol) {
357
+ this.addPointSeed(seeds, 0.5 * (a.u0 + a.u1), 0.5 * (b.u0 + b.u1), paramTol);
358
+ }
359
+ buildPairCandidates(segs1, segs2, pad) {
360
+ if (segs1.length === 0 || segs2.length === 0)
361
+ return [];
362
+ const index = new SegmentHashIndex(segs2, pad);
363
+ const marks = new Int32Array(segs2.length);
364
+ const ret = [];
365
+ let stamp = 1;
366
+ for (let i = 0; i < segs1.length; i++) {
367
+ const s1 = segs1[i];
368
+ const js = index.query(s1, pad, marks, stamp++);
369
+ if (stamp >= 0x7fffffff) {
370
+ marks.fill(0);
371
+ stamp = 1;
372
+ }
373
+ for (const j of js) {
374
+ const s2 = segs2[j];
375
+ if (!segmentBoxesMayIntersect(s1.seg, s2.seg, pad))
376
+ continue;
377
+ ret.push({ i, j });
378
+ }
379
+ }
380
+ return ret;
381
+ }
382
+ addPointSeed(seeds, u1, u2, paramTol) {
383
+ if (this.runPointSeedLimit > 0 && seeds.length >= this.runPointSeedLimit)
384
+ return;
385
+ for (const seed of seeds) {
386
+ if (Math.abs(seed.u1 - u1) <= paramTol &&
387
+ Math.abs(seed.u2 - u2) <= paramTol) {
388
+ return;
389
+ }
390
+ }
391
+ seeds.push({ u1, u2 });
392
+ }
393
+ addOverlapSeed(seeds, next) {
394
+ for (let i = 0; i < seeds.length; i++) {
395
+ const cur = seeds[i];
396
+ const overlap1 = next.range1.intersect(cur.range1, Precision.CURVE_PARAM_EPS * 8);
397
+ const overlap2 = next.range2.intersect(cur.range2, Precision.CURVE_PARAM_EPS * 8);
398
+ if (overlap1.length === 0 || overlap2.length === 0)
399
+ continue;
400
+ seeds[i] = {
401
+ range1: new Interval(Math.min(cur.range1.start, next.range1.start), Math.max(cur.range1.end, next.range1.end)),
402
+ range2: new Interval(Math.min(cur.range2.start, next.range2.start), Math.max(cur.range2.end, next.range2.end)),
403
+ };
404
+ return;
405
+ }
406
+ if (this.runOverlapSeedLimit > 0 && seeds.length >= this.runOverlapSeedLimit)
407
+ return;
408
+ seeds.push(next);
409
+ }
410
+ refinePair(c1, c2, u1Seed, u2Seed, tol, strictCertify = false) {
411
+ const newton = this.refineByNewton(c1, c2, u1Seed, u2Seed, tol);
412
+ if (newton && newton.residual <= tol * 2) {
413
+ if (!strictCertify) {
414
+ polylineDiagnostics.maxResidual = Math.max(polylineDiagnostics.maxResidual, newton.residual);
415
+ return newton;
416
+ }
417
+ const certified = certifyParamPair(c1, c2, newton, tol, (curve, p, t) => this.safeClosestPoint(curve, p, t));
418
+ if (certified) {
419
+ polylineDiagnostics.maxResidual = Math.max(polylineDiagnostics.maxResidual, certified.pair.residual);
420
+ if (certified.usedDegenerateRescue)
421
+ polylineDiagnostics.degenerateRescueCount++;
422
+ return certified.pair;
423
+ }
424
+ polylineDiagnostics.certificationRejectCount++;
425
+ }
426
+ const proj = this.refineByProjection(c1, c2, newton?.u1 ?? u1Seed, newton?.u2 ?? u2Seed, tol);
427
+ if (proj && proj.residual <= tol * 2) {
428
+ if (!strictCertify) {
429
+ polylineDiagnostics.maxResidual = Math.max(polylineDiagnostics.maxResidual, proj.residual);
430
+ return proj;
431
+ }
432
+ const certified = certifyParamPair(c1, c2, proj, tol, (curve, p, t) => this.safeClosestPoint(curve, p, t));
433
+ if (certified) {
434
+ polylineDiagnostics.maxResidual = Math.max(polylineDiagnostics.maxResidual, certified.pair.residual);
435
+ if (certified.usedDegenerateRescue)
436
+ polylineDiagnostics.degenerateRescueCount++;
437
+ return certified.pair;
438
+ }
439
+ polylineDiagnostics.certificationRejectCount++;
440
+ }
441
+ const best = this.pickBest(newton, proj);
442
+ if (!best || best.residual > tol * 8) {
443
+ polylineDiagnostics.refineFailureCount++;
444
+ return undefined;
445
+ }
446
+ if (!strictCertify) {
447
+ polylineDiagnostics.maxResidual = Math.max(polylineDiagnostics.maxResidual, best.residual);
448
+ return best;
449
+ }
450
+ const certified = certifyParamPair(c1, c2, best, tol, (curve, p, t) => this.safeClosestPoint(curve, p, t));
451
+ if (!certified) {
452
+ polylineDiagnostics.certificationRejectCount++;
453
+ polylineDiagnostics.refineFailureCount++;
454
+ return undefined;
455
+ }
456
+ polylineDiagnostics.maxResidual = Math.max(polylineDiagnostics.maxResidual, certified.pair.residual);
457
+ if (certified.usedDegenerateRescue)
458
+ polylineDiagnostics.degenerateRescueCount++;
459
+ return certified.pair;
460
+ }
461
+ refineByNewton(c1, c2, u1Seed, u2Seed, tol) {
462
+ const r1 = c1.getRange();
463
+ const r2 = c2.getRange();
464
+ const span1 = Math.max(r1.length(), Precision.CURVE_PARAM_EPS);
465
+ const span2 = Math.max(r2.length(), Precision.CURVE_PARAM_EPS);
466
+ let u1 = r1.clamp(u1Seed);
467
+ let u2 = r2.clamp(u2Seed);
468
+ let best = this.measure(c1, c2, u1, u2);
469
+ let lastDelta = Number.POSITIVE_INFINITY;
470
+ for (let i = 0; i < this.maxNewtonIter; i++) {
471
+ polylineDiagnostics.newtonIterationsTotal++;
472
+ const p1 = c1.pointAt(u1);
473
+ const p2 = c2.pointAt(u2);
474
+ const diff = p1.subtracted(p2);
475
+ if (diff.len() <= tol)
476
+ return this.measure(c1, c2, u1, u2);
477
+ const t1 = c1.tangentAt(u1);
478
+ const t2 = c2.tangentAt(u2);
479
+ const det = t1.cross(t2);
480
+ if (Math.abs(det) <= Precision.CURVE_NEWTON_EPS) {
481
+ break;
482
+ }
483
+ // [t1.x -t2.x; t1.y -t2.y] * [du, dv]^T = -diff
484
+ const bx = -diff.x;
485
+ const by = -diff.y;
486
+ let du = (bx * (-t2.y) - by * (-t2.x)) / det;
487
+ let dv = (t1.x * by - t1.y * bx) / det;
488
+ if (!Number.isFinite(du) || !Number.isFinite(dv)) {
489
+ break;
490
+ }
491
+ const limit1 = Math.max(span1 * 0.25, Precision.CURVE_PARAM_EPS * 8);
492
+ const limit2 = Math.max(span2 * 0.25, Precision.CURVE_PARAM_EPS * 8);
493
+ du = clamp(du, -limit1, limit1);
494
+ dv = clamp(dv, -limit2, limit2);
495
+ let nextU1 = r1.clamp(u1 + du);
496
+ let nextU2 = r2.clamp(u2 + dv);
497
+ let candidate = this.measure(c1, c2, nextU1, nextU2);
498
+ // Damping if raw Newton step does not improve.
499
+ if (candidate.residual > best.residual + tol * 0.2) {
500
+ let accepted = false;
501
+ for (let damp = 0; damp < 4; damp++) {
502
+ const f = Math.pow(0.5, damp + 1);
503
+ const dU1 = du * f;
504
+ const dU2 = dv * f;
505
+ nextU1 = r1.clamp(u1 + dU1);
506
+ nextU2 = r2.clamp(u2 + dU2);
507
+ candidate = this.measure(c1, c2, nextU1, nextU2);
508
+ if (candidate.residual <= best.residual + tol * 0.1) {
509
+ accepted = true;
510
+ break;
511
+ }
512
+ }
513
+ if (!accepted && candidate.residual > best.residual + tol * 0.25) {
514
+ break;
515
+ }
516
+ }
517
+ const delta = Math.abs(nextU1 - u1) + Math.abs(nextU2 - u2);
518
+ u1 = nextU1;
519
+ u2 = nextU2;
520
+ if (candidate.residual < best.residual)
521
+ best = candidate;
522
+ if (delta <= Precision.CURVE_PARAM_EPS * 8) {
523
+ break;
524
+ }
525
+ if (delta >= lastDelta - Precision.CURVE_PARAM_EPS * 8) {
526
+ break;
527
+ }
528
+ lastDelta = delta;
529
+ }
530
+ const final = this.measure(c1, c2, u1, u2);
531
+ return this.pickBest(best, final);
532
+ }
533
+ refineByProjection(c1, c2, u1Seed, u2Seed, tol) {
534
+ const r1 = c1.getRange();
535
+ const r2 = c2.getRange();
536
+ let u1 = r1.clamp(u1Seed);
537
+ let u2 = r2.clamp(u2Seed);
538
+ let best = this.measure(c1, c2, u1, u2);
539
+ for (let i = 0; i < this.maxNewtonIter; i++) {
540
+ polylineDiagnostics.projectionIterationsTotal++;
541
+ const p1 = c1.pointAt(u1);
542
+ const cp2 = this.safeClosestPoint(c2, p1, tol);
543
+ if (!cp2)
544
+ break;
545
+ const nextU2 = r2.clamp(cp2.param);
546
+ const p2 = c2.pointAt(nextU2);
547
+ const cp1 = this.safeClosestPoint(c1, p2, tol);
548
+ if (!cp1)
549
+ break;
550
+ const nextU1 = r1.clamp(cp1.param);
551
+ const candidate = this.measure(c1, c2, nextU1, nextU2);
552
+ if (candidate.residual < best.residual)
553
+ best = candidate;
554
+ if (candidate.residual <= tol)
555
+ return candidate;
556
+ const du = Math.abs(nextU1 - u1);
557
+ const dv = Math.abs(nextU2 - u2);
558
+ u1 = nextU1;
559
+ u2 = nextU2;
560
+ if (du + dv <= Precision.CURVE_PARAM_EPS * 8)
561
+ break;
562
+ }
563
+ return best;
564
+ }
565
+ runRescuePass(c1, c2, pointTol, seedParamTol, strictCertify) {
566
+ polylineDiagnostics.rescuePassCount++;
567
+ const ret = [];
568
+ const seeds = [];
569
+ const r1 = c1.getRange();
570
+ const r2 = c2.getRange();
571
+ const baseSamples = Math.max(24, Math.min(96, Math.floor(this.segmentsPerCurve / 2)));
572
+ for (let i = 0; i <= baseSamples; i++) {
573
+ const t = i / baseSamples;
574
+ const u1 = r1.start + (r1.end - r1.start) * t;
575
+ const p1 = c1.pointAt(u1);
576
+ const cp2 = this.safeClosestPoint(c2, p1, pointTol * 3);
577
+ if (!cp2 || cp2.distance > pointTol * 2.5)
578
+ continue;
579
+ this.addPointSeed(seeds, u1, r2.clamp(cp2.param), seedParamTol);
580
+ }
581
+ for (let i = 0; i <= baseSamples; i++) {
582
+ const t = i / baseSamples;
583
+ const u2 = r2.start + (r2.end - r2.start) * t;
584
+ const p2 = c2.pointAt(u2);
585
+ const cp1 = this.safeClosestPoint(c1, p2, pointTol * 3);
586
+ if (!cp1 || cp1.distance > pointTol * 2.5)
587
+ continue;
588
+ this.addPointSeed(seeds, r1.clamp(cp1.param), u2, seedParamTol);
589
+ }
590
+ polylineDiagnostics.rescueSeedCount += seeds.length;
591
+ for (const seed of seeds) {
592
+ const refined = this.refinePair(c1, c2, seed.u1, seed.u2, pointTol, strictCertify);
593
+ if (!refined)
594
+ continue;
595
+ this.pushUnique(ret, {
596
+ point: refined.point,
597
+ u1: refined.u1,
598
+ u2: refined.u2,
599
+ isOverlap: false,
600
+ });
601
+ }
602
+ return ret;
603
+ }
604
+ measure(c1, c2, u1, u2) {
605
+ const p1 = c1.pointAt(u1);
606
+ const p2 = c2.pointAt(u2);
607
+ return {
608
+ u1,
609
+ u2,
610
+ point: p1.added(p2).scale(0.5),
611
+ residual: p1.distanceTo(p2),
612
+ };
613
+ }
614
+ refineOverlap(c1, c2, overlap, tol, paramTol) {
615
+ const midU1 = 0.5 * (overlap.range1.start + overlap.range1.end);
616
+ const midU2 = 0.5 * (overlap.range2.start + overlap.range2.end);
617
+ const mid = this.refinePair(c1, c2, midU1, midU2, tol, false);
618
+ if (!mid)
619
+ return undefined;
620
+ const range2 = projectRangeToCurve(c1, c2, overlap.range1, tol, (curve, p, t) => this.safeClosestPoint(curve, p, t));
621
+ if (!range2)
622
+ return undefined;
623
+ if (overlap.range1.length() <= paramTol || range2.length() <= paramTol) {
624
+ return {
625
+ point: mid.point,
626
+ u1: mid.u1,
627
+ u2: mid.u2,
628
+ isOverlap: false,
629
+ };
630
+ }
631
+ const quality = certifyOverlapMonotone(c1, c2, overlap.range1, tol, paramTol, (curve, p, t) => this.safeClosestPoint(curve, p, t));
632
+ if (!quality) {
633
+ return {
634
+ point: mid.point,
635
+ u1: mid.u1,
636
+ u2: mid.u2,
637
+ isOverlap: false,
638
+ };
639
+ }
640
+ return {
641
+ point: mid.point,
642
+ u1: mid.u1,
643
+ u2: mid.u2,
644
+ isOverlap: true,
645
+ range1: overlap.range1,
646
+ range2,
647
+ };
648
+ }
649
+ safeClosestPoint(curve, p, tol) {
650
+ try {
651
+ return curve.closestPoint(p, tol);
652
+ }
653
+ catch {
654
+ polylineDiagnostics.numericClosestFallbackCount++;
655
+ return this.sampleClosestPoint(curve, p, 48);
656
+ }
657
+ }
658
+ sampleClosestPoint(curve, p, sampleCount) {
659
+ const range = curve.getRange();
660
+ let bestParam = range.start;
661
+ let bestPoint = curve.pointAt(bestParam);
662
+ let bestDist = bestPoint.distanceTo(p);
663
+ const total = Math.max(8, sampleCount);
664
+ for (let i = 1; i <= total; i++) {
665
+ const t = i / total;
666
+ const u = range.start + (range.end - range.start) * t;
667
+ const q = curve.pointAt(u);
668
+ const d = q.distanceTo(p);
669
+ if (d < bestDist) {
670
+ bestDist = d;
671
+ bestPoint = q;
672
+ bestParam = u;
673
+ }
674
+ }
675
+ // Local Newton refinement around sampled best parameter.
676
+ let u = bestParam;
677
+ for (let i = 0; i < 12; i++) {
678
+ const cp = curve.pointAt(u).subtracted(p);
679
+ const d1 = curve.derivativeAt(u, 1);
680
+ const d2 = curve.derivativeAt(u, 2);
681
+ const f = cp.dot(d1);
682
+ const fp = d1.dot(d1) + cp.dot(d2);
683
+ if (!Number.isFinite(f) || !Number.isFinite(fp) || Math.abs(fp) <= Precision.CURVE_NEWTON_EPS)
684
+ break;
685
+ const next = range.clamp(u - f / fp);
686
+ if (Math.abs(next - u) <= Precision.CURVE_PARAM_EPS * 4) {
687
+ u = next;
688
+ break;
689
+ }
690
+ u = next;
691
+ }
692
+ bestParam = u;
693
+ bestPoint = curve.pointAt(bestParam);
694
+ bestDist = bestPoint.distanceTo(p);
695
+ return {
696
+ point: bestPoint,
697
+ param: bestParam,
698
+ distance: bestDist,
699
+ };
700
+ }
701
+ pickBest(a, b) {
702
+ if (!a)
703
+ return b;
704
+ if (!b)
705
+ return a;
706
+ return a.residual <= b.residual ? a : b;
707
+ }
708
+ pushUnique(out, next) {
709
+ for (const item of out) {
710
+ if (Math.abs(item.u1 - next.u1) <= Precision.CURVE_PARAM_EPS * 8 &&
711
+ Math.abs(item.u2 - next.u2) <= Precision.CURVE_PARAM_EPS * 8 &&
712
+ item.point.distanceTo(next.point) <= Precision.CURVE_LENGTH_EPS * 4 &&
713
+ item.isOverlap === next.isOverlap) {
714
+ return;
715
+ }
716
+ }
717
+ out.push(next);
718
+ }
719
+ recursiveMaxNodes(c1, c2) {
720
+ const heavy = c1.isBSpline() || c2.isBSpline() || c1.isEllipseArc() || c2.isEllipseArc();
721
+ return heavy
722
+ ? Math.max(5000, this.segmentsPerCurve * 28)
723
+ : Math.max(2500, this.segmentsPerCurve * 16);
724
+ }
725
+ }
726
+ function clamp(x, min, max) {
727
+ return Math.min(max, Math.max(min, x));
728
+ }
729
+ function clampInt(x, min, max) {
730
+ return Math.min(max, Math.max(min, x | 0));
731
+ }