topotopo 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/NOTICE +30 -0
  2. package/README.md +54 -16
  3. package/dist/cli.js +95 -14
  4. package/dist/core/analysis.d.ts +5 -1
  5. package/dist/core/analysis.js +8 -3
  6. package/dist/core/bake.d.ts +2 -5
  7. package/dist/core/bake.js +12 -25
  8. package/dist/core/bevel.js +165 -97
  9. package/dist/core/geometry.js +1 -1
  10. package/dist/core/imageops.d.ts +6 -0
  11. package/dist/core/imageops.js +51 -0
  12. package/dist/core/materials.d.ts +4 -0
  13. package/dist/core/materials.js +11 -0
  14. package/dist/core/packed.js +11 -0
  15. package/dist/core/particles.d.ts +1 -1
  16. package/dist/core/particles.js +1 -1
  17. package/dist/core/rbd.js +13 -1
  18. package/dist/core/scatter.d.ts +1 -1
  19. package/dist/core/scatter.js +1 -1
  20. package/dist/core/scene.d.ts +20 -0
  21. package/dist/core/scene.js +71 -0
  22. package/dist/core/snippet-lib.d.ts +1 -1
  23. package/dist/core/snippet-lib.js +1 -1
  24. package/dist/core/solidify.d.ts +38 -0
  25. package/dist/core/solidify.js +356 -0
  26. package/dist/core/tangents.d.ts +52 -0
  27. package/dist/core/tangents.js +214 -0
  28. package/dist/core/texcoord.d.ts +4 -0
  29. package/dist/core/texcoord.js +14 -0
  30. package/dist/core/topology.d.ts +22 -0
  31. package/dist/core/topology.js +70 -7
  32. package/dist/core/traceimage.d.ts +7 -0
  33. package/dist/core/traceimage.js +221 -0
  34. package/dist/core/tritri.d.ts +5 -0
  35. package/dist/core/tritri.js +120 -0
  36. package/dist/core/uv.d.ts +13 -0
  37. package/dist/core/uv.js +3 -3
  38. package/dist/core/uvreport.d.ts +66 -0
  39. package/dist/core/uvreport.js +308 -0
  40. package/dist/core/xatlas.js +32 -2
  41. package/dist/gallery/app/gallery.css +100 -0
  42. package/dist/gallery/app/gallery.js +80 -0
  43. package/dist/gallery/bake.d.ts +34 -0
  44. package/dist/gallery/bake.js +144 -0
  45. package/dist/gallery/cli.d.ts +4 -0
  46. package/dist/gallery/cli.js +157 -0
  47. package/dist/gallery/library.d.ts +124 -0
  48. package/dist/gallery/library.js +366 -0
  49. package/dist/gallery/pages.d.ts +94 -0
  50. package/dist/gallery/pages.js +148 -0
  51. package/dist/gallery/server.d.ts +21 -0
  52. package/dist/gallery/server.js +391 -0
  53. package/dist/graph/engine.js +14 -0
  54. package/dist/graph/types.d.ts +17 -0
  55. package/dist/host/artifacts.d.ts +21 -0
  56. package/dist/host/artifacts.js +58 -0
  57. package/dist/host/export-targets.d.ts +33 -0
  58. package/dist/host/export-targets.js +84 -0
  59. package/dist/index.d.ts +3 -1
  60. package/dist/index.js +2 -1
  61. package/dist/inspect.d.ts +6 -1
  62. package/dist/inspect.js +13 -1
  63. package/dist/io/common.d.ts +8 -0
  64. package/dist/io/gltf.js +236 -19
  65. package/dist/io/targets.d.ts +31 -0
  66. package/dist/io/targets.js +75 -0
  67. package/dist/mcp/docs.d.ts +1 -1
  68. package/dist/mcp/docs.js +73 -6
  69. package/dist/mcp/library.d.ts +12 -0
  70. package/dist/mcp/library.js +159 -0
  71. package/dist/mcp/server.js +29 -12
  72. package/dist/mcp/tools.d.ts +1 -1
  73. package/dist/mcp/tools.js +102 -43
  74. package/dist/nodes/bake.js +56 -36
  75. package/dist/nodes/bevel.js +4 -3
  76. package/dist/nodes/code.js +33 -7
  77. package/dist/nodes/curves.js +7 -0
  78. package/dist/nodes/generate.js +1 -1
  79. package/dist/nodes/imageops.d.ts +1 -0
  80. package/dist/nodes/imageops.js +206 -0
  81. package/dist/nodes/index.d.ts +3 -0
  82. package/dist/nodes/index.js +3 -0
  83. package/dist/nodes/material.js +3 -0
  84. package/dist/nodes/measure.js +3 -2
  85. package/dist/nodes/rbd.js +1 -1
  86. package/dist/nodes/scene.d.ts +1 -0
  87. package/dist/nodes/scene.js +53 -0
  88. package/dist/nodes/solidify.d.ts +1 -0
  89. package/dist/nodes/solidify.js +52 -0
  90. package/dist/nodes/transform.js +5 -1
  91. package/dist/nodes/util.d.ts +1 -1
  92. package/dist/nodes/wasmcall.js +1 -1
  93. package/dist/render/options.js +1 -1
  94. package/dist/render/pbr.d.ts +28 -0
  95. package/dist/render/pbr.js +378 -0
  96. package/dist/render/preview.d.ts +58 -0
  97. package/dist/render/preview.js +24 -0
  98. package/dist/render/raster.d.ts +12 -2
  99. package/dist/render/raster.js +98 -11
  100. package/dist/render/texview.d.ts +1 -1
  101. package/dist/render/texview.js +7 -2
  102. package/dist/viewer/app/camera.js +27 -7
  103. package/dist/viewer/app/embed.js +80 -0
  104. package/dist/viewer/app/export-popover.js +68 -0
  105. package/dist/viewer/app/grid.js +1 -1
  106. package/dist/viewer/app/guides.js +1 -1
  107. package/dist/viewer/app/image-view.js +114 -0
  108. package/dist/viewer/app/keymap.js +15 -3
  109. package/dist/viewer/app/layers.js +24 -5
  110. package/dist/viewer/app/main.js +71 -15
  111. package/dist/viewer/app/markers.js +1 -1
  112. package/dist/viewer/app/outliner.js +56 -15
  113. package/dist/viewer/app/outputs.css +73 -0
  114. package/dist/viewer/app/outputs.js +240 -0
  115. package/dist/viewer/app/props.js +1 -1
  116. package/dist/viewer/app/scene.js +6 -2
  117. package/dist/viewer/app/select.js +14 -3
  118. package/dist/viewer/app/selection.js +1 -1
  119. package/dist/viewer/app/status.js +20 -0
  120. package/dist/viewer/app/style.css +2 -1
  121. package/dist/viewer/app/units.js +1 -1
  122. package/dist/viewer/app/vars.js +1 -1
  123. package/dist/viewer/index.html +20 -6
  124. package/dist/viewer/outputs.d.ts +54 -0
  125. package/dist/viewer/outputs.js +436 -0
  126. package/dist/viewer/server.d.ts +19 -2
  127. package/dist/viewer/server.js +77 -9
  128. package/dist/workspace.d.ts +21 -2
  129. package/dist/workspace.js +124 -4
  130. package/kernels/pkg/README.md +21 -28
  131. package/kernels/pkg-simd/README.md +21 -28
  132. package/package.json +11 -4
