@pooder/kit 5.3.1 → 5.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.
Files changed (90) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.d.mts +243 -36
  3. package/dist/index.d.ts +243 -36
  4. package/dist/index.js +2278 -1041
  5. package/dist/index.mjs +2278 -1041
  6. package/package.json +1 -1
  7. package/src/coordinate.ts +106 -106
  8. package/src/extensions/background.ts +323 -230
  9. package/src/extensions/bridgeSelection.ts +17 -17
  10. package/src/extensions/constraints.ts +322 -322
  11. package/src/extensions/dieline.ts +1149 -1076
  12. package/src/extensions/dielineShape.ts +109 -0
  13. package/src/extensions/edgeScale.ts +19 -19
  14. package/src/extensions/feature.ts +1137 -1021
  15. package/src/extensions/featureComplete.ts +46 -46
  16. package/src/extensions/film.ts +266 -194
  17. package/src/extensions/geometry.ts +885 -752
  18. package/src/extensions/image.ts +2054 -1926
  19. package/src/extensions/index.ts +11 -11
  20. package/src/extensions/maskOps.ts +283 -283
  21. package/src/extensions/mirror.ts +128 -128
  22. package/src/extensions/ruler.ts +654 -451
  23. package/src/extensions/sceneLayout.ts +140 -140
  24. package/src/extensions/sceneLayoutModel.ts +364 -352
  25. package/src/extensions/sceneVisibility.ts +64 -71
  26. package/src/extensions/size.ts +389 -389
  27. package/src/extensions/tracer.ts +1019 -1019
  28. package/src/extensions/white-ink.ts +1567 -1514
  29. package/src/extensions/wrappedOffsets.ts +33 -33
  30. package/src/index.ts +2 -2
  31. package/src/services/CanvasService.ts +832 -300
  32. package/src/services/ViewportSystem.ts +95 -95
  33. package/src/services/index.ts +3 -3
  34. package/src/services/renderSpec.ts +53 -18
  35. package/src/units.ts +27 -27
  36. package/tests/run.ts +118 -118
  37. package/tsconfig.test.json +15 -15
  38. package/.test-dist/src/CanvasService.js +0 -249
  39. package/.test-dist/src/ViewportSystem.js +0 -75
  40. package/.test-dist/src/background.js +0 -203
  41. package/.test-dist/src/bridgeSelection.js +0 -20
  42. package/.test-dist/src/constraints.js +0 -237
  43. package/.test-dist/src/coordinate.js +0 -74
  44. package/.test-dist/src/dieline.js +0 -818
  45. package/.test-dist/src/edgeScale.js +0 -12
  46. package/.test-dist/src/extensions/background.js +0 -203
  47. package/.test-dist/src/extensions/bridgeSelection.js +0 -20
  48. package/.test-dist/src/extensions/constraints.js +0 -237
  49. package/.test-dist/src/extensions/dieline.js +0 -828
  50. package/.test-dist/src/extensions/edgeScale.js +0 -12
  51. package/.test-dist/src/extensions/feature.js +0 -825
  52. package/.test-dist/src/extensions/featureComplete.js +0 -32
  53. package/.test-dist/src/extensions/film.js +0 -167
  54. package/.test-dist/src/extensions/geometry.js +0 -545
  55. package/.test-dist/src/extensions/image.js +0 -1529
  56. package/.test-dist/src/extensions/index.js +0 -30
  57. package/.test-dist/src/extensions/maskOps.js +0 -279
  58. package/.test-dist/src/extensions/mirror.js +0 -104
  59. package/.test-dist/src/extensions/ruler.js +0 -345
  60. package/.test-dist/src/extensions/sceneLayout.js +0 -96
  61. package/.test-dist/src/extensions/sceneLayoutModel.js +0 -196
  62. package/.test-dist/src/extensions/sceneVisibility.js +0 -62
  63. package/.test-dist/src/extensions/size.js +0 -331
  64. package/.test-dist/src/extensions/tracer.js +0 -538
  65. package/.test-dist/src/extensions/white-ink.js +0 -1190
  66. package/.test-dist/src/extensions/wrappedOffsets.js +0 -33
  67. package/.test-dist/src/feature.js +0 -826
  68. package/.test-dist/src/featureComplete.js +0 -32
  69. package/.test-dist/src/film.js +0 -167
  70. package/.test-dist/src/geometry.js +0 -506
  71. package/.test-dist/src/image.js +0 -1250
  72. package/.test-dist/src/index.js +0 -18
  73. package/.test-dist/src/maskOps.js +0 -270
  74. package/.test-dist/src/mirror.js +0 -104
  75. package/.test-dist/src/renderSpec.js +0 -2
  76. package/.test-dist/src/ruler.js +0 -343
  77. package/.test-dist/src/sceneLayout.js +0 -99
  78. package/.test-dist/src/sceneLayoutModel.js +0 -196
  79. package/.test-dist/src/sceneView.js +0 -40
  80. package/.test-dist/src/sceneVisibility.js +0 -42
  81. package/.test-dist/src/services/CanvasService.js +0 -249
  82. package/.test-dist/src/services/ViewportSystem.js +0 -76
  83. package/.test-dist/src/services/index.js +0 -24
  84. package/.test-dist/src/services/renderSpec.js +0 -2
  85. package/.test-dist/src/size.js +0 -332
  86. package/.test-dist/src/tracer.js +0 -544
  87. package/.test-dist/src/units.js +0 -30
  88. package/.test-dist/src/white-ink.js +0 -829
  89. package/.test-dist/src/wrappedOffsets.js +0 -33
  90. package/.test-dist/tests/run.js +0 -94
