paperjs-offset 1.0.8 → 2.0.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,760 @@
1
+ import paper from 'paper';
2
+
3
+ var MAX_RECURSION_TIME = 20;
4
+ var STRATEGIES = [
5
+ {
6
+ algorithm: 'adaptive',
7
+ splitSelfIntersectingCurves: true,
8
+ guardInsideJoins: true,
9
+ simplifySelfIntersectingStroke: true,
10
+ adaptiveFallback: true,
11
+ },
12
+ {
13
+ algorithm: 'robust',
14
+ splitSelfIntersectingCurves: true,
15
+ guardInsideJoins: true,
16
+ simplifySelfIntersectingStroke: true,
17
+ adaptiveFallback: false,
18
+ },
19
+ {
20
+ algorithm: 'split',
21
+ splitSelfIntersectingCurves: true,
22
+ guardInsideJoins: false,
23
+ simplifySelfIntersectingStroke: false,
24
+ adaptiveFallback: false,
25
+ },
26
+ {
27
+ algorithm: 'legacy',
28
+ splitSelfIntersectingCurves: false,
29
+ guardInsideJoins: false,
30
+ simplifySelfIntersectingStroke: false,
31
+ adaptiveFallback: false,
32
+ },
33
+ ];
34
+ function getStrategy(algorithm) {
35
+ if (algorithm === 'auto') {
36
+ return STRATEGIES[0];
37
+ }
38
+ return STRATEGIES.filter(function (strategy) { return strategy.algorithm === algorithm; })[0] || STRATEGIES[0];
39
+ }
40
+ /**
41
+ * Offset the start/terminal segment of a bezier curve
42
+ * @param segment segment to offset
43
+ * @param curve curve to offset
44
+ * @param handleNormal the normal of the the line formed of two handles
45
+ * @param offset offset value
46
+ */
47
+ function offsetSegment(segment, curve, handleNormal, offset) {
48
+ var isFirst = segment.curve === curve;
49
+ // get offset vector
50
+ var offsetVector = (curve.getNormalAtTime(isFirst ? 0 : 1)).multiply(offset);
51
+ // get offset point
52
+ var point = segment.point.add(offsetVector);
53
+ var newSegment = new paper.Segment(point);
54
+ // handleOut for start segment & handleIn for terminal segment
55
+ var handle = (isFirst ? 'handleOut' : 'handleIn');
56
+ newSegment[handle] = segment[handle].add(handleNormal.subtract(offsetVector).divide(2));
57
+ return newSegment;
58
+ }
59
+ /**
60
+ * Adaptive offset a curve by repeatly apply the approximation proposed by Tiller and Hanson.
61
+ * @param curve curve to offset
62
+ * @param offset offset value
63
+ */
64
+ function adaptiveOffsetCurve(curve, offset, strategy, recursionTime) {
65
+ if (recursionTime === void 0) { recursionTime = 0; }
66
+ var hNormal = (new paper.Curve(curve.segment1.handleOut.add(curve.segment1.point), new paper.Point(0, 0), new paper.Point(0, 0), curve.segment2.handleIn.add(curve.segment2.point))).getNormalAtTime(0.5).multiply(offset);
67
+ var segment1 = offsetSegment(curve.segment1, curve, hNormal, offset);
68
+ var segment2 = offsetSegment(curve.segment2, curve, hNormal, offset);
69
+ if (recursionTime > MAX_RECURSION_TIME) {
70
+ return [segment1, segment2];
71
+ }
72
+ // divide && re-offset
73
+ var offsetCurve = new paper.Curve(segment1, segment2);
74
+ var offsetCurveIntersections = offsetCurve.getIntersections(offsetCurve);
75
+ var threshold = Math.min(Math.abs(offset) / 10, 1);
76
+ var midOffset = offsetCurve.getPointAtTime(0.5).getDistance(curve.getPointAtTime(0.5));
77
+ var needsSplit = strategy.splitSelfIntersectingCurves
78
+ ? offsetCurveIntersections.length > 0 || Math.abs(midOffset - Math.abs(offset)) > threshold
79
+ : offsetCurveIntersections.length === 0 && Math.abs(midOffset - Math.abs(offset)) > threshold;
80
+ if (needsSplit) {
81
+ var subCurve = curve.divideAtTime(0.5);
82
+ if (subCurve != null) {
83
+ return adaptiveOffsetCurve(curve, offset, strategy, recursionTime + 1)
84
+ .concat(adaptiveOffsetCurve(subCurve, offset, strategy, recursionTime + 1));
85
+ }
86
+ }
87
+ return [segment1, segment2];
88
+ }
89
+ /**
90
+ * Create a round join segment between two adjacent segments.
91
+ */
92
+ function makeRoundJoin(segment1, segment2, originPoint, radius) {
93
+ var through = segment1.point.subtract(originPoint).add(segment2.point.subtract(originPoint))
94
+ .normalize(Math.abs(radius)).add(originPoint);
95
+ var arc = new paper.Path.Arc({ from: segment1.point, to: segment2.point, through: through, insert: false });
96
+ segment1.handleOut = arc.firstSegment.handleOut;
97
+ segment2.handleIn = arc.lastSegment.handleIn;
98
+ return arc.segments.length === 3 ? arc.segments[1] : null;
99
+ }
100
+ function det(p1, p2) {
101
+ return p1.x * p2.y - p1.y * p2.x;
102
+ }
103
+ /**
104
+ * Get the intersection point of point based lines
105
+ */
106
+ function getPointLineIntersections(p1, p2, p3, p4) {
107
+ var l1 = p1.subtract(p2);
108
+ var l2 = p3.subtract(p4);
109
+ var dl1 = det(p1, p2);
110
+ var dl2 = det(p3, p4);
111
+ return new paper.Point(dl1 * l2.x - l1.x * dl2, dl1 * l2.y - l1.y * dl2).divide(det(l1, l2));
112
+ }
113
+ /**
114
+ * Connect two adjacent bezier curve, each curve is represented by two segments,
115
+ * create different types of joins or simply removal redundant segment.
116
+ */
117
+ function isOutsideJoin(origin, offset) {
118
+ var _a;
119
+ var previousCurve = (_a = origin.previous) === null || _a === void 0 ? void 0 : _a.curve;
120
+ var nextCurve = origin.curve;
121
+ if (!previousCurve || !nextCurve) {
122
+ return true;
123
+ }
124
+ var tangentIn = previousCurve.getTangentAtTime(1);
125
+ var tangentOut = nextCurve.getTangentAtTime(0);
126
+ var turn = det(tangentIn, tangentOut);
127
+ return Math.abs(turn) < 1e-9 || turn * offset > 0;
128
+ }
129
+ function connectAdjacentBezier(segments1, segments2, origin, joinType, offset, limit, closed, strategy) {
130
+ var curve1 = new paper.Curve(segments1[0], segments1[1]);
131
+ var curve2 = new paper.Curve(segments2[0], segments2[1]);
132
+ var intersection = curve1.getIntersections(curve2);
133
+ var distance = segments1[1].point.getDistance(segments2[0].point);
134
+ var shouldJoin = !closed || !strategy.guardInsideJoins || isOutsideJoin(origin, offset);
135
+ if (origin.isSmooth()) {
136
+ segments2[0].handleOut = segments2[0].handleOut.project(origin.handleOut);
137
+ segments2[0].handleIn = segments1[1].handleIn.project(origin.handleIn);
138
+ segments2[0].point = segments1[1].point.add(segments2[0].point).divide(2);
139
+ segments1.pop();
140
+ }
141
+ else {
142
+ if (intersection.length === 0) {
143
+ if (distance > Math.abs(offset) * 0.1) {
144
+ // connect
145
+ switch (joinType) {
146
+ case 'miter':
147
+ if (shouldJoin) {
148
+ var join = getPointLineIntersections(curve1.point2, curve1.point2.add(curve1.getTangentAtTime(1)), curve2.point1, curve2.point1.add(curve2.getTangentAtTime(0)));
149
+ // prevent sharp angle
150
+ var joinOffset = Math.max(join.getDistance(curve1.point2), join.getDistance(curve2.point1));
151
+ if (joinOffset < Math.abs(offset) * limit) {
152
+ segments1.push(new paper.Segment(join));
153
+ }
154
+ }
155
+ break;
156
+ case 'round':
157
+ if (shouldJoin) {
158
+ var mid = makeRoundJoin(segments1[1], segments2[0], origin.point, offset);
159
+ if (mid) {
160
+ segments1.push(mid);
161
+ }
162
+ }
163
+ break;
164
+ }
165
+ }
166
+ else {
167
+ segments2[0].handleIn = segments1[1].handleIn;
168
+ segments1.pop();
169
+ }
170
+ }
171
+ else {
172
+ var second1 = curve1.divideAt(intersection[0]);
173
+ if (second1) {
174
+ var join = second1.segment1;
175
+ var second2 = curve2.divideAt(curve2.getIntersections(curve1)[0]);
176
+ join.handleOut = second2 ? second2.segment1.handleOut : segments2[0].handleOut;
177
+ segments1.pop();
178
+ segments2[0] = join;
179
+ }
180
+ else {
181
+ segments2[0].handleIn = segments1[1].handleIn;
182
+ segments1.pop();
183
+ }
184
+ }
185
+ }
186
+ }
187
+ /**
188
+ * Connect all the segments together.
189
+ */
190
+ function connectBeziers(rawSegments, join, source, offset, limit, strategy) {
191
+ var originSegments = source.segments;
192
+ var first = rawSegments[0].slice();
193
+ for (var i = 0; i < rawSegments.length - 1; ++i) {
194
+ connectAdjacentBezier(rawSegments[i], rawSegments[i + 1], originSegments[i + 1], join, offset, limit, source.closed, strategy);
195
+ }
196
+ if (source.closed) {
197
+ connectAdjacentBezier(rawSegments[rawSegments.length - 1], first, originSegments[0], join, offset, limit, source.closed, strategy);
198
+ rawSegments[0][0] = first[0];
199
+ }
200
+ return rawSegments;
201
+ }
202
+ function reduceSingleChildCompoundPath(path) {
203
+ if (path.children.length === 1) {
204
+ path = path.children[0];
205
+ path.remove(); // remove from parent, this is critical, or the style attributes will be ignored
206
+ }
207
+ return path;
208
+ }
209
+ /** Normalize a path, always clockwise, non-self-intersection, ignore really small components, and no one-component compound path. */
210
+ function normalize(path, areaThreshold) {
211
+ if (areaThreshold === void 0) { areaThreshold = 0.01; }
212
+ if (path.closed) {
213
+ var ignoreArea_1 = Math.abs(path.area * areaThreshold);
214
+ if (!path.clockwise) {
215
+ path.reverse();
216
+ }
217
+ path = path.unite(path, { insert: false });
218
+ path = path.resolveCrossings();
219
+ if (path instanceof paper.CompoundPath) {
220
+ path.children.filter(function (c) { return Math.abs(c.area) < ignoreArea_1; }).forEach(function (c) { return c.remove(); });
221
+ if (path.children.length === 1) {
222
+ return reduceSingleChildCompoundPath(path);
223
+ }
224
+ }
225
+ }
226
+ return path;
227
+ }
228
+ function cleanupStrokeOutline(path, offset, strategy) {
229
+ var result = normalize(path);
230
+ if (strategy.simplifySelfIntersectingStroke && countSelfIntersections(result) > 0) {
231
+ var simplified = result.clone({ insert: false });
232
+ simplified.simplify(Math.max(Math.min(Math.abs(offset) * 0.02, 0.5), 0.1));
233
+ result = normalize(simplified);
234
+ }
235
+ return result;
236
+ }
237
+ function isSameDirection(partialPath, fullPath) {
238
+ var offset1 = partialPath.segments[0].location.offset;
239
+ var offset2 = partialPath.segments[Math.max(1, Math.floor(partialPath.segments.length / 2))].location.offset;
240
+ var sampleOffset = (offset1 + offset2) / 3;
241
+ var originOffset1 = fullPath.getNearestLocation(partialPath.getPointAt(sampleOffset)).offset;
242
+ var originOffset2 = fullPath.getNearestLocation(partialPath.getPointAt(2 * sampleOffset)).offset;
243
+ return originOffset1 < originOffset2;
244
+ }
245
+ /** Remove self intersection when offset is negative by point direction dectection. */
246
+ function removeIntersection(path) {
247
+ if (path.closed) {
248
+ var newPath = path.unite(path, { insert: false });
249
+ if (newPath instanceof paper.CompoundPath) {
250
+ newPath.children.filter(function (c) {
251
+ if (c.segments.length > 1) {
252
+ return !isSameDirection(c, path);
253
+ }
254
+ else {
255
+ return true;
256
+ }
257
+ }).forEach(function (c) { return c.remove(); });
258
+ return reduceSingleChildCompoundPath(newPath);
259
+ }
260
+ }
261
+ return path;
262
+ }
263
+ function getSegments(path) {
264
+ if (path instanceof paper.CompoundPath) {
265
+ return path.children.map(function (c) { return c.segments; }).flat();
266
+ }
267
+ else {
268
+ return path.segments;
269
+ }
270
+ }
271
+ /**
272
+ * Remove impossible segments in negative offset condition.
273
+ */
274
+ function removeOutsiders(newPath, path) {
275
+ var segments = getSegments(newPath).slice();
276
+ segments.forEach(function (segment) {
277
+ if (!path.contains(segment.point)) {
278
+ segment.remove();
279
+ }
280
+ });
281
+ }
282
+ function preparePath(path, offset) {
283
+ var source = path.clone({ insert: false });
284
+ source.reduce({});
285
+ if (path.closed && !path.clockwise) {
286
+ source.reverse();
287
+ offset = -offset;
288
+ }
289
+ return [source, offset];
290
+ }
291
+ function offsetSimpleShape(path, offset, join, limit, strategy) {
292
+ var _a;
293
+ var source;
294
+ _a = preparePath(path, offset), source = _a[0], offset = _a[1];
295
+ var curves = source.curves.slice();
296
+ var offsetCurves = curves.map(function (curve) { return adaptiveOffsetCurve(curve, offset, strategy); }).flat();
297
+ var raws = [];
298
+ for (var i = 0; i < offsetCurves.length; i += 2) {
299
+ raws.push(offsetCurves.slice(i, i + 2));
300
+ }
301
+ var segments = connectBeziers(raws, join, source, offset, limit, strategy).flat();
302
+ var newPath = removeIntersection(new paper.Path({ segments: segments, insert: false, closed: path.closed }));
303
+ newPath.reduce({});
304
+ if (source.closed && ((source.clockwise && offset < 0) || (!source.clockwise && offset > 0))) {
305
+ removeOutsiders(newPath, path);
306
+ }
307
+ // recovery path
308
+ if (source.clockwise !== path.clockwise) {
309
+ newPath.reverse();
310
+ }
311
+ return normalize(newPath);
312
+ }
313
+ function makeRoundCap(from, to, offset) {
314
+ var origin = from.point.add(to.point).divide(2);
315
+ var normal = to.point.subtract(from.point).rotate(-90, new paper.Point(0, 0)).normalize(offset);
316
+ var through = origin.add(normal);
317
+ var arc = new paper.Path.Arc({ from: from.point, to: to.point, through: through, insert: false });
318
+ return arc.segments;
319
+ }
320
+ function connectSide(outer, inner, offset, cap) {
321
+ if (outer instanceof paper.CompoundPath) {
322
+ var cs = outer.children.map(function (c) { return ({ c: c, a: Math.abs(c.area) }); });
323
+ cs = cs.sort(function (c1, c2) { return c2.a - c1.a; });
324
+ outer = cs[0].c;
325
+ }
326
+ var oSegments = outer.segments.slice();
327
+ var iSegments = inner.segments.slice();
328
+ switch (cap) {
329
+ case 'round':
330
+ var heads = makeRoundCap(iSegments[iSegments.length - 1], oSegments[0], offset);
331
+ var tails = makeRoundCap(oSegments[oSegments.length - 1], iSegments[0], offset);
332
+ var result = new paper.Path({ segments: heads.concat(oSegments, tails, iSegments), closed: true, insert: false });
333
+ result.reduce({});
334
+ return result;
335
+ default: return new paper.Path({ segments: oSegments.concat(iSegments), closed: true, insert: false });
336
+ }
337
+ }
338
+ function offsetSimpleStroke(path, offset, join, cap, limit, strategy) {
339
+ offset = path.closed && !path.clockwise ? -offset : offset;
340
+ var positiveOffset = offsetSimpleShape(path, offset, join, limit, strategy);
341
+ var negativeOffset = offsetSimpleShape(path, -offset, join, limit, strategy);
342
+ if (path.closed) {
343
+ return cleanupStrokeOutline(positiveOffset.subtract(negativeOffset, { insert: false }), offset, strategy);
344
+ }
345
+ else {
346
+ var inner = negativeOffset;
347
+ var holes = new Array();
348
+ if (negativeOffset instanceof paper.CompoundPath) {
349
+ holes = negativeOffset.children.filter(function (c) { return c.closed; });
350
+ holes.forEach(function (h) { return h.remove(); });
351
+ inner = negativeOffset.children[0];
352
+ }
353
+ inner.reverse();
354
+ var final = connectSide(positiveOffset, inner, offset, cap);
355
+ if (holes.length > 0) {
356
+ for (var _i = 0, holes_1 = holes; _i < holes_1.length; _i++) {
357
+ var hole = holes_1[_i];
358
+ final = final.subtract(hole, { insert: false });
359
+ }
360
+ }
361
+ return cleanupStrokeOutline(final, offset, strategy);
362
+ }
363
+ }
364
+ function getChildPaths(path) {
365
+ if (path instanceof paper.CompoundPath) {
366
+ return path.children;
367
+ }
368
+ return [path];
369
+ }
370
+ function finiteNumber(value) {
371
+ return Number.isFinite(value);
372
+ }
373
+ function countSelfIntersections(path) {
374
+ if (!path.closed) {
375
+ return 0;
376
+ }
377
+ try {
378
+ var children_1 = getChildPaths(path);
379
+ var count_1 = 0;
380
+ children_1.forEach(function (child, index) {
381
+ count_1 += child.getIntersections(child).length;
382
+ for (var i = index + 1; i < children_1.length; i += 1) {
383
+ count_1 += child.getIntersections(children_1[i]).length;
384
+ }
385
+ });
386
+ return count_1;
387
+ }
388
+ catch (error) {
389
+ return 0;
390
+ }
391
+ }
392
+ function samplePoints(path, maxPerChild) {
393
+ if (maxPerChild === void 0) { maxPerChild = 16; }
394
+ var points = [];
395
+ getChildPaths(path).forEach(function (child) {
396
+ if (!child.length || child.segments.length === 0) {
397
+ return;
398
+ }
399
+ var count = Math.min(maxPerChild, Math.max(4, Math.ceil(child.length / 30)));
400
+ for (var i = 0; i < count; i += 1) {
401
+ var ratio = child.closed ? i / count : i / Math.max(count - 1, 1);
402
+ var point = child.getPointAt(child.length * ratio);
403
+ if (point) {
404
+ points.push(point);
405
+ }
406
+ }
407
+ });
408
+ return points;
409
+ }
410
+ function containsPoint(path, point) {
411
+ try {
412
+ return path.contains(point);
413
+ }
414
+ catch (error) {
415
+ return false;
416
+ }
417
+ }
418
+ function distanceToPath(path, point) {
419
+ try {
420
+ var nearest = path.getNearestPoint(point);
421
+ return nearest ? nearest.getDistance(point) : Number.POSITIVE_INFINITY;
422
+ }
423
+ catch (error) {
424
+ return Number.POSITIVE_INFINITY;
425
+ }
426
+ }
427
+ function addWarning(warnings, warning) {
428
+ if (warnings.indexOf(warning) === -1) {
429
+ warnings.push(warning);
430
+ }
431
+ }
432
+ function analyzeOffsetQuality(source, result, offset, options) {
433
+ if (options === void 0) { options = {}; }
434
+ var warnings = new Array();
435
+ var expectedClosed = options.stroke ? true : source.closed;
436
+ var segmentCount = getSegments(result).length;
437
+ var area = Math.abs(result.area || 0);
438
+ var absOffset = Math.abs(offset);
439
+ var score = segmentCount * 0.01;
440
+ var containmentErrors = 0;
441
+ var distanceErrors = 0;
442
+ var bounds = result.bounds;
443
+ if (segmentCount === 0) {
444
+ score += 100000;
445
+ addWarning(warnings, 'empty-result');
446
+ }
447
+ if (!bounds || !finiteNumber(bounds.x) || !finiteNumber(bounds.y) || !finiteNumber(bounds.width) || !finiteNumber(bounds.height)) {
448
+ score += 100000;
449
+ addWarning(warnings, 'non-finite-bounds');
450
+ }
451
+ if (result.closed !== expectedClosed) {
452
+ score += 50000;
453
+ addWarning(warnings, 'unexpected-closed-state');
454
+ }
455
+ var selfIntersections = countSelfIntersections(result);
456
+ if (selfIntersections > 0) {
457
+ score += selfIntersections * 1000;
458
+ addWarning(warnings, 'self-intersection');
459
+ }
460
+ if (source.closed && result.closed && !options.stroke) {
461
+ var sourceArea = Math.abs(source.area || 0);
462
+ if (sourceArea > 0 && offset > 0 && area < sourceArea * 0.95) {
463
+ score += ((sourceArea - area) / sourceArea) * 2000;
464
+ addWarning(warnings, 'positive-offset-area-shrank');
465
+ }
466
+ if (sourceArea > 0 && offset < 0 && area > sourceArea * 1.05) {
467
+ score += ((area - sourceArea) / sourceArea) * 2000;
468
+ addWarning(warnings, 'negative-offset-area-grew');
469
+ }
470
+ if (sourceArea > 0 && offset < 0) {
471
+ var areaRatio = area / sourceArea;
472
+ if (areaRatio < 0.25) {
473
+ score += (0.25 - areaRatio) * 4000;
474
+ addWarning(warnings, 'negative-offset-collapse');
475
+ }
476
+ }
477
+ if (sourceArea > 0 && offset > 0) {
478
+ var sourceBounds = source.bounds;
479
+ var centerShift = result.bounds.center.getDistance(sourceBounds.center);
480
+ var centerTolerance = Math.max(absOffset * 1.15, Math.min(sourceBounds.width, sourceBounds.height) * 0.08);
481
+ if (centerShift > centerTolerance) {
482
+ score += (centerShift - centerTolerance) * 80;
483
+ addWarning(warnings, 'offset-center-shift');
484
+ }
485
+ }
486
+ var containmentTolerance_1 = Math.max(absOffset * 0.08, 0.5);
487
+ var containmentSamples = offset >= 0 ? samplePoints(source) : samplePoints(result);
488
+ containmentSamples.forEach(function (point) {
489
+ var container = offset >= 0 ? result : source;
490
+ if (!containsPoint(container, point) && distanceToPath(container, point) > containmentTolerance_1) {
491
+ containmentErrors += 1;
492
+ }
493
+ });
494
+ if (containmentErrors > 0) {
495
+ score += containmentErrors * 150;
496
+ addWarning(warnings, offset >= 0 ? 'source-outside-positive-offset' : 'negative-offset-outside-source');
497
+ }
498
+ }
499
+ if (absOffset > 0.001) {
500
+ var distanceTolerance_1 = Math.max(absOffset * 0.18, 0.75);
501
+ samplePoints(result).forEach(function (point) {
502
+ var distance = distanceToPath(source, point);
503
+ if (finiteNumber(distance) && distance < distanceTolerance_1) {
504
+ distanceErrors += 1;
505
+ }
506
+ });
507
+ if (distanceErrors > 0) {
508
+ score += distanceErrors * 35;
509
+ addWarning(warnings, 'offset-distance-collapse');
510
+ }
511
+ }
512
+ return {
513
+ score: score,
514
+ warnings: warnings,
515
+ selfIntersections: selfIntersections,
516
+ containmentErrors: containmentErrors,
517
+ distanceErrors: distanceErrors,
518
+ segmentCount: segmentCount,
519
+ area: area,
520
+ };
521
+ }
522
+ function pickBestResult(source, offset, stroke, makeResult) {
523
+ var bestResult = null;
524
+ var bestQuality = null;
525
+ var firstError = null;
526
+ STRATEGIES.forEach(function (strategy) {
527
+ try {
528
+ var result = makeResult(strategy);
529
+ var quality = analyzeOffsetQuality(source, result, offset, { stroke: stroke });
530
+ quality.algorithm = strategy.algorithm;
531
+ if (!bestQuality || quality.score < bestQuality.score) {
532
+ bestResult = result;
533
+ bestQuality = quality;
534
+ }
535
+ }
536
+ catch (error) {
537
+ if (!firstError && error instanceof Error) {
538
+ firstError = error;
539
+ }
540
+ }
541
+ });
542
+ if (!bestResult) {
543
+ throw firstError || new Error('Unable to offset path with any algorithm');
544
+ }
545
+ return bestResult;
546
+ }
547
+ function getNonSelfIntersectionPath(path) {
548
+ if (path.closed) {
549
+ return path.unite(path, { insert: false });
550
+ }
551
+ return path;
552
+ }
553
+ function withoutAdaptiveFallback(strategy) {
554
+ return {
555
+ algorithm: 'robust',
556
+ splitSelfIntersectingCurves: strategy.splitSelfIntersectingCurves,
557
+ guardInsideJoins: strategy.guardInsideJoins,
558
+ simplifySelfIntersectingStroke: strategy.simplifySelfIntersectingStroke,
559
+ adaptiveFallback: false,
560
+ };
561
+ }
562
+ function addAdaptiveCandidate(candidates, makeResult) {
563
+ try {
564
+ candidates.push(makeResult());
565
+ }
566
+ catch (error) {
567
+ // Keep adaptive mode opportunistic: a failed fallback should not hide valid strict results.
568
+ }
569
+ }
570
+ function pickBestCandidate(source, offset, stroke, candidates) {
571
+ var bestResult = candidates[0];
572
+ var bestQuality = analyzeOffsetQuality(source, bestResult, offset, { stroke: stroke });
573
+ for (var i = 1; i < candidates.length; i += 1) {
574
+ var quality = analyzeOffsetQuality(source, candidates[i], offset, { stroke: stroke });
575
+ if (quality.score < bestQuality.score) {
576
+ bestResult = candidates[i];
577
+ bestQuality = quality;
578
+ }
579
+ }
580
+ return bestResult;
581
+ }
582
+ function offsetPathAdaptive(path, offset, join, limit, strategy) {
583
+ var baseStrategy = withoutAdaptiveFallback(strategy);
584
+ var candidates = new Array();
585
+ addAdaptiveCandidate(candidates, function () { return offsetPathWithStrategy(path, offset, join, limit, baseStrategy); });
586
+ if (join !== 'round') {
587
+ addAdaptiveCandidate(candidates, function () { return offsetPathWithStrategy(path, offset, 'round', limit, baseStrategy); });
588
+ }
589
+ if (path.closed && offset < 0) {
590
+ [0.8, 0.65, 0.5, 0.35, 0.25].forEach(function (factor) {
591
+ var fallbackOffset = offset * factor;
592
+ addAdaptiveCandidate(candidates, function () { return offsetPathWithStrategy(path, fallbackOffset, join, limit, baseStrategy); });
593
+ if (join !== 'round') {
594
+ addAdaptiveCandidate(candidates, function () { return offsetPathWithStrategy(path, fallbackOffset, 'round', limit, baseStrategy); });
595
+ }
596
+ });
597
+ }
598
+ if (candidates.length === 0) {
599
+ return offsetPathWithStrategy(path, offset, join, limit, baseStrategy);
600
+ }
601
+ return pickBestCandidate(path, offset, false, candidates);
602
+ }
603
+ function offsetPathWithStrategy(path, offset, join, limit, strategy) {
604
+ if (strategy.adaptiveFallback) {
605
+ return offsetPathAdaptive(path, offset, join, limit, strategy);
606
+ }
607
+ var nonSIPath = getNonSelfIntersectionPath(path);
608
+ var result = nonSIPath;
609
+ if (nonSIPath instanceof paper.Path) {
610
+ result = offsetSimpleShape(nonSIPath, offset, join, limit, strategy);
611
+ }
612
+ else {
613
+ var offsetParts = nonSIPath.children.map(function (c) {
614
+ if (c.segments.length > 1) {
615
+ if (!isSameDirection(c, path)) {
616
+ c.reverse();
617
+ }
618
+ var offsetPath_1 = offsetSimpleShape(c, offset, join, limit, strategy);
619
+ offsetPath_1 = normalize(offsetPath_1);
620
+ if (offsetPath_1.clockwise !== c.clockwise) {
621
+ offsetPath_1.reverse();
622
+ }
623
+ if (offsetPath_1 instanceof paper.CompoundPath) {
624
+ offsetPath_1.applyMatrix = true;
625
+ return offsetPath_1.children;
626
+ }
627
+ else {
628
+ return offsetPath_1;
629
+ }
630
+ }
631
+ else {
632
+ return null;
633
+ }
634
+ });
635
+ var children = offsetParts.flat().filter(function (c) { return !!c; });
636
+ result = new paper.CompoundPath({ children: children, insert: false });
637
+ }
638
+ result = normalize(result);
639
+ result.copyAttributes(nonSIPath, false);
640
+ result.remove();
641
+ return result;
642
+ }
643
+ function offsetPath(path, offset, join, limit, algorithm) {
644
+ if (algorithm === void 0) { algorithm = 'auto'; }
645
+ if (algorithm === 'auto') {
646
+ return pickBestResult(path, offset, false, function (strategy) { return offsetPathWithStrategy(path, offset, join, limit, strategy); });
647
+ }
648
+ return offsetPathWithStrategy(path, offset, join, limit, getStrategy(algorithm));
649
+ }
650
+ function offsetStrokeWithStrategy(path, offset, join, cap, limit, strategy) {
651
+ if (strategy.adaptiveFallback) {
652
+ return offsetStrokeAdaptive(path, offset, join, cap, limit, strategy);
653
+ }
654
+ var nonSIPath = getNonSelfIntersectionPath(path);
655
+ var result = nonSIPath;
656
+ if (nonSIPath instanceof paper.Path) {
657
+ result = offsetSimpleStroke(nonSIPath, offset, join, cap, limit, strategy);
658
+ }
659
+ else {
660
+ var children = nonSIPath.children.flatMap(function (c) {
661
+ return offsetSimpleStroke(c, offset, join, cap, limit, strategy);
662
+ });
663
+ result = children.reduce(function (c1, c2) { return c1.unite(c2, { insert: false }); });
664
+ }
665
+ result.strokeWidth = 0;
666
+ result.fillColor = nonSIPath.strokeColor;
667
+ result.shadowBlur = nonSIPath.shadowBlur;
668
+ result.shadowColor = nonSIPath.shadowColor;
669
+ result.shadowOffset = nonSIPath.shadowOffset;
670
+ return result;
671
+ }
672
+ function offsetStrokeAdaptive(path, offset, join, cap, limit, strategy) {
673
+ var baseStrategy = withoutAdaptiveFallback(strategy);
674
+ var candidates = new Array();
675
+ addAdaptiveCandidate(candidates, function () { return offsetStrokeWithStrategy(path, offset, join, cap, limit, baseStrategy); });
676
+ if (join !== 'round') {
677
+ addAdaptiveCandidate(candidates, function () { return offsetStrokeWithStrategy(path, offset, 'round', cap, limit, baseStrategy); });
678
+ }
679
+ if (cap !== 'round') {
680
+ addAdaptiveCandidate(candidates, function () { return offsetStrokeWithStrategy(path, offset, join, 'round', limit, baseStrategy); });
681
+ }
682
+ if (join !== 'round' && cap !== 'round') {
683
+ addAdaptiveCandidate(candidates, function () { return offsetStrokeWithStrategy(path, offset, 'round', 'round', limit, baseStrategy); });
684
+ }
685
+ if (candidates.length === 0) {
686
+ return offsetStrokeWithStrategy(path, offset, join, cap, limit, baseStrategy);
687
+ }
688
+ return pickBestCandidate(path, offset, true, candidates);
689
+ }
690
+ function offsetStroke$1(path, offset, join, cap, limit, algorithm) {
691
+ if (algorithm === void 0) { algorithm = 'auto'; }
692
+ if (algorithm === 'auto') {
693
+ return pickBestResult(path, offset, true, function (strategy) { return offsetStrokeWithStrategy(path, offset, join, cap, limit, strategy); });
694
+ }
695
+ return offsetStrokeWithStrategy(path, offset, join, cap, limit, getStrategy(algorithm));
696
+ }
697
+
698
+ function resolveOptions(options) {
699
+ var _a, _b, _c, _d;
700
+ return {
701
+ join: (_a = options === null || options === void 0 ? void 0 : options.join) !== null && _a !== void 0 ? _a : 'miter',
702
+ cap: (_b = options === null || options === void 0 ? void 0 : options.cap) !== null && _b !== void 0 ? _b : 'butt',
703
+ limit: (_c = options === null || options === void 0 ? void 0 : options.limit) !== null && _c !== void 0 ? _c : 10,
704
+ algorithm: (_d = options === null || options === void 0 ? void 0 : options.algorithm) !== null && _d !== void 0 ? _d : 'auto',
705
+ };
706
+ }
707
+ function insertResult(source, result, options) {
708
+ if (!options || options.insert !== false) {
709
+ (source.parent || paper.project.activeLayer).addChild(result);
710
+ }
711
+ }
712
+ function offset(path, distance, options) {
713
+ var resolvedOptions = resolveOptions(options);
714
+ var newPath = offsetPath(path, distance, resolvedOptions.join, resolvedOptions.limit, resolvedOptions.algorithm);
715
+ insertResult(path, newPath, options);
716
+ return newPath;
717
+ }
718
+ function offsetStroke(path, distance, options) {
719
+ var resolvedOptions = resolveOptions(options);
720
+ var newPath = offsetStroke$1(path, distance, resolvedOptions.join, resolvedOptions.cap, resolvedOptions.limit, resolvedOptions.algorithm);
721
+ insertResult(path, newPath, options);
722
+ return newPath;
723
+ }
724
+ function analyze(source, result, distance, options) {
725
+ return analyzeOffsetQuality(source, result, distance, options || {});
726
+ }
727
+ var PaperOffset = /** @class */ (function () {
728
+ function PaperOffset() {
729
+ }
730
+ PaperOffset.offset = function (path, distance, options) {
731
+ return offset(path, distance, options);
732
+ };
733
+ PaperOffset.offsetStroke = function (path, distance, options) {
734
+ return offsetStroke(path, distance, options);
735
+ };
736
+ PaperOffset.analyze = function (source, result, distance, options) {
737
+ return analyze(source, result, distance, options);
738
+ };
739
+ return PaperOffset;
740
+ }());
741
+ /**
742
+ * @deprecated EXTEND existing paper module is not recommend anymore
743
+ */
744
+ function ExtendPaperJs(paperNs) {
745
+ paperNs.Path.prototype.offset = function (distance, options) {
746
+ return offset(this, distance, options);
747
+ };
748
+ paperNs.Path.prototype.offsetStroke = function (distance, options) {
749
+ return offsetStroke(this, distance, options);
750
+ };
751
+ paperNs.CompoundPath.prototype.offset = function (distance, options) {
752
+ return offset(this, distance, options);
753
+ };
754
+ paperNs.CompoundPath.prototype.offsetStroke = function (distance, options) {
755
+ return offsetStroke(this, distance, options);
756
+ };
757
+ }
758
+
759
+ export { PaperOffset, analyze, ExtendPaperJs as default, ExtendPaperJs as extendPaperJs, offset, offsetStroke };
760
+ //# sourceMappingURL=index.mjs.map