@@ -0,0 +1,14 @@
1
+ // Texture coordinate conventions, in one place.
2
+ //
3
+ // TopoTopo (like Houdini and OpenGL): v points up. uv (0, 0) is the bottom-left of an image and (0, 1) its top-left;
4
+ // image row 0 (the first row in memory and in a PNG) is the top, at v = 1.
5
+ // glTF TEXCOORD_n: v points down. (0, 0) is the top-left of the image, so glTF v = 1 - TopoTopo v.
6
+ //
7
+ // Tangent space follows from this. TopoTopo's tangent is dP/du and its bitangent dP/dv points towards image "up",
8
+ // which is the green-up (OpenGL) normal map convention glTF uses. MikkTSpace fed TopoTopo uvs therefore returns the
9
+ // handedness glTF expects (bitangent = w · cross(N, T)) without the sign flip a v-down caller (three.js reading glTF
10
+ // uvs) applies.
11
+ /** TopoTopo v ↔ glTF v (the mapping is its own inverse). */
12
+ export const gltfV = (v) => 1 - v;
13
+ /** Continuous image row coordinate (0 = top edge of row 0, h = bottom edge of the last row) of TopoTopo v. */
14
+ export const imageRowOfV = (v, h) => (1 - v) * h;
@@ -93,3 +93,25 @@ export declare function topologyReport(g: Geometry): {
93
93
  closed: boolean;
94
94
  euler: number;
95
95
  };
96
+ /** Triangle shape quality q = 4√3·area / Σ edge² (1 for equilateral, 0 for collinear corners). */
97
+ export declare const TRI_DEGENERATE_QUALITY = 1e-9;
98
+ export declare const TRI_NEAR_DEGENERATE_QUALITY = 0.0001;
99
+ export interface TriangleReport {
100
+ triangles: number;
101
+ /** Smallest triangle area (Infinity when there are no triangles). */
102
+ minArea: number;
103
+ /** Smallest shape quality q (see TRI_DEGENERATE_QUALITY). */
104
+ minQuality: number;
105
+ /** Triangles with zero area or q below TRI_DEGENERATE_QUALITY (collinear corners within rounding). */
106
+ degenerate: number;
107
+ /** Slivers with q below TRI_NEAR_DEGENERATE_QUALITY that are not degenerate. */
108
+ nearDegenerate: number;
109
+ /** Source polygons of the degenerate / near-degenerate triangles, ascending, at most `limit` each. */
110
+ degeneratePrims: number[];
111
+ nearDegeneratePrims: number[];
112
+ }
113
+ /**
114
+ * Health of the triangles that export, rendering and baking actually use (the same triangulate()
115
+ * split), which polygon-level checks can miss: a non-degenerate quad can still split into a sliver.
116
+ */
117
+ export declare function triangleReport(g: Geometry, tri?: Triangulation, limit?: number): TriangleReport;
@@ -403,6 +403,12 @@ export function boundaryLoops(g) {
403
403
  }
404
404
  return loops;
405
405
  }
406
+ /**
407
+ * A quad diagonal is numerically healthy when each of its two triangles covers more than this
408
+ * fraction of the polygon's area. Collinear corners leave one triangle at ~1e-16 of the area
409
+ * (pure rounding); any real split, however thin, is far above it.
410
+ */
411
+ const QUAD_SPLIT_REL_AREA = 1e-9;
406
412
  /** Triangulate closed polygons. Fans for convex quads/tris, earcut otherwise. Output winding follows the polygon. */