@@ -1,752 +1,885 @@
1
- import paper from "paper";
2
- import { pickExitIndex, scoreOutsideAbove } from "./bridgeSelection";
3
- import { sampleWrappedOffsets, wrappedDistance } from "./wrappedOffsets";
4
-
5
- export type FeatureOperation = "add" | "subtract";
6
- export type FeatureShape = "rect" | "circle";
7
-
8
- export interface DielineFeature {
9
- id: string;
10
- groupId?: string;
11
- operation: FeatureOperation;
12
- shape: FeatureShape;
13
- x: number;
14
- y: number;
15
- width?: number;
16
- height?: number;
17
- radius?: number;
18
- rotation?: number;
19
- // Rendering behavior: 'edge' (modifies perimeter) or 'surface' (hole/island)
20
- renderBehavior?: "edge" | "surface";
21
- color?: string;
22
- strokeDash?: number[];
23
- skipCut?: boolean;
24
- bridge?: {
25
- type: "vertical";
26
- };
27
- }
28
-
29
- export interface GeometryOptions {
30
- shape: "rect" | "circle" | "ellipse" | "custom";
31
- width: number;
32
- height: number;
33
- radius: number;
34
- x: number;
35
- y: number;
36
- features: Array<DielineFeature>;
37
- pathData?: string;
38
- customSourceWidthPx?: number;
39
- customSourceHeightPx?: number;
40
- canvasWidth?: number;
41
- canvasHeight?: number;
42
- }
43
-
44
- export interface MaskGeometryOptions extends GeometryOptions {
45
- canvasWidth: number;
46
- canvasHeight: number;
47
- }
48
-
49
- /**
50
- * Resolves the absolute position of a feature based on normalized coordinates.
51
- */
52
- export function resolveFeaturePosition(
53
- feature: DielineFeature,
54
- geometry: { x: number; y: number; width: number; height: number },
55
- ): { x: number; y: number } {
56
- const { x, y, width, height } = geometry;
57
- // geometry.x/y is the Center.
58
- const left = x - width / 2;
59
- const top = y - height / 2;
60
-
61
- return {
62
- x: left + feature.x * width,
63
- y: top + feature.y * height,
64
- };
65
- }
66
-
67
- /**
68
- * Initializes paper.js project if not already initialized.
69
- */
70
- function ensurePaper(width: number, height: number) {
71
- if (!paper.project) {
72
- paper.setup(new paper.Size(width, height));
73
- } else {
74
- paper.view.viewSize = new paper.Size(width, height);
75
- }
76
- }
77
-
78
- const isBridgeDebugEnabled = () =>
79
- Boolean((globalThis as any).__POODER_BRIDGE_DEBUG__);
80
-
81
- function normalizePathItem(shape: paper.PathItem): paper.PathItem {
82
- let result: any = shape;
83
- if (typeof result.resolveCrossings === "function") result = result.resolveCrossings();
84
- if (typeof result.reduce === "function") result = result.reduce({});
85
- if (typeof result.reorient === "function") result = result.reorient(true, true);
86
- if (typeof result.reduce === "function") result = result.reduce({});
87
- return result as paper.PathItem;
88
- }
89
-
90
- function getBridgeDelta(itemBounds: paper.Rectangle, overlap: number) {
91
- return Math.max(overlap, Math.min(5, Math.max(1, itemBounds.height * 0.02)));
92
- }
93
-
94
- function getExitHit(args: {
95
- mainShape: paper.Path;
96
- x: number;
97
- bridgeBottom: number;
98
- toY: number;
99
- eps: number;
100
- delta: number;
101
- overlap: number;
102
- op: FeatureOperation;
103
- }) {
104
- const { mainShape, x, bridgeBottom, toY, eps, delta, overlap, op } = args;
105
-
106
- const ray = new paper.Path.Line({
107
- from: [x, bridgeBottom],
108
- to: [x, toY],
109
- insert: false,
110
- });
111
-
112
- const intersections = mainShape.getIntersections(ray) || [];
113
- ray.remove();
114
-
115
- const validHits = intersections.filter((i) => i.point.y < bridgeBottom - eps);
116
- if (validHits.length === 0) return null;
117
-
118
- validHits.sort((a, b) => b.point.y - a.point.y);
119
- const flags = validHits.map((h) => {
120
- const above = h.point.add(new paper.Point(0, -delta));
121
- const below = h.point.add(new paper.Point(0, delta));
122
- return {
123
- insideAbove: mainShape.contains(above),
124
- insideBelow: mainShape.contains(below),
125
- };
126
- });
127
-
128
- const idx = pickExitIndex(flags);
129
- if (idx < 0) return null;
130
-
131
- if (isBridgeDebugEnabled()) {
132
- console.debug("Geometry: Bridge ray", {
133
- x,
134
- validHits: validHits.length,
135
- idx,
136
- delta,
137
- overlap,
138
- op,
139
- });
140
- }
141
-
142
- const hit = validHits[idx];
143
- return { point: hit.point, location: hit };
144
- }
145
-
146
- function selectOuterChain(args: {
147
- mainShape: paper.Path;
148
- pointsA: paper.Point[];
149
- pointsB: paper.Point[];
150
- delta: number;
151
- overlap: number;
152
- op: FeatureOperation;
153
- }) {
154
- const { mainShape, pointsA, pointsB, delta, overlap, op } = args;
155
-
156
- const scoreA = scoreOutsideAbove(
157
- pointsA.map((p) => ({
158
- outsideAbove: !mainShape.contains(p.add(new paper.Point(0, -delta))),
159
- })),
160
- );
161
- const scoreB = scoreOutsideAbove(
162
- pointsB.map((p) => ({
163
- outsideAbove: !mainShape.contains(p.add(new paper.Point(0, -delta))),
164
- })),
165
- );
166
-
167
- const ratioA = scoreA / pointsA.length;
168
- const ratioB = scoreB / pointsB.length;
169
-
170
- if (isBridgeDebugEnabled()) {
171
- console.debug("Geometry: Bridge chain", {
172
- scoreA,
173
- scoreB,
174
- lenA: pointsA.length,
175
- lenB: pointsB.length,
176
- ratioA,
177
- ratioB,
178
- delta,
179
- overlap,
180
- op,
181
- });
182
- }
183
-
184
- const ratioEps = 1e-6;
185
- if (Math.abs(ratioA - ratioB) > ratioEps) {
186
- return ratioA > ratioB ? pointsA : pointsB;
187
- }
188
- if (scoreA !== scoreB) return scoreA > scoreB ? pointsA : pointsB;
189
- return pointsA.length <= pointsB.length ? pointsA : pointsB;
190
- }
191
-
192
- /**
193
- * Creates the base dieline shape (Rect/Circle/Ellipse/Custom)
194
- */
195
- function createBaseShape(options: GeometryOptions): paper.PathItem {
196
- const {
197
- shape,
198
- width,
199
- height,
200
- radius,
201
- x,
202
- y,
203
- pathData,
204
- customSourceWidthPx,
205
- customSourceHeightPx,
206
- } = options;
207
- const center = new paper.Point(x, y);
208
-
209
- if (shape === "rect") {
210
- return new paper.Path.Rectangle({
211
- point: [x - width / 2, y - height / 2],
212
- size: [Math.max(0, width), Math.max(0, height)],
213
- radius: Math.max(0, radius),
214
- });
215
- } else if (shape === "circle") {
216
- const r = Math.min(width, height) / 2;
217
- return new paper.Path.Circle({
218
- center: center,
219
- radius: Math.max(0, r),
220
- });
221
- } else if (shape === "ellipse") {
222
- return new paper.Path.Ellipse({
223
- center: center,
224
- radius: [Math.max(0, width / 2), Math.max(0, height / 2)],
225
- });
226
- } else if (shape === "custom" && pathData) {
227
- const hasMultipleSubPaths = ((pathData.match(/[Mm]/g) || []).length ?? 0) > 1;
228
- const path: paper.PathItem = hasMultipleSubPaths
229
- ? new paper.CompoundPath(pathData)
230
- : (() => {
231
- const single = new paper.Path();
232
- single.pathData = pathData;
233
- return single;
234
- })();
235
- const sourceWidth = Number(customSourceWidthPx ?? 0);
236
- const sourceHeight = Number(customSourceHeightPx ?? 0);
237
- if (
238
- Number.isFinite(sourceWidth) &&
239
- Number.isFinite(sourceHeight) &&
240
- sourceWidth > 0 &&
241
- sourceHeight > 0 &&
242
- width > 0 &&
243
- height > 0
244
- ) {
245
- // Preserve original detect-space offset/expand by mapping source image
246
- // coordinates directly into the target dieline frame.
247
- const targetLeft = x - width / 2;
248
- const targetTop = y - height / 2;
249
- path.scale(width / sourceWidth, height / sourceHeight, new paper.Point(0, 0));
250
- path.translate(new paper.Point(targetLeft, targetTop));
251
- return path;
252
- }
253
-
254
- if (
255
- width > 0 &&
256
- height > 0 &&
257
- path.bounds.width > 0 &&
258
- path.bounds.height > 0
259
- ) {
260
- // Fallback for malformed custom-path metadata.
261
- path.position = center;
262
- path.scale(width / path.bounds.width, height / path.bounds.height);
263
- return path;
264
- }
265
- path.position = center;
266
- return path;
267
- } else {
268
- return new paper.Path.Rectangle({
269
- point: [x - width / 2, y - height / 2],
270
- size: [Math.max(0, width), Math.max(0, height)],
271
- });
272
- }
273
- }
274
-
275
- function resolveBridgeBasePath(
276
- shape: paper.PathItem,
277
- anchor: paper.Point,
278
- ): paper.Path | null {
279
- if (shape instanceof paper.Path) {
280
- return shape;
281
- }
282
-
283
- if (shape instanceof paper.CompoundPath) {
284
- const children = (shape.children || []).filter(
285
- (child): child is paper.Path => child instanceof paper.Path,
286
- );
287
- if (!children.length) return null;
288
- let best = children[0];
289
- let bestDistance = Infinity;
290
- for (const child of children) {
291
- const location = child.getNearestLocation(anchor);
292
- const point = location?.point;
293
- if (!point) continue;
294
- const distance = point.getDistance(anchor);
295
- if (distance < bestDistance) {
296
- bestDistance = distance;
297
- best = child;
298
- }
299
- }
300
- return best;
301
- }
302
-
303
- return null;
304
- }
305
-
306
- /**
307
- * Creates a Paper.js Item for a single feature.
308
- */
309
- function createFeatureItem(
310
- feature: DielineFeature,
311
- center: paper.Point,
312
- ): paper.PathItem {
313
- let item: paper.PathItem;
314
-
315
- if (feature.shape === "rect") {
316
- const w = feature.width || 10;
317
- const h = feature.height || 10;
318
- const r = feature.radius || 0;
319
- item = new paper.Path.Rectangle({
320
- point: [center.x - w / 2, center.y - h / 2],
321
- size: [w, h],
322
- radius: r,
323
- });
324
- } else {
325
- // Circle
326
- const r = feature.radius || 5;
327
- item = new paper.Path.Circle({
328
- center: center,
329
- radius: r,
330
- });
331
- }
332
-
333
- if (feature.rotation) {
334
- item.rotate(feature.rotation, center);
335
- }
336
-
337
- return item;
338
- }
339
-
340
- /**
341
- * Internal helper to generate the Perimeter Shape (Base + Edge Features).
342
- */
343
- function getPerimeterShape(options: GeometryOptions): paper.PathItem {
344
- // 1. Create Base Shape
345
- let mainShape = createBaseShape(options);
346
-
347
- const { features } = options;
348
-
349
- if (features && features.length > 0) {
350
- // Filter for Edge Features (Default is Edge, unless explicit 'surface')
351
- const edgeFeatures = features.filter(
352
- (f) => !f.renderBehavior || f.renderBehavior === "edge",
353
- );
354
-
355
- const adds: paper.PathItem[] = [];
356
- const subtracts: paper.PathItem[] = [];
357
-
358
- edgeFeatures.forEach((f) => {
359
- const pos = resolveFeaturePosition(f, options);
360
- const center = new paper.Point(pos.x, pos.y);
361
- const item = createFeatureItem(f, center);
362
-
363
- // Handle Bridge logic: Create a connection shape to the main body
364
- if (f.bridge && f.bridge.type === "vertical") {
365
- const itemBounds = item.bounds;
366
- const mainBounds = mainShape.bounds;
367
- const bridgeTop = mainBounds.top;
368
- const bridgeBottom = itemBounds.top;
369
-
370
- if (bridgeBottom > bridgeTop) {
371
- const overlap = 2;
372
- const rayPadding = 10;
373
- const eps = 0.1;
374
- const delta = getBridgeDelta(itemBounds, overlap);
375
-
376
- const toY = bridgeTop - rayPadding;
377
- const inset = Math.min(1, Math.max(0, itemBounds.width * 0.01));
378
- const xLeft = itemBounds.left + inset;
379
- const xRight = itemBounds.right - inset;
380
- const bridgeBasePath = resolveBridgeBasePath(mainShape, center);
381
- const canBridge = !!bridgeBasePath && xRight - xLeft > eps;
382
-
383
- if (canBridge && bridgeBasePath) {
384
- const leftHit = getExitHit({
385
- mainShape: bridgeBasePath,
386
- x: xLeft,
387
- bridgeBottom,
388
- toY,
389
- eps,
390
- delta,
391
- overlap,
392
- op: f.operation,
393
- });
394
- const rightHit = getExitHit({
395
- mainShape: bridgeBasePath,
396
- x: xRight,
397
- bridgeBottom,
398
- toY,
399
- eps,
400
- delta,
401
- overlap,
402
- op: f.operation,
403
- });
404
-
405
- if (leftHit && rightHit) {
406
- const pathLength = bridgeBasePath.length;
407
- const leftOffset = leftHit.location.offset;
408
- const rightOffset = rightHit.location.offset;
409
-
410
- const distanceA = wrappedDistance(pathLength, leftOffset, rightOffset);
411
- const distanceB = wrappedDistance(pathLength, rightOffset, leftOffset);
412
- const countFor = (d: number) =>
413
- Math.max(8, Math.min(80, Math.ceil(d / 6)));
414
-
415
- const offsetsA = sampleWrappedOffsets(
416
- pathLength,
417
- leftOffset,
418
- rightOffset,
419
- countFor(distanceA),
420
- );
421
-
422
- const offsetsB = sampleWrappedOffsets(
423
- pathLength,
424
- rightOffset,
425
- leftOffset,
426
- countFor(distanceB),
427
- );
428
-
429
- const pointsA = offsetsA
430
- .map((o) => bridgeBasePath.getPointAt(o))
431
- .filter((p): p is paper.Point => Boolean(p));
432
- const pointsB = offsetsB
433
- .map((o) => bridgeBasePath.getPointAt(o))
434
- .filter((p): p is paper.Point => Boolean(p));
435
-
436
- if (pointsA.length >= 2 && pointsB.length >= 2) {
437
- let topBase = selectOuterChain({
438
- mainShape: bridgeBasePath,
439
- pointsA,
440
- pointsB,
441
- delta,
442
- overlap,
443
- op: f.operation,
444
- });
445
-
446
- const dist2 = (a: paper.Point, b: paper.Point) => {
447
- const dx = a.x - b.x;
448
- const dy = a.y - b.y;
449
- return dx * dx + dy * dy;
450
- };
451
-
452
- if (
453
- dist2(topBase[0], leftHit.point) >
454
- dist2(topBase[0], rightHit.point)
455
- ) {
456
- topBase = topBase.slice().reverse();
457
- }
458
-
459
- topBase = topBase.slice();
460
- topBase[0] = leftHit.point;
461
- topBase[topBase.length - 1] = rightHit.point;
462
-
463
- const capShiftY =
464
- f.operation === "subtract"
465
- ? -Math.max(overlap * 2, delta)
466
- : overlap;
467
- const topPoints = topBase.map((p) =>
468
- p.add(new paper.Point(0, capShiftY)),
469
- );
470
-
471
- const bridgeBottomY = bridgeBottom + overlap * 2;
472
- const bridgePoly = new paper.Path({ insert: false });
473
- for (const p of topPoints) bridgePoly.add(p);
474
- bridgePoly.add(new paper.Point(xRight, bridgeBottomY));
475
- bridgePoly.add(new paper.Point(xLeft, bridgeBottomY));
476
- bridgePoly.closed = true;
477
-
478
- const unitedItem = item.unite(bridgePoly);
479
- item.remove();
480
- bridgePoly.remove();
481
-
482
- if (f.operation === "add") {
483
- adds.push(unitedItem);
484
- } else {
485
- subtracts.push(unitedItem);
486
- }
487
- return;
488
- }
489
- }
490
- }
491
-
492
- if (f.operation === "add") {
493
- adds.push(item);
494
- } else {
495
- subtracts.push(item);
496
- }
497
- } else {
498
- if (f.operation === "add") {
499
- adds.push(item);
500
- } else {
501
- subtracts.push(item);
502
- }
503
- }
504
- } else {
505
- if (f.operation === "add") {
506
- adds.push(item);
507
- } else {
508
- subtracts.push(item);
509
- }
510
- }
511
- });
512
-
513
- // 2. Process Additions (Union)
514
- if (adds.length > 0) {
515
- for (const item of adds) {
516
- try {
517
- const temp = mainShape.unite(item);
518
- mainShape.remove();
519
- item.remove();
520
- mainShape = normalizePathItem(temp);
521
- } catch (e) {
522
- console.error("Geometry: Failed to unite feature", e);
523
- item.remove();
524
- }
525
- }
526
- }
527
-
528
- // 3. Process Subtractions (Difference)
529
- if (subtracts.length > 0) {
530
- for (const item of subtracts) {
531
- try {
532
- const temp = mainShape.subtract(item);
533
- mainShape.remove();
534
- item.remove();
535
- mainShape = normalizePathItem(temp);
536
- } catch (e) {
537
- console.error("Geometry: Failed to subtract feature", e);
538
- item.remove();
539
- }
540
- }
541
- }
542
- }
543
-
544
- return mainShape;
545
- }
546
-
547
- /**
548
- * Applies Internal/Surface features to a shape.
549
- */
550
- function applySurfaceFeatures(
551
- shape: paper.PathItem,
552
- features: DielineFeature[],
553
- options: GeometryOptions,
554
- ): paper.PathItem {
555
- const surfaceFeatures = features.filter(
556
- (f) => f.renderBehavior === "surface",
557
- );
558
-
559
- if (surfaceFeatures.length === 0) return shape;
560
-
561
- let result = shape;
562
-
563
- // Internal features are usually subtractive (holes)
564
- // But we support 'add' too (islands? maybe just unite)
565
-
566
- for (const f of surfaceFeatures) {
567
- const pos = resolveFeaturePosition(f, options);
568
- const center = new paper.Point(pos.x, pos.y);
569
- const item = createFeatureItem(f, center);
570
-
571
- try {
572
- if (f.operation === "add") {
573
- const temp = result.unite(item);
574
- result.remove();
575
- item.remove();
576
- result = normalizePathItem(temp);
577
- } else {
578
- const temp = result.subtract(item);
579
- result.remove();
580
- item.remove();
581
- result = normalizePathItem(temp);
582
- }
583
- } catch (e) {
584
- console.error("Geometry: Failed to apply surface feature", e);
585
- item.remove();
586
- }
587
- }
588
-
589
- return result;
590
- }
591
-
592
- /**
593
- * Generates the path data for the Dieline (Product Shape).
594
- */
595
- export function generateDielinePath(options: GeometryOptions): string {
596
- const paperWidth = options.canvasWidth || options.width * 2 || 2000;
597
- const paperHeight = options.canvasHeight || options.height * 2 || 2000;
598
- ensurePaper(paperWidth, paperHeight);
599
- paper.project.activeLayer.removeChildren();
600
-
601
- const perimeter = getPerimeterShape(options);
602
- const finalShape = applySurfaceFeatures(perimeter, options.features, options);
603
-
604
- const pathData = finalShape.pathData;
605
- finalShape.remove();
606
-
607
- return pathData;
608
- }
609
-
610
- /**
611
- * Generates the path data for the Mask (Background Overlay).
612
- * Logic: Canvas SUBTRACT ProductShape
613
- */
614
- export function generateMaskPath(options: MaskGeometryOptions): string {
615
- ensurePaper(options.canvasWidth, options.canvasHeight);
616
- paper.project.activeLayer.removeChildren();
617
-
618
- const { canvasWidth, canvasHeight } = options;
619
-
620
- const maskRect = new paper.Path.Rectangle({
621
- point: [0, 0],
622
- size: [canvasWidth, canvasHeight],
623
- });
624
-
625
- const perimeter = getPerimeterShape(options);
626
- const mainShape = applySurfaceFeatures(perimeter, options.features, options);
627
-
628
- const finalMask = maskRect.subtract(mainShape);
629
-
630
- maskRect.remove();
631
- mainShape.remove();
632
-
633
- const pathData = finalMask.pathData;
634
- finalMask.remove();
635
-
636
- return pathData;
637
- }
638
-
639
- /**
640
- * Generates the path data for the Bleed Zone.
641
- */
642
- export function generateBleedZonePath(
643
- originalOptions: GeometryOptions,
644
- offsetOptions: GeometryOptions,
645
- offset: number,
646
- ): string {
647
- const paperWidth =
648
- originalOptions.canvasWidth || originalOptions.width * 2 || 2000;
649
- const paperHeight =
650
- originalOptions.canvasHeight || originalOptions.height * 2 || 2000;
651
- ensurePaper(paperWidth, paperHeight);
652
- paper.project.activeLayer.removeChildren();
653
-
654
- // 1. Generate Original Shape
655
- const pOriginal = getPerimeterShape(originalOptions);
656
- const shapeOriginal = applySurfaceFeatures(
657
- pOriginal,
658
- originalOptions.features,
659
- originalOptions,
660
- );
661
-
662
- // 2. Generate Offset Shape
663
- const pOffset = getPerimeterShape(offsetOptions);
664
- const shapeOffset = applySurfaceFeatures(
665
- pOffset,
666
- offsetOptions.features,
667
- offsetOptions,
668
- );
669
-
670
- // 3. Calculate Difference
671
- let bleedZone: paper.PathItem;
672
- if (offset > 0) {
673
- bleedZone = shapeOffset.subtract(shapeOriginal);
674
- } else {
675
- bleedZone = shapeOriginal.subtract(shapeOffset);
676
- }
677
-
678
- const pathData = bleedZone.pathData;
679
-
680
- shapeOriginal.remove();
681
- shapeOffset.remove();
682
- bleedZone.remove();
683
-
684
- return pathData;
685
- }
686
-
687
- /**
688
- * Finds the lowest point (Max Y) on the Dieline geometry (Base Shape ONLY).
689
- */
690
- export function getLowestPointOnDieline(
691
- options: GeometryOptions,
692
- ): { x: number; y: number } {
693
- ensurePaper(options.width * 2, options.height * 2);
694
- paper.project.activeLayer.removeChildren();
695
-
696
- const shape = createBaseShape(options);
697
- const bounds = shape.bounds;
698
-
699
- const result = {
700
- x: bounds.center.x,
701
- y: bounds.bottom,
702
- };
703
- shape.remove();
704
-
705
- return result;
706
- }
707
-
708
- /**
709
- * Finds the nearest point on the Dieline geometry (Base Shape ONLY) for a given target point.
710
- * Used for constraining feature movement.
711
- */
712
- export function getNearestPointOnDieline(
713
- point: { x: number; y: number },
714
- options: GeometryOptions,
715
- ): { x: number; y: number; normal?: { x: number; y: number } } {
716
- ensurePaper(options.width * 2, options.height * 2);
717
- paper.project.activeLayer.removeChildren();
718
-
719
- // We constrain to the BASE shape, not including other features,
720
- // because usually you want to snap to the main edge.
721
- const shape = createBaseShape(options);
722
-
723
- const p = new paper.Point(point.x, point.y);
724
- const location = shape.getNearestLocation(p);
725
-
726
- const result = {
727
- x: location.point.x,
728
- y: location.point.y,
729
- normal: location.normal ? { x: location.normal.x, y: location.normal.y } : undefined
730
- };
731
- shape.remove();
732
-
733
- return result;
734
- }
735
-
736
- export function getPathBounds(pathData: string): {
737
- x: number;
738
- y: number;
739
- width: number;
740
- height: number;
741
- } {
742
- const path = new paper.Path();
743
- path.pathData = pathData;
744
- const bounds = path.bounds;
745
- path.remove();
746
- return {
747
- x: bounds.x,
748
- y: bounds.y,
749
- width: bounds.width,
750
- height: bounds.height,
751
- };
752
- }
1
+ import paper from "paper";
2
+ import { pickExitIndex, scoreOutsideAbove } from "./bridgeSelection";
3
+ import {
4
+ DEFAULT_DIELINE_SHAPE,
5
+ getHeartShapeParams,
6
+ getShapeFitMode,
7
+ } from "./dielineShape";
8
+ import type {
9
+ BuiltinDielineShape,
10
+ DielineShape,
11
+ DielineShapeStyle,
12
+ ShapeFitMode,
13
+ } from "./dielineShape";
14
+ import { sampleWrappedOffsets, wrappedDistance } from "./wrappedOffsets";
15
+
16
+ export type FeatureOperation = "add" | "subtract";
17
+ export type FeatureShape = "rect" | "circle";
18
+
19
+ export interface DielineFeature {
20
+ id: string;
21
+ groupId?: string;
22
+ operation: FeatureOperation;
23
+ shape: FeatureShape;
24
+ x: number;
25
+ y: number;
26
+ width?: number;
27
+ height?: number;
28
+ radius?: number;
29
+ rotation?: number;
30
+ // Rendering behavior: 'edge' (modifies perimeter) or 'surface' (hole/island)
31
+ renderBehavior?: "edge" | "surface";
32
+ color?: string;
33
+ strokeDash?: number[];
34
+ skipCut?: boolean;
35
+ bridge?: {
36
+ type: "vertical";
37
+ };
38
+ }
39
+
40
+ export interface GeometryOptions {
41
+ shape: DielineShape;
42
+ width: number;
43
+ height: number;
44
+ radius: number;
45
+ x: number;
46
+ y: number;
47
+ features: Array<DielineFeature>;
48
+ pathData?: string;
49
+ shapeStyle?: DielineShapeStyle;
50
+ customSourceWidthPx?: number;
51
+ customSourceHeightPx?: number;
52
+ canvasWidth?: number;
53
+ canvasHeight?: number;
54
+ }
55
+
56
+ export interface MaskGeometryOptions extends GeometryOptions {
57
+ canvasWidth: number;
58
+ canvasHeight: number;
59
+ }
60
+
61
+ /**
62
+ * Resolves the absolute position of a feature based on normalized coordinates.
63
+ */
64
+ export function resolveFeaturePosition(
65
+ feature: DielineFeature,
66
+ geometry: { x: number; y: number; width: number; height: number },
67
+ ): { x: number; y: number } {
68
+ const { x, y, width, height } = geometry;
69
+ // geometry.x/y is the Center.
70
+ const left = x - width / 2;
71
+ const top = y - height / 2;
72
+
73
+ return {
74
+ x: left + feature.x * width,
75
+ y: top + feature.y * height,
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Initializes paper.js project if not already initialized.
81
+ */
82
+ function ensurePaper(width: number, height: number) {
83
+ if (!paper.project) {
84
+ paper.setup(new paper.Size(width, height));
85
+ } else {
86
+ paper.view.viewSize = new paper.Size(width, height);
87
+ }
88
+ }
89
+
90
+ const isBridgeDebugEnabled = () =>
91
+ Boolean((globalThis as any).__POODER_BRIDGE_DEBUG__);
92
+
93
+ function normalizePathItem(shape: paper.PathItem): paper.PathItem {
94
+ let result: any = shape;
95
+ if (typeof result.resolveCrossings === "function") result = result.resolveCrossings();
96
+ if (typeof result.reduce === "function") result = result.reduce({});
97
+ if (typeof result.reorient === "function") result = result.reorient(true, true);
98
+ if (typeof result.reduce === "function") result = result.reduce({});
99
+ return result as paper.PathItem;
100
+ }
101
+
102
+ function getBridgeDelta(itemBounds: paper.Rectangle, overlap: number) {
103
+ return Math.max(overlap, Math.min(5, Math.max(1, itemBounds.height * 0.02)));
104
+ }
105
+
106
+ function getExitHit(args: {
107
+ mainShape: paper.Path;
108
+ x: number;
109
+ bridgeBottom: number;
110
+ toY: number;
111
+ eps: number;
112
+ delta: number;
113
+ overlap: number;
114
+ op: FeatureOperation;
115
+ }) {
116
+ const { mainShape, x, bridgeBottom, toY, eps, delta, overlap, op } = args;
117
+
118
+ const ray = new paper.Path.Line({
119
+ from: [x, bridgeBottom],
120
+ to: [x, toY],
121
+ insert: false,
122
+ });
123
+
124
+ const intersections = mainShape.getIntersections(ray) || [];
125
+ ray.remove();
126
+
127
+ const validHits = intersections.filter((i) => i.point.y < bridgeBottom - eps);
128
+ if (validHits.length === 0) return null;
129
+
130
+ validHits.sort((a, b) => b.point.y - a.point.y);
131
+ const flags = validHits.map((h) => {
132
+ const above = h.point.add(new paper.Point(0, -delta));
133
+ const below = h.point.add(new paper.Point(0, delta));
134
+ return {
135
+ insideAbove: mainShape.contains(above),
136
+ insideBelow: mainShape.contains(below),
137
+ };
138
+ });
139
+
140
+ const idx = pickExitIndex(flags);
141
+ if (idx < 0) return null;
142
+
143
+ if (isBridgeDebugEnabled()) {
144
+ console.debug("Geometry: Bridge ray", {
145
+ x,
146
+ validHits: validHits.length,
147
+ idx,
148
+ delta,
149
+ overlap,
150
+ op,
151
+ });
152
+ }
153
+
154
+ const hit = validHits[idx];
155
+ return { point: hit.point, location: hit };
156
+ }
157
+
158
+ function selectOuterChain(args: {
159
+ mainShape: paper.Path;
160
+ pointsA: paper.Point[];
161
+ pointsB: paper.Point[];
162
+ delta: number;
163
+ overlap: number;
164
+ op: FeatureOperation;
165
+ }) {
166
+ const { mainShape, pointsA, pointsB, delta, overlap, op } = args;
167
+
168
+ const scoreA = scoreOutsideAbove(
169
+ pointsA.map((p) => ({
170
+ outsideAbove: !mainShape.contains(p.add(new paper.Point(0, -delta))),
171
+ })),
172
+ );
173
+ const scoreB = scoreOutsideAbove(
174
+ pointsB.map((p) => ({
175
+ outsideAbove: !mainShape.contains(p.add(new paper.Point(0, -delta))),
176
+ })),
177
+ );
178
+
179
+ const ratioA = scoreA / pointsA.length;
180
+ const ratioB = scoreB / pointsB.length;
181
+
182
+ if (isBridgeDebugEnabled()) {
183
+ console.debug("Geometry: Bridge chain", {
184
+ scoreA,
185
+ scoreB,
186
+ lenA: pointsA.length,
187
+ lenB: pointsB.length,
188
+ ratioA,
189
+ ratioB,
190
+ delta,
191
+ overlap,
192
+ op,
193
+ });
194
+ }
195
+
196
+ const ratioEps = 1e-6;
197
+ if (Math.abs(ratioA - ratioB) > ratioEps) {
198
+ return ratioA > ratioB ? pointsA : pointsB;
199
+ }
200
+ if (scoreA !== scoreB) return scoreA > scoreB ? pointsA : pointsB;
201
+ return pointsA.length <= pointsB.length ? pointsA : pointsB;
202
+ }
203
+
204
+ /**
205
+ * Creates the base dieline shape (Rect/Circle/Ellipse/Heart/Custom).
206
+ */
207
+ type BuiltinShapeBuilder = (options: GeometryOptions) => paper.PathItem;
208
+
209
+ function fitPathItemToRect(
210
+ item: paper.PathItem,
211
+ rect: { left: number; top: number; width: number; height: number },
212
+ fitMode: ShapeFitMode,
213
+ ): paper.PathItem {
214
+ const { left, top, width, height } = rect;
215
+ const bounds = item.bounds;
216
+ if (
217
+ width <= 0 ||
218
+ height <= 0 ||
219
+ !Number.isFinite(bounds.width) ||
220
+ !Number.isFinite(bounds.height) ||
221
+ bounds.width <= 0 ||
222
+ bounds.height <= 0
223
+ ) {
224
+ item.position = new paper.Point(left + width / 2, top + height / 2);
225
+ return item;
226
+ }
227
+
228
+ item.translate(new paper.Point(-bounds.left, -bounds.top));
229
+ if (fitMode === "stretch") {
230
+ item.scale(width / bounds.width, height / bounds.height, new paper.Point(0, 0));
231
+ item.translate(new paper.Point(left, top));
232
+ return item;
233
+ }
234
+
235
+ const uniformScale = Math.min(width / bounds.width, height / bounds.height);
236
+ item.scale(uniformScale, uniformScale, new paper.Point(0, 0));
237
+ const scaledWidth = bounds.width * uniformScale;
238
+ const scaledHeight = bounds.height * uniformScale;
239
+ item.translate(
240
+ new paper.Point(
241
+ left + (width - scaledWidth) / 2,
242
+ top + (height - scaledHeight) / 2,
243
+ ),
244
+ );
245
+ return item;
246
+ }
247
+
248
+ function createNormalizedHeartPath(params: {
249
+ lobeSpread: number;
250
+ notchDepth: number;
251
+ tipSharpness: number;
252
+ }): paper.Path {
253
+ const { lobeSpread, notchDepth, tipSharpness } = params;
254
+
255
+ const halfSpread = 0.22 + lobeSpread * 0.18;
256
+ const notchY = 0.06 + notchDepth * 0.2;
257
+ const shoulderY = 0.24 + notchDepth * 0.2;
258
+ const topLift = 0.12 + (1 - notchDepth) * 0.06;
259
+ const topY = notchY - topLift;
260
+ const sideCtrlY = shoulderY - (0.18 - notchDepth * 0.08);
261
+ const lowerCtrlY = 0.58 + (1 - tipSharpness) * 0.16;
262
+ const tipCtrlX = 0.34 - tipSharpness * 0.2;
263
+ const notchCtrlX = 0.06 + lobeSpread * 0.06;
264
+ const lobeCtrlX = 0.1 + lobeSpread * 0.08;
265
+ const notchCtrlY = notchY - topLift * 0.45;
266
+
267
+ const xPeakL = 0.5 - halfSpread;
268
+ const xPeakR = 0.5 + halfSpread;
269
+
270
+ const heartPath = new paper.Path({ insert: false });
271
+ heartPath.moveTo(new paper.Point(0.5, notchY));
272
+ heartPath.cubicCurveTo(
273
+ new paper.Point(0.5 - notchCtrlX, notchCtrlY),
274
+ new paper.Point(xPeakL + lobeCtrlX, topY),
275
+ new paper.Point(xPeakL, topY),
276
+ );
277
+ heartPath.cubicCurveTo(
278
+ new paper.Point(xPeakL - lobeCtrlX, topY),
279
+ new paper.Point(0, sideCtrlY),
280
+ new paper.Point(0, shoulderY),
281
+ );
282
+ heartPath.cubicCurveTo(
283
+ new paper.Point(0, lowerCtrlY),
284
+ new paper.Point(tipCtrlX, 1),
285
+ new paper.Point(0.5, 1),
286
+ );
287
+ heartPath.cubicCurveTo(
288
+ new paper.Point(1 - tipCtrlX, 1),
289
+ new paper.Point(1, lowerCtrlY),
290
+ new paper.Point(1, shoulderY),
291
+ );
292
+ heartPath.cubicCurveTo(
293
+ new paper.Point(1, sideCtrlY),
294
+ new paper.Point(xPeakR + lobeCtrlX, topY),
295
+ new paper.Point(xPeakR, topY),
296
+ );
297
+ heartPath.cubicCurveTo(
298
+ new paper.Point(xPeakR - lobeCtrlX, topY),
299
+ new paper.Point(0.5 + notchCtrlX, notchCtrlY),
300
+ new paper.Point(0.5, notchY),
301
+ );
302
+ heartPath.closed = true;
303
+ return heartPath;
304
+ }
305
+
306
+ function createHeartBaseShape(options: GeometryOptions): paper.PathItem {
307
+ const { x, y, width, height } = options;
308
+ const w = Math.max(0, width);
309
+ const h = Math.max(0, height);
310
+ const left = x - w / 2;
311
+ const top = y - h / 2;
312
+ const fitMode = getShapeFitMode(options.shapeStyle);
313
+ const heartParams = getHeartShapeParams(options.shapeStyle);
314
+ const rawHeart = createNormalizedHeartPath(heartParams);
315
+ return fitPathItemToRect(rawHeart, { left, top, width: w, height: h }, fitMode);
316
+ }
317
+
318
+ const BUILTIN_SHAPE_BUILDERS: Record<BuiltinDielineShape, BuiltinShapeBuilder> =
319
+ {
320
+ rect: (options) => {
321
+ const { x, y, width, height, radius } = options;
322
+ return new paper.Path.Rectangle({
323
+ point: [x - width / 2, y - height / 2],
324
+ size: [Math.max(0, width), Math.max(0, height)],
325
+ radius: Math.max(0, radius),
326
+ });
327
+ },
328
+ circle: (options) => {
329
+ const { x, y, width, height } = options;
330
+ const r = Math.min(width, height) / 2;
331
+ return new paper.Path.Circle({
332
+ center: new paper.Point(x, y),
333
+ radius: Math.max(0, r),
334
+ });
335
+ },
336
+ ellipse: (options) => {
337
+ const { x, y, width, height } = options;
338
+ return new paper.Path.Ellipse({
339
+ center: new paper.Point(x, y),
340
+ radius: [Math.max(0, width / 2), Math.max(0, height / 2)],
341
+ });
342
+ },
343
+ heart: createHeartBaseShape,
344
+ };
345
+
346
+ function createCustomBaseShape(options: GeometryOptions): paper.PathItem | null {
347
+ const {
348
+ pathData,
349
+ customSourceWidthPx,
350
+ customSourceHeightPx,
351
+ x,
352
+ y,
353
+ width,
354
+ height,
355
+ } = options;
356
+ if (typeof pathData !== "string" || pathData.trim().length === 0) {
357
+ return null;
358
+ }
359
+
360
+ const center = new paper.Point(x, y);
361
+ const hasMultipleSubPaths = ((pathData.match(/[Mm]/g) || []).length ?? 0) > 1;
362
+ const path: paper.PathItem = hasMultipleSubPaths
363
+ ? new paper.CompoundPath(pathData)
364
+ : (() => {
365
+ const single = new paper.Path();
366
+ single.pathData = pathData;
367
+ return single;
368
+ })();
369
+ const sourceWidth = Number(customSourceWidthPx ?? 0);
370
+ const sourceHeight = Number(customSourceHeightPx ?? 0);
371
+ if (
372
+ Number.isFinite(sourceWidth) &&
373
+ Number.isFinite(sourceHeight) &&
374
+ sourceWidth > 0 &&
375
+ sourceHeight > 0 &&
376
+ width > 0 &&
377
+ height > 0
378
+ ) {
379
+ // Preserve original detect-space offset/expand by mapping source image
380
+ // coordinates directly into the target dieline frame.
381
+ const targetLeft = x - width / 2;
382
+ const targetTop = y - height / 2;
383
+ path.scale(width / sourceWidth, height / sourceHeight, new paper.Point(0, 0));
384
+ path.translate(new paper.Point(targetLeft, targetTop));
385
+ return path;
386
+ }
387
+
388
+ if (width > 0 && height > 0 && path.bounds.width > 0 && path.bounds.height > 0) {
389
+ // Fallback for malformed custom-path metadata.
390
+ path.position = center;
391
+ path.scale(width / path.bounds.width, height / path.bounds.height);
392
+ return path;
393
+ }
394
+ path.position = center;
395
+ return path;
396
+ }
397
+
398
+ function createBaseShape(options: GeometryOptions): paper.PathItem {
399
+ const { shape } = options;
400
+ if (shape === "custom") {
401
+ const customShape = createCustomBaseShape(options);
402
+ if (customShape) return customShape;
403
+ return BUILTIN_SHAPE_BUILDERS[DEFAULT_DIELINE_SHAPE](options);
404
+ }
405
+ return BUILTIN_SHAPE_BUILDERS[shape](options);
406
+ }
407
+
408
+ function resolveBridgeBasePath(
409
+ shape: paper.PathItem,
410
+ anchor: paper.Point,
411
+ ): paper.Path | null {
412
+ if (shape instanceof paper.Path) {
413
+ return shape;
414
+ }
415
+
416
+ if (shape instanceof paper.CompoundPath) {
417
+ const children = (shape.children || []).filter(
418
+ (child): child is paper.Path => child instanceof paper.Path,
419
+ );
420
+ if (!children.length) return null;
421
+ let best = children[0];
422
+ let bestDistance = Infinity;
423
+ for (const child of children) {
424
+ const location = child.getNearestLocation(anchor);
425
+ const point = location?.point;
426
+ if (!point) continue;
427
+ const distance = point.getDistance(anchor);
428
+ if (distance < bestDistance) {
429
+ bestDistance = distance;
430
+ best = child;
431
+ }
432
+ }
433
+ return best;
434
+ }
435
+
436
+ return null;
437
+ }
438
+
439
+ /**
440
+ * Creates a Paper.js Item for a single feature.
441
+ */
442
+ function createFeatureItem(
443
+ feature: DielineFeature,
444
+ center: paper.Point,
445
+ ): paper.PathItem {
446
+ let item: paper.PathItem;
447
+
448
+ if (feature.shape === "rect") {
449
+ const w = feature.width || 10;
450
+ const h = feature.height || 10;
451
+ const r = feature.radius || 0;
452
+ item = new paper.Path.Rectangle({
453
+ point: [center.x - w / 2, center.y - h / 2],
454
+ size: [w, h],
455
+ radius: r,
456
+ });
457
+ } else {
458
+ // Circle
459
+ const r = feature.radius || 5;
460
+ item = new paper.Path.Circle({
461
+ center: center,
462
+ radius: r,
463
+ });
464
+ }
465
+
466
+ if (feature.rotation) {
467
+ item.rotate(feature.rotation, center);
468
+ }
469
+
470
+ return item;
471
+ }
472
+
473
+ /**
474
+ * Internal helper to generate the Perimeter Shape (Base + Edge Features).
475
+ */
476
+ function getPerimeterShape(options: GeometryOptions): paper.PathItem {
477
+ // 1. Create Base Shape
478
+ let mainShape = createBaseShape(options);
479
+
480
+ const { features } = options;
481
+
482
+ if (features && features.length > 0) {
483
+ // Filter for Edge Features (Default is Edge, unless explicit 'surface')
484
+ const edgeFeatures = features.filter(
485
+ (f) => !f.renderBehavior || f.renderBehavior === "edge",
486
+ );
487
+
488
+ const adds: paper.PathItem[] = [];
489
+ const subtracts: paper.PathItem[] = [];
490
+
491
+ edgeFeatures.forEach((f) => {
492
+ const pos = resolveFeaturePosition(f, options);
493
+ const center = new paper.Point(pos.x, pos.y);
494
+ const item = createFeatureItem(f, center);
495
+
496
+ // Handle Bridge logic: Create a connection shape to the main body
497
+ if (f.bridge && f.bridge.type === "vertical") {
498
+ const itemBounds = item.bounds;
499
+ const mainBounds = mainShape.bounds;
500
+ const bridgeTop = mainBounds.top;
501
+ const bridgeBottom = itemBounds.top;
502
+
503
+ if (bridgeBottom > bridgeTop) {
504
+ const overlap = 2;
505
+ const rayPadding = 10;
506
+ const eps = 0.1;
507
+ const delta = getBridgeDelta(itemBounds, overlap);
508
+
509
+ const toY = bridgeTop - rayPadding;
510
+ const inset = Math.min(1, Math.max(0, itemBounds.width * 0.01));
511
+ const xLeft = itemBounds.left + inset;
512
+ const xRight = itemBounds.right - inset;
513
+ const bridgeBasePath = resolveBridgeBasePath(mainShape, center);
514
+ const canBridge = !!bridgeBasePath && xRight - xLeft > eps;
515
+
516
+ if (canBridge && bridgeBasePath) {
517
+ const leftHit = getExitHit({
518
+ mainShape: bridgeBasePath,
519
+ x: xLeft,
520
+ bridgeBottom,
521
+ toY,
522
+ eps,
523
+ delta,
524
+ overlap,
525
+ op: f.operation,
526
+ });
527
+ const rightHit = getExitHit({
528
+ mainShape: bridgeBasePath,
529
+ x: xRight,
530
+ bridgeBottom,
531
+ toY,
532
+ eps,
533
+ delta,
534
+ overlap,
535
+ op: f.operation,
536
+ });
537
+
538
+ if (leftHit && rightHit) {
539
+ const pathLength = bridgeBasePath.length;
540
+ const leftOffset = leftHit.location.offset;
541
+ const rightOffset = rightHit.location.offset;
542
+
543
+ const distanceA = wrappedDistance(pathLength, leftOffset, rightOffset);
544
+ const distanceB = wrappedDistance(pathLength, rightOffset, leftOffset);
545
+ const countFor = (d: number) =>
546
+ Math.max(8, Math.min(80, Math.ceil(d / 6)));
547
+
548
+ const offsetsA = sampleWrappedOffsets(
549
+ pathLength,
550
+ leftOffset,
551
+ rightOffset,
552
+ countFor(distanceA),
553
+ );
554
+
555
+ const offsetsB = sampleWrappedOffsets(
556
+ pathLength,
557
+ rightOffset,
558
+ leftOffset,
559
+ countFor(distanceB),
560
+ );
561
+
562
+ const pointsA = offsetsA
563
+ .map((o) => bridgeBasePath.getPointAt(o))
564
+ .filter((p): p is paper.Point => Boolean(p));
565
+ const pointsB = offsetsB
566
+ .map((o) => bridgeBasePath.getPointAt(o))
567
+ .filter((p): p is paper.Point => Boolean(p));
568
+
569
+ if (pointsA.length >= 2 && pointsB.length >= 2) {
570
+ let topBase = selectOuterChain({
571
+ mainShape: bridgeBasePath,
572
+ pointsA,
573
+ pointsB,
574
+ delta,
575
+ overlap,
576
+ op: f.operation,
577
+ });
578
+
579
+ const dist2 = (a: paper.Point, b: paper.Point) => {
580
+ const dx = a.x - b.x;
581
+ const dy = a.y - b.y;
582
+ return dx * dx + dy * dy;
583
+ };
584
+
585
+ if (
586
+ dist2(topBase[0], leftHit.point) >
587
+ dist2(topBase[0], rightHit.point)
588
+ ) {
589
+ topBase = topBase.slice().reverse();
590
+ }
591
+
592
+ topBase = topBase.slice();
593
+ topBase[0] = leftHit.point;
594
+ topBase[topBase.length - 1] = rightHit.point;
595
+
596
+ const capShiftY =
597
+ f.operation === "subtract"
598
+ ? -Math.max(overlap * 2, delta)
599
+ : overlap;
600
+ const topPoints = topBase.map((p) =>
601
+ p.add(new paper.Point(0, capShiftY)),
602
+ );
603
+
604
+ const bridgeBottomY = bridgeBottom + overlap * 2;
605
+ const bridgePoly = new paper.Path({ insert: false });
606
+ for (const p of topPoints) bridgePoly.add(p);
607
+ bridgePoly.add(new paper.Point(xRight, bridgeBottomY));
608
+ bridgePoly.add(new paper.Point(xLeft, bridgeBottomY));
609
+ bridgePoly.closed = true;
610
+
611
+ const unitedItem = item.unite(bridgePoly);
612
+ item.remove();
613
+ bridgePoly.remove();
614
+
615
+ if (f.operation === "add") {
616
+ adds.push(unitedItem);
617
+ } else {
618
+ subtracts.push(unitedItem);
619
+ }
620
+ return;
621
+ }
622
+ }
623
+ }
624
+
625
+ if (f.operation === "add") {
626
+ adds.push(item);
627
+ } else {
628
+ subtracts.push(item);
629
+ }
630
+ } else {
631
+ if (f.operation === "add") {
632
+ adds.push(item);
633
+ } else {
634
+ subtracts.push(item);
635
+ }
636
+ }
637
+ } else {
638
+ if (f.operation === "add") {
639
+ adds.push(item);
640
+ } else {
641
+ subtracts.push(item);
642
+ }
643
+ }
644
+ });
645
+
646
+ // 2. Process Additions (Union)
647
+ if (adds.length > 0) {
648
+ for (const item of adds) {
649
+ try {
650
+ const temp = mainShape.unite(item);
651
+ mainShape.remove();
652
+ item.remove();
653
+ mainShape = normalizePathItem(temp);
654
+ } catch (e) {
655
+ console.error("Geometry: Failed to unite feature", e);
656
+ item.remove();
657
+ }
658
+ }
659
+ }
660
+
661
+ // 3. Process Subtractions (Difference)
662
+ if (subtracts.length > 0) {
663
+ for (const item of subtracts) {
664
+ try {
665
+ const temp = mainShape.subtract(item);
666
+ mainShape.remove();
667
+ item.remove();
668
+ mainShape = normalizePathItem(temp);
669
+ } catch (e) {
670
+ console.error("Geometry: Failed to subtract feature", e);
671
+ item.remove();
672
+ }
673
+ }
674
+ }
675
+ }
676
+
677
+ return mainShape;
678
+ }
679
+
680
+ /**
681
+ * Applies Internal/Surface features to a shape.
682
+ */
683
+ function applySurfaceFeatures(
684
+ shape: paper.PathItem,
685
+ features: DielineFeature[],
686
+ options: GeometryOptions,
687
+ ): paper.PathItem {
688
+ const surfaceFeatures = features.filter(
689
+ (f) => f.renderBehavior === "surface",
690
+ );
691
+
692
+ if (surfaceFeatures.length === 0) return shape;
693
+
694
+ let result = shape;
695
+
696
+ // Internal features are usually subtractive (holes)
697
+ // But we support 'add' too (islands? maybe just unite)
698
+
699
+ for (const f of surfaceFeatures) {
700
+ const pos = resolveFeaturePosition(f, options);
701
+ const center = new paper.Point(pos.x, pos.y);
702
+ const item = createFeatureItem(f, center);
703
+
704
+ try {
705
+ if (f.operation === "add") {
706
+ const temp = result.unite(item);
707
+ result.remove();
708
+ item.remove();
709
+ result = normalizePathItem(temp);
710
+ } else {
711
+ const temp = result.subtract(item);
712
+ result.remove();
713
+ item.remove();
714
+ result = normalizePathItem(temp);
715
+ }
716
+ } catch (e) {
717
+ console.error("Geometry: Failed to apply surface feature", e);
718
+ item.remove();
719
+ }
720
+ }
721
+
722
+ return result;
723
+ }
724
+
725
+ /**
726
+ * Generates the path data for the Dieline (Product Shape).
727
+ */
728
+ export function generateDielinePath(options: GeometryOptions): string {
729
+ const paperWidth = options.canvasWidth || options.width * 2 || 2000;
730
+ const paperHeight = options.canvasHeight || options.height * 2 || 2000;
731
+ ensurePaper(paperWidth, paperHeight);
732
+ paper.project.activeLayer.removeChildren();
733
+
734
+ const perimeter = getPerimeterShape(options);
735
+ const finalShape = applySurfaceFeatures(perimeter, options.features, options);
736
+
737
+ const pathData = finalShape.pathData;
738
+ finalShape.remove();
739
+
740
+ return pathData;
741
+ }
742
+
743
+ /**
744
+ * Generates the path data for the Mask (Background Overlay).
745
+ * Logic: Canvas SUBTRACT ProductShape
746
+ */
747
+ export function generateMaskPath(options: MaskGeometryOptions): string {
748
+ ensurePaper(options.canvasWidth, options.canvasHeight);
749
+ paper.project.activeLayer.removeChildren();
750
+
751
+ const { canvasWidth, canvasHeight } = options;
752
+
753
+ const maskRect = new paper.Path.Rectangle({
754
+ point: [0, 0],
755
+ size: [canvasWidth, canvasHeight],
756
+ });
757
+
758
+ const perimeter = getPerimeterShape(options);
759
+ const mainShape = applySurfaceFeatures(perimeter, options.features, options);
760
+
761
+ const finalMask = maskRect.subtract(mainShape);
762
+
763
+ maskRect.remove();
764
+ mainShape.remove();
765
+
766
+ const pathData = finalMask.pathData;
767
+ finalMask.remove();
768
+
769
+ return pathData;
770
+ }
771
+
772
+ /**
773
+ * Generates the path data for the Bleed Zone.
774
+ */
775
+ export function generateBleedZonePath(
776
+ originalOptions: GeometryOptions,
777
+ offsetOptions: GeometryOptions,
778
+ offset: number,
779
+ ): string {
780
+ const paperWidth =
781
+ originalOptions.canvasWidth || originalOptions.width * 2 || 2000;
782
+ const paperHeight =
783
+ originalOptions.canvasHeight || originalOptions.height * 2 || 2000;
784
+ ensurePaper(paperWidth, paperHeight);
785
+ paper.project.activeLayer.removeChildren();
786
+
787
+ // 1. Generate Original Shape
788
+ const pOriginal = getPerimeterShape(originalOptions);
789
+ const shapeOriginal = applySurfaceFeatures(
790
+ pOriginal,
791
+ originalOptions.features,
792
+ originalOptions,
793
+ );
794
+
795
+ // 2. Generate Offset Shape
796
+ const pOffset = getPerimeterShape(offsetOptions);
797
+ const shapeOffset = applySurfaceFeatures(
798
+ pOffset,
799
+ offsetOptions.features,
800
+ offsetOptions,
801
+ );
802
+
803
+ // 3. Calculate Difference
804
+ let bleedZone: paper.PathItem;
805
+ if (offset > 0) {
806
+ bleedZone = shapeOffset.subtract(shapeOriginal);
807
+ } else {
808
+ bleedZone = shapeOriginal.subtract(shapeOffset);
809
+ }
810
+
811
+ const pathData = bleedZone.pathData;
812
+
813
+ shapeOriginal.remove();
814
+ shapeOffset.remove();
815
+ bleedZone.remove();
816
+
817
+ return pathData;
818
+ }
819
+
820
+ /**
821
+ * Finds the lowest point (Max Y) on the Dieline geometry (Base Shape ONLY).
822
+ */
823
+ export function getLowestPointOnDieline(
824
+ options: GeometryOptions,
825
+ ): { x: number; y: number } {
826
+ ensurePaper(options.width * 2, options.height * 2);
827
+ paper.project.activeLayer.removeChildren();
828
+
829
+ const shape = createBaseShape(options);
830
+ const bounds = shape.bounds;
831
+
832
+ const result = {
833
+ x: bounds.center.x,
834
+ y: bounds.bottom,
835
+ };
836
+ shape.remove();
837
+
838
+ return result;
839
+ }
840
+
841
+ /**
842
+ * Finds the nearest point on the Dieline geometry (Base Shape ONLY) for a given target point.
843
+ * Used for constraining feature movement.
844
+ */
845
+ export function getNearestPointOnDieline(
846
+ point: { x: number; y: number },
847
+ options: GeometryOptions,
848
+ ): { x: number; y: number; normal?: { x: number; y: number } } {
849
+ ensurePaper(options.width * 2, options.height * 2);
850
+ paper.project.activeLayer.removeChildren();
851
+
852
+ // We constrain to the BASE shape, not including other features,
853
+ // because usually you want to snap to the main edge.
854
+ const shape = createBaseShape(options);
855
+
856
+ const p = new paper.Point(point.x, point.y);
857
+ const location = shape.getNearestLocation(p);
858
+
859
+ const result = {
860
+ x: location.point.x,
861
+ y: location.point.y,
862
+ normal: location.normal ? { x: location.normal.x, y: location.normal.y } : undefined
863
+ };
864
+ shape.remove();
865
+
866
+ return result;
867
+ }
868
+
869
+ export function getPathBounds(pathData: string): {
870
+ x: number;
871
+ y: number;
872
+ width: number;
873
+ height: number;
874
+ } {
875
+ const path = new paper.Path();
876
+ path.pathData = pathData;
877
+ const bounds = path.bounds;
878
+ path.remove();
879
+ return {
880
+ x: bounds.x,
881
+ y: bounds.y,
882
+ width: bounds.width,
883
+ height: bounds.height,
884
+ };
885
+ }