407
413
  export function triangulate(g, primMask) {
408
414
  const P = g.P, vp = g.vertexPoint;
@@ -428,9 +434,16 @@ export function triangulate(g, primMask) {
428
434
  }
429
435
  primNewell(g, p, nrm);
430
436
  if (n === 4) {
431
- // pick the diagonal that keeps both triangles facing the polygon normal
432
- const ok02 = triN(s, s + 1, s + 2) > 0 && triN(s, s + 2, s + 3) > 0;
433
- if (ok02 || !(triN(s + 1, s + 2, s + 3) > 0 && triN(s + 1, s + 3, s) > 0)) {
437
+ // Pick the diagonal that keeps both triangles facing the polygon normal. A diagonal whose
438
+ // triangles both hold a healthy share of the polygon's area wins first, so a quad with
439
+ // (nearly) collinear corners never yields a zero-area sliver when the other diagonal is fine.
440
+ // triN is 2·area_tri·|nrm| for planar quads and |nrm|² = 4·area_poly², so the ratio is scale-free.
441
+ const t0 = triN(s, s + 1, s + 2), t1 = triN(s, s + 2, s + 3);
442
+ const t2 = triN(s + 1, s + 2, s + 3), t3 = triN(s + 1, s + 3, s);
443
+ const tol = QUAD_SPLIT_REL_AREA * (nrm[0] * nrm[0] + nrm[1] * nrm[1] + nrm[2] * nrm[2]);
444
+ const ok02 = t0 > 0 && t1 > 0, ok13 = t2 > 0 && t3 > 0;
445
+ const healthy02 = t0 > tol && t1 > tol, healthy13 = t2 > tol && t3 > tol;
446
+ if (healthy02 || (!healthy13 && (ok02 || !ok13))) {
434
447
  tris.push(s, s + 1, s + 2, s, s + 2, s + 3);
435
448
  }
436
449
  else
@@ -454,11 +467,23 @@ export function triangulate(g, primMask) {
454
467
  }
455
468
  continue;
456
469
  }
470
+ // earcut's triangles share one orientation in the projection plane: flip them all or none so they
471
+ // follow the polygon's winding. (A per-triangle 3D test would flip single triangles of a strongly
472
+ // non-planar polygon and fold the surface.)
473
+ let poly2 = 0, tri2 = 0;
474
+ for (let k = 0, j = n - 1; k < n; j = k++)
475
+ poly2 += flat[j * 2] * flat[k * 2 + 1] - flat[k * 2] * flat[j * 2 + 1];
476
+ for (let k = 0; k < idx.length; k += 3) {
477
+ const a = idx[k] * 2, b = idx[k + 1] * 2, c = idx[k + 2] * 2;
478
+ tri2 += (flat[b] - flat[a]) * (flat[c + 1] - flat[a + 1]) - (flat[c] - flat[a]) * (flat[b + 1] - flat[a + 1]);
479
+ }
480
+ const flip = poly2 * tri2 < 0;
457
481
  for (let k = 0; k < idx.length; k += 3) {
458
- let a = s + idx[k], b = s + idx[k + 1], c = s + idx[k + 2];
459
- if (triN(a, b, c) < 0)
460
- [b, c] = [c, b];
461
- tris.push(a, b, c);
482
+ const a = s + idx[k], b = s + idx[k + 1], c = s + idx[k + 2];
483
+ if (flip)
484
+ tris.push(a, c, b);
485
+ else
486
+ tris.push(a, b, c);
462
487
  tp.push(p);
463
488
  }
464
489
  }
@@ -590,3 +615,41 @@ export function topologyReport(g) {
590
615
  closed, euler: V - Ecount + F,
591
616
  };
592
617
  }
618
+ /** Triangle shape quality q = 4√3·area / Σ edge² (1 for equilateral, 0 for collinear corners). */
619
+ export const TRI_DEGENERATE_QUALITY = 1e-9;
620
+ export const TRI_NEAR_DEGENERATE_QUALITY = 1e-4;
621
+ /**
622
+ * Health of the triangles that export, rendering and baking actually use (the same triangulate()
623
+ * split), which polygon-level checks can miss: a non-degenerate quad can still split into a sliver.
624
+ */
625
+ export function triangleReport(g, tri = triangulate(g), limit = 32) {
626
+ const P = g.P, vp = g.vertexPoint, { tris, triPrim } = tri;
627
+ let minArea = Infinity, minQuality = Infinity, degenerate = 0, nearDegenerate = 0;
628
+ const dp = new Set(), np = new Set();
629
+ for (let t = 0; t < tris.length; t += 3) {
630
+ const a = vp[tris[t]] * 3, b = vp[tris[t + 1]] * 3, c = vp[tris[t + 2]] * 3;
631
+ const ux = P[b] - P[a], uy = P[b + 1] - P[a + 1], uz = P[b + 2] - P[a + 2];
632
+ const wx = P[c] - P[a], wy = P[c + 1] - P[a + 1], wz = P[c + 2] - P[a + 2];
633
+ const vx = P[c] - P[b], vy = P[c + 1] - P[b + 1], vz = P[c + 2] - P[b + 2];
634
+ const area = 0.5 * Math.hypot(uy * wz - uz * wy, uz * wx - ux * wz, ux * wy - uy * wx);
635
+ const e2 = ux * ux + uy * uy + uz * uz + wx * wx + wy * wy + wz * wz + vx * vx + vy * vy + vz * vz;
636
+ const q = e2 > 0 ? (4 * Math.sqrt(3) * area) / e2 : 0;
637
+ if (area < minArea)
638
+ minArea = area;
639
+ if (q < minQuality)
640
+ minQuality = q;
641
+ if (area === 0 || q < TRI_DEGENERATE_QUALITY) {
642
+ degenerate++;
643
+ dp.add(triPrim[t / 3]);
644
+ }
645
+ else if (q < TRI_NEAR_DEGENERATE_QUALITY) {
646
+ nearDegenerate++;
647
+ np.add(triPrim[t / 3]);
648
+ }
649
+ }
650
+ const ids = (s) => [...s].sort((x, y) => x - y).slice(0, limit);
651
+ return {
652
+ triangles: tris.length / 3, minArea, minQuality: tris.length ? minQuality : Infinity, degenerate, nearDegenerate,
653
+ degeneratePrims: ids(dp), nearDegeneratePrims: ids(np),
654
+ };
655
+ }
@@ -0,0 +1,7 @@
1
+ export type PixelPoint = [number, number];
2
+ export interface ImageContour {
3
+ points: PixelPoint[];
4
+ component: number;
5
+ hole: boolean;
6
+ }
7
+ export declare function traceMask(mask: Float32Array, w: number, h: number, threshold: number, minArea: number, tolerance: number): ImageContour[];
@@ -0,0 +1,221 @@
1
+ const MAX_EDGES = 1_000_000;
2
+ const cross = (a, b, c) => (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
3
+ function area(p) {
4
+ let a = 0;
5
+ for (let i = 0; i < p.length; i++) {
6
+ const q = p[(i + 1) % p.length];
7
+ a += p[i][0] * q[1] - q[0] * p[i][1];
8
+ }
9
+ return a / 2;
10
+ }
11
+ function collinear(p) {
12
+ return p.filter((v, i) => cross(p[(i + p.length - 1) % p.length], v, p[(i + 1) % p.length]) !== 0);
13
+ }
14
+ export function traceMask(mask, w, h, threshold, minArea, tolerance) {
15
+ const n = w * h, labels = new Int32Array(n), queue = new Int32Array(n), counts = [];
16
+ // Stable row-major component numbering and linear-time flood fill.
17
+ for (let s = 0; s < n; s++) {
18
+ if (labels[s] || !(mask[s] >= threshold))
19
+ continue;
20
+ const id = counts.length + 1;
21
+ let head = 0, tail = 1;
22
+ queue[0] = s;
23
+ labels[s] = id;
24
+ const visit = (k) => { if (!labels[k] && mask[k] >= threshold) {
25
+ labels[k] = id;
26
+ queue[tail++] = k;
27
+ } };
28
+ while (head < tail) {
29
+ const k = queue[head++], x = k % w;
30
+ if (x > 0)
31
+ visit(k - 1);
32
+ if (x + 1 < w)
33
+ visit(k + 1);
34
+ if (k >= w)
35
+ visit(k - w);
36
+ if (k + w < n)
37
+ visit(k + w);
38
+ }
39
+ counts.push(tail);
40
+ }
41
+ const inside = (x, y) => x >= 0 && x < w && y >= 0 && y < h && labels[y * w + x] > 0 && counts[labels[y * w + x] - 1] >= minArea;
42
+ const seen = new Uint8Array(n), out = [];
43
+ let edges = 0;
44
+ // Edge directions: right, down, left, up; foreground is always to the right.
45
+ const dx = [1, 0, -1, 0], dy = [0, 1, 0, -1];
46
+ const boundary = (x, y, d) => inside(x, y) && !inside(x + (d === 1 ? 1 : d === 3 ? -1 : 0), y + (d === 2 ? 1 : d === 0 ? -1 : 0));
47
+ const edgeAt = (x, y, d) => [x - (d === 1 || d === 2 ? 1 : 0), y - (d === 2 || d === 3 ? 1 : 0)];
48
+ for (let y = 0; y < h; y++)
49
+ for (let x = 0; x < w; x++) {
50
+ if (!inside(x, y))
51
+ continue;
52
+ for (let d = 0; d < 4; d++) {
53
+ if ((seen[y * w + x] & (1 << d)) || !boundary(x, y, d))
54
+ continue;
55
+ const start = (y * w + x) * 4 + d, points = [];
56
+ let px = x, py = y, dir = d;
57
+ let vx = x + (d === 1 || d === 2 ? 1 : 0), vy = y + (d === 2 || d === 3 ? 1 : 0);
58
+ do {
59
+ if (++edges > MAX_EDGES)
60
+ throw new Error('trace_image: more than 1,000,000 boundary edges; crop the image, lower its resolution, or increase min_area');
61
+ seen[py * w + px] |= 1 << dir;
62
+ points.push([vx, vy]);
63
+ vx += dx[dir];
64
+ vy += dy[dir];
65
+ let found = false;
66
+ for (const turn of [1, 0, 3, 2]) {
67
+ const nd = (dir + turn) % 4, [nx, ny] = edgeAt(vx, vy, nd);
68
+ if (!boundary(nx, ny, nd))
69
+ continue;
70
+ px = nx;
71
+ py = ny;
72
+ dir = nd;
73
+ found = true;
74
+ break;
75
+ }
76
+ if (!found)
77
+ throw new Error('trace_image: open boundary');
78
+ } while ((py * w + px) * 4 + dir !== start);
79
+ const clean = collinear(points);
80
+ if (clean.length >= 3)
81
+ out.push({ points: clean, component: labels[y * w + x] - 1, hole: area(clean) < 0 });
82
+ }
83
+ }
84
+ if (tolerance > 0)
85
+ simplifyContours(out, tolerance);
86
+ return out;
87
+ }
88
+ function dist2(p, a, b) {
89
+ const x = b[0] - a[0], y = b[1] - a[1], len = x * x + y * y;
90
+ const t = len ? Math.max(0, Math.min(1, ((p[0] - a[0]) * x + (p[1] - a[1]) * y) / len)) : 0;
91
+ return (p[0] - a[0] - t * x) ** 2 + (p[1] - a[1] - t * y) ** 2;
92
+ }
93
+ function inTriangle(p, a, b, c) {
94
+ const x = cross(a, b, p), y = cross(b, c, p), z = cross(c, a, p);
95
+ return (x >= 0 && y >= 0 && z >= 0) || (x <= 0 && y <= 0 && z <= 0);
96
+ }
97
+ function intersects(a, b, c, d) {
98
+ return Math.max(a[0], b[0]) >= Math.min(c[0], d[0]) && Math.max(c[0], d[0]) >= Math.min(a[0], b[0]) &&
99
+ Math.max(a[1], b[1]) >= Math.min(c[1], d[1]) && Math.max(c[1], d[1]) >= Math.min(a[1], b[1]) &&
100
+ cross(a, b, c) * cross(a, b, d) <= 0 && cross(c, d, a) * cross(c, d, b) <= 0;
101
+ }
102
+ /** Spatially indexed conservative vertex removal; never collapses a hole or joins two components. */
103
+ function simplifyContours(loops, tolerance) {
104
+ const verts = [], counts = loops.map((l) => l.points.length), first = [];
105
+ for (let l = 0; l < loops.length; l++) {
106
+ const points = loops[l].points, start = verts.length;
107
+ first.push(start);
108
+ points.forEach((p, i) => verts.push({ p, prev: start + (i + points.length - 1) % points.length, next: start + (i + 1) % points.length, loop: l, active: true, span: [p] }));
109
+ }
110
+ // Index edges by bounding boxes. Existing long straight boundaries are cheap (one cell wide).
111
+ const cell = 16, bins = new Map();
112
+ const keys = (a, b, c) => {
113
+ const minx = Math.floor(Math.min(a[0], b[0], c?.[0] ?? a[0]) / cell), maxx = Math.floor(Math.max(a[0], b[0], c?.[0] ?? a[0]) / cell);
114
+ const miny = Math.floor(Math.min(a[1], b[1], c?.[1] ?? a[1]) / cell), maxy = Math.floor(Math.max(a[1], b[1], c?.[1] ?? a[1]) / cell);
115
+ const result = [];
116
+ for (let y = miny; y <= maxy; y++)
117
+ for (let x = minx; x <= maxx; x++)
118
+ result.push(x + ',' + y);
119
+ return result;
120
+ };
121
+ const index = (i, add) => {
122
+ for (const k of keys(verts[i].p, verts[verts[i].next].p)) {
123
+ if (add) {
124
+ let s = bins.get(k);
125
+ if (!s)
126
+ bins.set(k, s = new Set());
127
+ s.add(i);
128
+ }
129
+ else {
130
+ const s = bins.get(k);
131
+ s?.delete(i);
132
+ if (!s?.size)
133
+ bins.delete(k);
134
+ }
135
+ }
136
+ };
137
+ verts.forEach((_, i) => index(i, true));
138
+ // Pixel masks can have zero-width contacts (including repeated vertices within one
139
+ // outline). Keep the participating components exact: changing even the ordering of
140
+ // their wedges can change how a downstream polygon fill resolves such pinches.
141
+ const fixedComponents = new Set();
142
+ verts.forEach((v, i) => {
143
+ for (const e of bins.get(Math.floor(v.p[0] / cell) + ',' + Math.floor(v.p[1] / cell)) ?? []) {
144
+ if (e === i || e === v.prev)
145
+ continue;
146
+ const a = verts[e].p, b = verts[verts[e].next].p;
147
+ if (cross(a, b, v.p) === 0 && v.p[0] >= Math.min(a[0], b[0]) && v.p[0] <= Math.max(a[0], b[0]) &&
148
+ v.p[1] >= Math.min(a[1], b[1]) && v.p[1] <= Math.max(a[1], b[1])) {
149
+ fixedComponents.add(loops[v.loop].component);
150
+ fixedComponents.add(loops[verts[e].loop].component);
151
+ }
152
+ }
153
+ });
154
+ // Preserve contacts as well as crossings: a diagonal pinch can close a hole even when
155
+ // no pair of segments crosses strictly. Only an actual shared adjacent vertex is allowed.
156
+ const blocked = (a, b, c, d) => {
157
+ if (!intersects(verts[a].p, verts[b].p, verts[c].p, verts[d].p))
158
+ return false;
159
+ const shared = a === c || a === d ? a : b === c || b === d ? b : -1;
160
+ if (shared < 0)
161
+ return true;
162
+ const s = verts[shared].p, p = verts[a === shared ? b : a].p, q = verts[c === shared ? d : c].p;
163
+ return cross(s, p, q) === 0 && (p[0] - s[0]) * (q[0] - s[0]) + (p[1] - s[1]) * (q[1] - s[1]) > 0;
164
+ };
165
+ const pending = verts.map((_, i) => i), queued = new Set(pending);
166
+ for (let head = 0; head < pending.length; head++) {
167
+ const i = pending[head];
168
+ queued.delete(i);
169
+ const v = verts[i];
170
+ if (!v.active || counts[v.loop] <= 3 || fixedComponents.has(loops[v.loop].component))
171
+ continue;
172
+ const p = verts[v.prev], n = verts[v.next], a = p.p, b = v.p, c = n.p;
173
+ if ((a[0] === c[0] && a[1] === c[1]) || dist2(b, a, c) > tolerance * tolerance)
174
+ continue;
175
+ if (p.span.some((q) => dist2(q, a, c) > tolerance * tolerance) || v.span.some((q) => dist2(q, a, c) > tolerance * tolerance))
176
+ continue;
177
+ const candidates = new Set();
178
+ for (const k of keys(a, b, c))
179
+ for (const e of bins.get(k) ?? [])
180
+ candidates.add(e);
181
+ let safe = true;
182
+ for (const e of candidates) {
183
+ if (e === v.prev || e === i)
184
+ continue;
185
+ const edge = verts[e], end = edge.next, q = edge.p, r = verts[end].p;
186
+ // Only the actual adjacent vertices may touch the swept triangle.
187
+ if ((e !== v.prev && e !== v.next && inTriangle(q, a, b, c)) ||
188
+ (end !== v.prev && end !== v.next && inTriangle(r, a, b, c)) ||
189
+ blocked(v.prev, v.next, e, end) || blocked(v.prev, i, e, end) || blocked(i, v.next, e, end)) {
190
+ safe = false;
191
+ break;
192
+ }
193
+ }
194
+ if (!safe)
195
+ continue;
196
+ index(v.prev, false);
197
+ index(i, false);
198
+ p.span = p.span.concat(v.span);
199
+ p.next = v.next;
200
+ n.prev = v.prev;
201
+ v.active = false;
202
+ counts[v.loop]--;
203
+ if (first[v.loop] === i)
204
+ first[v.loop] = v.next;
205
+ index(v.prev, true);
206
+ for (const k of [v.prev, v.next])
207
+ if (!queued.has(k)) {
208
+ pending.push(k);
209
+ queued.add(k);
210
+ }
211
+ }
212
+ for (let l = 0; l < loops.length; l++) {
213
+ const points = [];
214
+ let i = first[l];
215
+ do {
216
+ points.push(verts[i].p);
217
+ i = verts[i].next;
218
+ } while (i !== first[l]);
219
+ loops[l].points = points;
220
+ }
221
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Triangles A (offset a) and B (offset b) in T (9 numbers each) meet beyond what they share: `shared` corners (0, 1
3
+ * or 2; the shared corners must be the same points). eps: length tolerance.
4
+ */
5
+ export declare function trianglesContact(T: ArrayLike<number>, a: number, b: number, shared: number, eps: number): boolean;
@@ -0,0 +1,120 @@
1
+ // Strict triangle-pair contact test for self-intersection checks (analysis.selfIntersections with strict: true, used by
2
+ // solidify): two triangles of one mesh may meet only along what they share. Reported:
3
+ // - no shared corner: any contact, touching included (crossing edges, a vertex on the other face, coplanar overlap)
4
+ // - one shared corner: any common point other than that corner (one folds through the other near the corner)
5
+ // - a shared edge: coplanar overlap of positive area (one folded back onto the other); non-coplanar triangles that
6
+ // share an edge can only meet along it
7
+ // Non-coplanar pairs use the interval overlap of both triangles on the line where their planes meet (Möller);
8
+ // coplanar ones are clipped in 2D. Tolerances scale with the mesh size (eps = lengths, rel = areas).
9
+ const dot = (ax, ay, az, bx, by, bz) => ax * bx + ay * by + az * bz;
10
+ /** Signed doubled area of a 2D triangle. */
11
+ const area2 = (ax, ay, bx, by, cx, cy) => (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
12
+ /** Clip CCW triangle a against CCW triangle b (2D, 6 numbers each): intersection polygon area. */
13
+ function clipArea(a, b) {
14
+ let poly = a.slice();
15
+ for (let e = 0; e < 3 && poly.length >= 6; e++) {
16
+ const ax = b[e * 2], ay = b[e * 2 + 1], bx = b[((e + 1) % 3) * 2], by = b[((e + 1) % 3) * 2 + 1];
17
+ const out = [], n = poly.length / 2;
18
+ for (let i = 0; i < n; i++) {
19
+ const cx = poly[i * 2], cy = poly[i * 2 + 1], dx = poly[((i + 1) % n) * 2], dy = poly[((i + 1) % n) * 2 + 1];
20
+ const sc = area2(ax, ay, bx, by, cx, cy), sd = area2(ax, ay, bx, by, dx, dy);
21
+ if (sc >= 0)
22
+ out.push(cx, cy);
23
+ if ((sc >= 0) !== (sd >= 0)) {
24
+ const t = sc / (sc - sd);
25
+ out.push(cx + (dx - cx) * t, cy + (dy - cy) * t);
26
+ }
27
+ }
28
+ poly = out;
29
+ }
30
+ if (poly.length < 6)
31
+ return 0;
32
+ let s = 0;
33
+ for (let i = 0, n = poly.length / 2; i < n; i++) {
34
+ const j = (i + 1) % n;
35
+ s += poly[i * 2] * poly[j * 2 + 1] - poly[j * 2] * poly[i * 2 + 1];
36
+ }
37
+ return Math.abs(s) / 2;
38
+ }
39
+ /** 2D segments p1p2 and q1q2 touch or cross (within eps). */
40
+ function segTouch(p1x, p1y, p2x, p2y, q1x, q1y, q2x, q2y, eps) {
41
+ const lp = Math.hypot(p2x - p1x, p2y - p1y) || 1, lq = Math.hypot(q2x - q1x, q2y - q1y) || 1;
42
+ const d1 = area2(q1x, q1y, q2x, q2y, p1x, p1y) / lq, d2 = area2(q1x, q1y, q2x, q2y, p2x, p2y) / lq;
43
+ const d3 = area2(p1x, p1y, p2x, p2y, q1x, q1y) / lp, d4 = area2(p1x, p1y, p2x, p2y, q2x, q2y) / lp;
44
+ if (((d1 > eps && d2 > eps) || (d1 < -eps && d2 < -eps)) || ((d3 > eps && d4 > eps) || (d3 < -eps && d4 < -eps)))
45
+ return false;
46
+ // collinear-ish: projections must overlap
47
+ const ux = (p2x - p1x) / lp, uy = (p2y - p1y) / lp;
48
+ const a0 = 0, a1 = lp, b0 = (q1x - p1x) * ux + (q1y - p1y) * uy, b1 = (q2x - p1x) * ux + (q2y - p1y) * uy;
49
+ if (Math.abs(d1) <= eps && Math.abs(d2) <= eps)
50
+ return Math.min(a1, Math.max(b0, b1)) - Math.max(a0, Math.min(b0, b1)) >= -eps;
51
+ return true;
52
+ }
53
+ /**
54
+ * Triangles A (offset a) and B (offset b) in T (9 numbers each) meet beyond what they share: `shared` corners (0, 1
55
+ * or 2; the shared corners must be the same points). eps: length tolerance.
56
+ */
57
+ export function trianglesContact(T, a, b, shared, eps) {
58
+ const A = [T[a], T[a + 1], T[a + 2], T[a + 3], T[a + 4], T[a + 5], T[a + 6], T[a + 7], T[a + 8]];
59
+ const B = [T[b], T[b + 1], T[b + 2], T[b + 3], T[b + 4], T[b + 5], T[b + 6], T[b + 7], T[b + 8]];
60
+ const nrm = (X) => {
61
+ const ux = X[3] - X[0], uy = X[4] - X[1], uz = X[5] - X[2], wx = X[6] - X[0], wy = X[7] - X[1], wz = X[8] - X[2];
62
+ const nx = uy * wz - uz * wy, ny = uz * wx - ux * wz, nz = ux * wy - uy * wx, l = Math.hypot(nx, ny, nz);
63
+ return l > 0 ? [nx / l, ny / l, nz / l, l / 2] : null;
64
+ };
65
+ const nA = nrm(A), nB = nrm(B);
66
+ if (!nA || !nB)
67
+ return false; // degenerate triangles are reported by the degeneracy checks
68
+ // distances of each triangle's corners to the other's plane
69
+ const dA = [0, 1, 2].map((k) => dot(A[k * 3] - B[0], A[k * 3 + 1] - B[1], A[k * 3 + 2] - B[2], nB[0], nB[1], nB[2]));
70
+ const dB = [0, 1, 2].map((k) => dot(B[k * 3] - A[0], B[k * 3 + 1] - A[1], B[k * 3 + 2] - A[2], nA[0], nA[1], nA[2]));
71
+ const side = (d) => (d.every((x) => x > eps) ? 1 : d.every((x) => x < -eps) ? -1 : 0);
72
+ if (side(dA) !== 0 || side(dB) !== 0)
73
+ return false;
74
+ const coplanar = dA.every((x) => Math.abs(x) <= eps) && dB.every((x) => Math.abs(x) <= eps);
75
+ if (coplanar) {
76
+ // project on the dominant axis plane of A's normal, orient both counter-clockwise
77
+ const ax = Math.abs(nA[0]), ay = Math.abs(nA[1]), az = Math.abs(nA[2]);
78
+ const [i, j] = ax >= ay && ax >= az ? [1, 2] : ay >= az ? [2, 0] : [0, 1];
79
+ const p2 = (X) => { const q = [X[i], X[j], X[3 + i], X[3 + j], X[6 + i], X[6 + j]]; return area2(q[0], q[1], q[2], q[3], q[4], q[5]) < 0 ? [q[0], q[1], q[4], q[5], q[2], q[3]] : q; };
80
+ const pa = p2(A), pb = p2(B);
81
+ const proj = Math.max(ax, ay, az) || 1;
82
+ const ov = clipArea(pa, pb) / proj;
83
+ if (ov > 1e-9 * Math.min(nA[3], nB[3]))
84
+ return true;
85
+ if (shared)
86
+ return false;
87
+ // no area in common: touching edges or corners still count when nothing is shared
88
+ for (let e = 0; e < 3; e++)
89
+ for (let f = 0; f < 3; f++) {
90
+ if (segTouch(pa[e * 2], pa[e * 2 + 1], pa[((e + 1) % 3) * 2], pa[((e + 1) % 3) * 2 + 1], pb[f * 2], pb[f * 2 + 1], pb[((f + 1) % 3) * 2], pb[((f + 1) % 3) * 2 + 1], eps * proj))
91
+ return true;
92
+ }
93
+ return false;
94
+ }
95
+ if (shared >= 2)
96
+ return false;
97
+ // interval of each triangle on the line L = nA × nB, from the points where its edges meet the other plane
98
+ const Lx = nA[1] * nB[2] - nA[2] * nB[1], Ly = nA[2] * nB[0] - nA[0] * nB[2], Lz = nA[0] * nB[1] - nA[1] * nB[0];
99
+ const interval = (X, d) => {
100
+ let lo = Infinity, hi = -Infinity;
101
+ const add = (x, y, z) => { const s = x * Lx + y * Ly + z * Lz; if (s < lo)
102
+ lo = s; if (s > hi)
103
+ hi = s; };
104
+ for (let k = 0; k < 3; k++) {
105
+ const m = (k + 1) % 3;
106
+ if (Math.abs(d[k]) <= eps)
107
+ add(X[k * 3], X[k * 3 + 1], X[k * 3 + 2]);
108
+ if ((d[k] > eps && d[m] < -eps) || (d[k] < -eps && d[m] > eps)) {
109
+ const t = d[k] / (d[k] - d[m]);
110
+ add(X[k * 3] + (X[m * 3] - X[k * 3]) * t, X[k * 3 + 1] + (X[m * 3 + 1] - X[k * 3 + 1]) * t, X[k * 3 + 2] + (X[m * 3 + 2] - X[k * 3 + 2]) * t);
111
+ }
112
+ }
113
+ return [lo, hi];
114
+ };
115
+ const [a0, a1] = interval(A, dA), [b0, b1] = interval(B, dB);
116
+ const ll = Math.hypot(Lx, Ly, Lz) || 1;
117
+ const overlap = (Math.min(a1, b1) - Math.max(a0, b0)) / ll;
118
+ // one shared corner: the planes' line runs through it and both intervals contain it; more than a point in common is a fold
119
+ return shared === 1 ? overlap > eps : overlap >= -eps;
120
+ }
package/dist/core/uv.d.ts CHANGED
@@ -125,6 +125,19 @@ export declare function findIslands(g: Geometry, uv: Float64Array, byAttr?: Int3
125
125
  export declare function convexHull2D(pts: ArrayLike<number>): number[];
126
126
  /** Angle (radians) that rotates a hull to its minimum-area bounding rectangle (rotating calipers over hull edges). */
127
127
  export declare function minAreaRectAngle(hull: number[]): number;
128
+ export interface Rect {
129
+ w: number;
130
+ h: number;
131
+ id: number;
132
+ }
133
+ export interface Placed {
134
+ x: number;
135
+ y: number;
136
+ rot: boolean;
137
+ bin: number;
138
+ }
139
+ /** Skyline bottom-left packing of rects into `bins` squares of side W. Returns placements or null if they don't fit. */
140
+ export declare function skylinePack(rects: Rect[], W: number, bins: number, allowRotate: boolean, H?: number): Placed[] | null;
128
141
  /**
129
142
  * Pack islands into the 0..1 tile (or UDIM tiles 1001.. going right then up, 10 per row). Returns new
130
143
  * per-vertex uv (vertices outside every island keep their input uv).
package/dist/core/uv.js CHANGED
@@ -801,7 +801,7 @@ export function minAreaRectAngle(hull) {
801
801
  return best;
802
802
  }
803
803
  /** Skyline bottom-left packing of rects into `bins` squares of side W. Returns placements or null if they don't fit. */
804
- function skylinePack(rects, W, bins, allowRotate) {
804
+ export function skylinePack(rects, W, bins, allowRotate, H = W) {
805
805
  const out = new Array(rects.length);
806
806
  let bin = 0;
807
807
  let sky = [{ x: 0, y: 0, w: W }];
@@ -812,7 +812,7 @@ function skylinePack(rects, W, bins, allowRotate) {
812
812
  let best = null;
813
813
  for (const rot of allowRotate && Math.abs(r.w - r.h) > eps ? [false, true] : [false]) {
814
814
  const w = rot ? r.h : r.w, h = rot ? r.w : r.h;
815
- if (w > W + eps || h > W + eps)
815
+ if (w > W + eps || h > H + eps)
816
816
  continue;
817
817
  for (let i = 0; i < sky.length; i++) {
818
818
  const x = sky[i].x;
@@ -824,7 +824,7 @@ function skylinePack(rects, W, bins, allowRotate) {
824
824
  rem -= sky[j].w;
825
825
  j++;
826
826
  }
827
- if (y + h > W + eps)
827
+ if (y + h > H + eps)
828
828
  continue;
829
829
  const top = y + h;
830
830
  if (!best || top < best.top - eps || (Math.abs(top - best.top) <= eps && x < best.x))
@@ -0,0 +1,66 @@
1
+ import type { Geometry } from './geometry.ts';
2
+ import type { Triangulation } from './topology.ts';
3
+ export interface UVReportOptions {
4
+ /** uv attribute (vertex or point; default "uv") */
5
+ attribute?: string;
6
+ /** texture size in texels for texel density: n or [width, height] */
7
+ resolution?: number | [number, number];
8
+ /** prim string attribute naming pieces (default "name") */
9
+ pieceAttrib?: string;
10
+ /** most exact pair tests (default 4,000,000) */
11
+ maxPairTests?: number;
12
+ /** most overlap examples / collapsed triangle ids listed (default 16) */
13
+ maxExamples?: number;
14
+ /** raster estimate grid size (default 1024) */
15
+ rasterSize?: number;
16
+ }
17
+ export interface UVOverlap {
18
+ triangles: [number, number];
19
+ prims: [number, number];
20
+ area: number;
21
+ sameChart: boolean;
22
+ }
23
+ export interface UVPiece {
24
+ name: string;
25
+ triangles: number;
26
+ surfaceArea: number;
27
+ uvArea: number;
28
+ texelsPerMetre?: number;
29
+ }
30
+ export interface UVReport {
31
+ attribute: string;
32
+ /** false when uv is missing or a bound stopped the analysis early; reasons lists why */
33
+ complete: boolean;
34
+ reasons: string[];
35
+ missing: boolean;
36
+ triangles: number;
37
+ nonFinite: number;
38
+ collapsed: number;
39
+ collapsedTriangles: number[];
40
+ /** triangles with uv winding opposite to the majority (mirrored islands are legal; listed for review) */
41
+ mirrored: number;
42
+ outOfTile: number;
43
+ /** UDIM-style tiles touched: "u,v" integer pairs (0,0 is the unit tile) */
44
+ tiles: string[];
45
+ charts: number;
46
+ uvArea: number;
47
+ overlap: {
48
+ pairs: number;
49
+ sameChartPairs: number;
50
+ area: number;
51
+ candidatePairs: number;
52
+ testedPairs: number;
53
+ examples: UVOverlap[];
54
+ };
55
+ utilization: {
56
+ method: 'exact' | 'raster-estimate' | 'none';
57
+ value: number;
58
+ rasterSize?: number;
59
+ note: string;
60
+ };
61
+ pieces: UVPiece[];
62
+ resolution?: [number, number];
63
+ }
64
+ export declare function uvReport(g: Geometry, o?: UVReportOptions, tri?: Triangulation): UVReport;
65
+ /** Short text form of a report for inspect. */
66
+ export declare function uvReportText(r: UVReport): string[];