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,38 @@
1
+ import type { Geometry } from './geometry.ts';
2
+ export interface SolidifyOptions {
3
+ thickness: number;
4
+ /** -1 inside … 0 centred … +1 outside, relative to the face winding */
5
+ offset: number;
6
+ fillRim: boolean;
7
+ /** largest allowed |δ| (offset distance / face distance) */
8
+ miterLimit: number;
9
+ /** strict self-intersection pair tests (default 4,000,000) */
10
+ maxTests?: number;
11
+ }
12
+ export interface SolidifyResult {
13
+ geo: Geometry;
14
+ stats: {
15
+ outer: number;
16
+ inner: number;
17
+ rim: number;
18
+ maxMiter: number;
19
+ maxResidual: number;
20
+ tested: number;
21
+ };
22
+ }
23
+ /** A rejected input or result: message says what and where, hint what to do. */
24
+ export declare class SolidifyError extends Error {
25
+ hint: string;
26
+ constructor(message: string, hint: string);
27
+ }
28
+ /** Largest allowed least-squares residual, as a fraction of the offset distance. */
29
+ export declare const RESIDUAL_LIMIT = 0.02;
30
+ /**
31
+ * Minimum-length least-squares δ with n_f · δ = 1 for the unit normals N (3 per face): δ = (NᵀN)⁺ Nᵀ 1, dropping
32
+ * eigen-directions below 1e-9 of the largest (the free directions of an underconstrained point).
33
+ */
34
+ export declare function offsetDirection(N: number[]): {
35
+ d: number[];
36
+ residual: number;
37
+ };
38
+ export declare function solidify(g: Geometry, o: SolidifyOptions): SolidifyResult;
@@ -0,0 +1,356 @@
1
+ // Solidify (shell): a constant-thickness solid from a consistently wound polygon surface (a sheet, a folded panel, a
2
+ // closed hull).
3
+ //
4
+ // Offsets follow the face winding: the face normal n points to the "outside". offset +1 grows the wall outward (the
5
+ // input becomes the inner surface), -1 inward (the input stays the outer surface), 0 centres it. The two surfaces sit
6
+ // at signed distances d_out = (1 + offset)/2 · thickness and d_in = -(1 - offset)/2 · thickness.
7
+ //
8
+ // Each point moves by d · δ, where δ solves n_f · δ = 1 for every face f around the point: the offset planes of the
9
+ // incident faces meet there, so every face of a surface copy is exactly d away from its source face. δ is the
10
+ // minimum-length least-squares solution (pseudo-inverse of the stacked normals, from a deterministic Jacobi eigen
11
+ // decomposition): at a boundary point with one face it is that face's normal; along a fold it is the mitre of the two
12
+ // planes; at a corner of three or more planes their intersection. Where the planes do not meet (a saddle, a twisted
13
+ // corner) the least-squares residual is what thickness the faces lose; above RESIDUAL_LIMIT of the offset the node
14
+ // stops instead of silently thinning the wall, as it does when |δ| exceeds miter_limit (a fold so sharp the mitre runs
15
+ // away).
16
+ //
17
+ // Topology: an outer copy (input winding), an inner copy (reversed) and, with fill_rim, one quad per boundary edge
18
+ // joining them, oriented outward: a closed manifold for an open sheet, two nested closed surfaces for a closed one.
19
+ // Groups inner / outer / rim. Attributes come through GeoBuilder provenance (N and tangent are dropped: they would
20
+ // point the wrong way on the inner copy; recompute them downstream). Surface uvs are copied; rim uvs are metric: u =
21
+ // distance along the boundary loop, v = 0 on the inner surface to thickness on the outer.
22
+ //
23
+ // Rejected with a diagnostic, never repaired: open polylines, non-manifold edges or points, inconsistent winding,
24
+ // collapsed faces, and results that fold over (a face of a surface copy flips) or intersect themselves (strict check:
25
+ // crossings, coplanar overlaps and contacts beyond the shared vertices and edges). If the intersection check runs out
26
+ // of its budget the node fails rather than passing unchecked geometry.
27
+ import { GeoBuilder } from './geometry.js';
28
+ import { buildEdges, primNewell } from './topology.js';
29
+ import { halfEdges } from './halfedge.js';
30
+ import { selfIntersections } from './analysis.js';
31
+ /** A rejected input or result: message says what and where, hint what to do. */
32
+ export class SolidifyError extends Error {
33
+ hint;
34
+ constructor(message, hint) { super(message); this.hint = hint; }
35
+ }
36
+ /** Largest allowed least-squares residual, as a fraction of the offset distance. */
37
+ export const RESIDUAL_LIMIT = 0.02;
38
+ const list = (a, n = 8) => a.slice(0, n).join(', ') + (a.length > n ? `, … (${a.length})` : '');
39
+ /** Eigen decomposition of a symmetric 3×3 (row-major) by cyclic Jacobi: values w, vectors as columns of V. */
40
+ function jacobi3(A) {
41
+ const a = A.slice(), V = [1, 0, 0, 0, 1, 0, 0, 0, 1];
42
+ for (let sweep = 0; sweep < 32; sweep++) {
43
+ const off = a[1] * a[1] + a[2] * a[2] + a[5] * a[5];
44
+ if (off < 1e-30 * (a[0] * a[0] + a[4] * a[4] + a[8] * a[8] + 1e-300))
45
+ break;
46
+ for (const [p, q] of [[0, 1], [0, 2], [1, 2]]) {
47
+ const apq = a[p * 3 + q];
48
+ if (apq === 0)
49
+ continue;
50
+ const theta = (a[q * 3 + q] - a[p * 3 + p]) / (2 * apq);
51
+ const t = Math.sign(theta || 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1));
52
+ const c = 1 / Math.sqrt(t * t + 1), s = t * c;
53
+ for (let k = 0; k < 3; k++) {
54
+ const akp = a[k * 3 + p], akq = a[k * 3 + q];
55
+ a[k * 3 + p] = c * akp - s * akq;
56
+ a[k * 3 + q] = s * akp + c * akq;
57
+ }
58
+ for (let k = 0; k < 3; k++) {
59
+ const apk = a[p * 3 + k], aqk = a[q * 3 + k];
60
+ a[p * 3 + k] = c * apk - s * aqk;
61
+ a[q * 3 + k] = s * apk + c * aqk;
62
+ }
63
+ for (let k = 0; k < 3; k++) {
64
+ const vkp = V[k * 3 + p], vkq = V[k * 3 + q];
65
+ V[k * 3 + p] = c * vkp - s * vkq;
66
+ V[k * 3 + q] = s * vkp + c * vkq;
67
+ }
68
+ }
69
+ }
70
+ return { w: [a[0], a[4], a[8]], V };
71
+ }
72
+ /**
73
+ * Minimum-length least-squares δ with n_f · δ = 1 for the unit normals N (3 per face): δ = (NᵀN)⁺ Nᵀ 1, dropping
74
+ * eigen-directions below 1e-9 of the largest (the free directions of an underconstrained point).
75
+ */
76
+ export function offsetDirection(N) {
77
+ const M = [0, 0, 0, 0, 0, 0, 0, 0, 0], b = [0, 0, 0];
78
+ const k = N.length / 3;
79
+ for (let f = 0; f < k; f++) {
80
+ const x = N[f * 3], y = N[f * 3 + 1], z = N[f * 3 + 2];
81
+ M[0] += x * x;
82
+ M[1] += x * y;
83
+ M[2] += x * z;
84
+ M[4] += y * y;
85
+ M[5] += y * z;
86
+ M[8] += z * z;
87
+ b[0] += x;
88
+ b[1] += y;
89
+ b[2] += z;
90
+ }
91
+ M[3] = M[1];
92
+ M[6] = M[2];
93
+ M[7] = M[5];
94
+ const { w, V } = jacobi3(M);
95
+ const wmax = Math.max(w[0], w[1], w[2]);
96
+ const d = [0, 0, 0];
97
+ for (let e = 0; e < 3; e++) {
98
+ if (!(w[e] > 1e-9 * wmax))
99
+ continue;
100
+ const vx = V[e], vy = V[3 + e], vz = V[6 + e];
101
+ const s = (vx * b[0] + vy * b[1] + vz * b[2]) / w[e];
102
+ d[0] += vx * s;
103
+ d[1] += vy * s;
104
+ d[2] += vz * s;
105
+ }
106
+ let residual = 0;
107
+ for (let f = 0; f < k; f++)
108
+ residual = Math.max(residual, Math.abs(N[f * 3] * d[0] + N[f * 3 + 1] * d[1] + N[f * 3 + 2] * d[2] - 1));
109
+ return { d, residual };
110
+ }
111
+ export function solidify(g, o) {
112
+ const t = o.thickness, off = o.offset;
113
+ if (!(t > 0) || !Number.isFinite(t))
114
+ throw new SolidifyError(`solidify: thickness must be a positive number of metres (got ${t})`, 'e.g. 0.01 for 1 cm');
115
+ if (!(off >= -1 && off <= 1))
116
+ throw new SolidifyError(`solidify: offset must be between -1 (inside) and +1 (outside) (got ${off})`, '0 centres the wall on the surface');
117
+ if (!(o.miterLimit >= 1))
118
+ throw new SolidifyError(`solidify: miter_limit must be at least 1 (got ${o.miterLimit})`, 'the default 4 allows folds up to about 150°');
119
+ const np = g.numPoints, npr = g.numPrims, P = g.P, vp = g.vertexPoint;
120
+ // ---- input checks
121
+ const open = [], polys = [];
122
+ for (let p = 0; p < npr; p++) {
123
+ if (g.primKind && g.primKind[p]) {
124
+ open.push(p);
125
+ continue;
126
+ }
127
+ if (!g.primClosed[p])
128
+ open.push(p);
129
+ else
130
+ polys.push(p);
131
+ }
132
+ if (open.length)
133
+ throw new SolidifyError(`solidify: ${open.length} prim(s) are not polygons (prims ${list(open)})`, 'solidify works on a polygon surface; delete polylines/points/packed prims upstream (delete, or blast by group)');
134
+ if (!polys.length)
135
+ throw new SolidifyError('solidify: the input has no polygons', 'connect a polygon surface (grid, a selected part of a mesh)');
136
+ const fn = new Float64Array(npr * 3), collapsed = [], nrm = [0, 0, 0];
137
+ for (const p of polys) {
138
+ const s = g.primStart[p], e = g.primStart[p + 1];
139
+ let e2 = 0;
140
+ for (let v = s; v < e; v++) {
141
+ const a = vp[v] * 3, b = vp[v + 1 < e ? v + 1 : s] * 3;
142
+ e2 = Math.max(e2, (P[b] - P[a]) ** 2 + (P[b + 1] - P[a + 1]) ** 2 + (P[b + 2] - P[a + 2]) ** 2);
143
+ }
144
+ primNewell(g, p, nrm);
145
+ const l = Math.hypot(nrm[0], nrm[1], nrm[2]);
146
+ if (e - s < 3 || !(l > 1e-9 * e2)) {
147
+ collapsed.push(p);
148
+ continue;
149
+ }
150
+ fn[p * 3] = nrm[0] / l;
151
+ fn[p * 3 + 1] = nrm[1] / l;
152
+ fn[p * 3 + 2] = nrm[2] / l;
153
+ }
154
+ if (collapsed.length)
155
+ throw new SolidifyError(`solidify: ${collapsed.length} collapsed polygon(s) without a usable normal (prims ${list(collapsed)})`, 'remove them first (clean / mesh_repair with degenerate removal, or fuse points)');
156
+ const E = buildEdges(g);
157
+ const nonManifold = [];
158
+ for (let e = 0; e < E.a.length; e++)
159
+ if (E.count[e] > 2)
160
+ nonManifold.push(`${E.a[e]}-${E.b[e]}`);
161
+ if (nonManifold.length)
162
+ throw new SolidifyError(`solidify: ${nonManifold.length} non-manifold edge(s) shared by more than two polygons (points ${list(nonManifold)})`, 'select one sheet upstream (split or delete the extra faces)');
163
+ const he = halfEdges(g);
164
+ if (he.flippedEdges.size) {
165
+ const bad = [...he.flippedEdges].slice(0, 8).map((e) => `${he.edgeA[e]}-${he.edgeB[e]}`);
166
+ throw new SolidifyError(`solidify: inconsistent winding: ${he.flippedEdges.size} edge(s) where neighbouring polygons run the same way (points ${list(bad)})`, 'make the winding consistent first (reverse part of the mesh, or clean fix_winding); the winding decides which side is outside');
167
+ }
168
+ // incident faces per point; a point's faces must form one fan (else two sheets touch at a point)
169
+ const inc = Array.from({ length: np }, () => []);
170
+ for (const p of polys)
171
+ for (let v = g.primStart[p]; v < g.primStart[p + 1]; v++)
172
+ inc[vp[v]].push(p);
173
+ const edgeKey = (a, b) => (a < b ? a * np + b : b * np + a);
174
+ const edgePrims = new Map();
175
+ for (const p of polys) {
176
+ const s = g.primStart[p], e = g.primStart[p + 1];
177
+ for (let v = s; v < e; v++) {
178
+ const k = edgeKey(vp[v], vp[v + 1 < e ? v + 1 : s]);
179
+ const l = edgePrims.get(k);
180
+ if (l)
181
+ l.push(p);
182
+ else
183
+ edgePrims.set(k, [p]);
184
+ }
185
+ }
186
+ const bowtie = [];
187
+ for (let i = 0; i < np; i++) {
188
+ const F = [...new Set(inc[i])];
189
+ if (F.length < 2)
190
+ continue;
191
+ const idx = new Map(F.map((f, k) => [f, k])), par = F.map((_, k) => k);
192
+ const find = (x) => { while (par[x] !== x)
193
+ x = par[x] = par[par[x]]; return x; };
194
+ for (const f of F) {
195
+ const s = g.primStart[f], e = g.primStart[f + 1];
196
+ for (let v = s; v < e; v++) {
197
+ const a = vp[v], b = vp[v + 1 < e ? v + 1 : s];
198
+ if (a !== i && b !== i)
199
+ continue;
200
+ for (const h of edgePrims.get(edgeKey(a, b)) ?? [])
201
+ if (h !== f) {
202
+ const x = find(idx.get(f)), y = find(idx.get(h));
203
+ if (x !== y)
204
+ par[x] = y;
205
+ }
206
+ }
207
+ }
208
+ if (new Set(F.map((_, k) => find(k))).size > 1)
209
+ bowtie.push(i);
210
+ }
211
+ if (bowtie.length)
212
+ throw new SolidifyError(`solidify: ${bowtie.length} non-manifold point(s) where separate fans of polygons touch (points ${list(bowtie)})`, 'split the sheets at those points (fuse off / polysplit) or remove one of the touching parts');
213
+ // ---- offset directions
214
+ const dOut = ((1 + off) / 2) * t, dIn = -((1 - off) / 2) * t;
215
+ const delta = new Float64Array(np * 3), used = new Uint8Array(np);
216
+ let maxMiter = 0, maxResidual = 0;
217
+ const miterBad = [], residualBad = [];
218
+ for (let i = 0; i < np; i++) {
219
+ const F = [...new Set(inc[i])];
220
+ if (!F.length)
221
+ continue;
222
+ used[i] = 1;
223
+ const N = [];
224
+ for (const f of F)
225
+ N.push(fn[f * 3], fn[f * 3 + 1], fn[f * 3 + 2]);
226
+ const { d, residual } = offsetDirection(N);
227
+ const len = Math.hypot(d[0], d[1], d[2]);
228
+ maxMiter = Math.max(maxMiter, len);
229
+ maxResidual = Math.max(maxResidual, residual);
230
+ if (len > o.miterLimit)
231
+ miterBad.push(`${i} (×${len.toFixed(2)})`);
232
+ if (residual > RESIDUAL_LIMIT)
233
+ residualBad.push(`${i} (${(residual * 100).toFixed(1)}%)`);
234
+ delta[i * 3] = d[0];
235
+ delta[i * 3 + 1] = d[1];
236
+ delta[i * 3 + 2] = d[2];
237
+ }
238
+ if (miterBad.length)
239
+ throw new SolidifyError(`solidify: ${miterBad.length} point(s) need an offset longer than miter_limit ${o.miterLimit} × the thickness (points ${list(miterBad)}): the fold is too sharp for a mitred wall`, 'bevel or round the fold first, lower the thickness, or raise miter_limit if the long mitre is intended');
240
+ if (residualBad.length)
241
+ throw new SolidifyError(`solidify: at ${residualBad.length} point(s) the offset planes of the surrounding faces do not meet (thickness lost: points ${list(residualBad)}; limit ${RESIDUAL_LIMIT * 100}%)`, 'the surface is twisted or saddle-shaped there: subdivide or flatten it, or use a thinner wall');
242
+ // ---- build
243
+ const b = new GeoBuilder(g);
244
+ for (const k of ['N', 'tangent']) {
245
+ b.skip.point.add(k);
246
+ b.skip.vertex.add(k);
247
+ b.skip.prim.add(k);
248
+ }
249
+ const uvF = g.findAttrib('uv', ['vertex', 'point']);
250
+ const uvOn = !!uvF && uvF.attr.type === 'float' && !uvF.attr.isArray;
251
+ const uvA = uvOn ? b.attrib('vertex', 'uv', 3) : null;
252
+ if (uvOn) {
253
+ b.skip.vertex.add('uv');
254
+ b.skip.point.add('uv');
255
+ }
256
+ const uvOf = (v) => {
257
+ const a = uvF.attr, i = uvF.cls === 'vertex' ? v : vp[v], s = a.size, d = a.data;
258
+ return [d[i * s], s > 1 ? d[i * s + 1] : 0, s > 2 ? d[i * s + 2] : 0];
259
+ };
260
+ for (let i = 0; i < np; i++)
261
+ if (!used[i])
262
+ b.copyPoint(i); // loose points pass through
263
+ const outerPt = new Int32Array(np).fill(-1), innerPt = new Int32Array(np).fill(-1);
264
+ for (let i = 0; i < np; i++) {
265
+ if (!used[i])
266
+ continue;
267
+ const x = P[i * 3], y = P[i * 3 + 1], z = P[i * 3 + 2], dx = delta[i * 3], dy = delta[i * 3 + 1], dz = delta[i * 3 + 2];
268
+ outerPt[i] = b.addPoint(x + dx * dOut, y + dy * dOut, z + dz * dOut, i);
269
+ innerPt[i] = b.addPoint(x + dx * dIn, y + dy * dIn, z + dz * dIn, i);
270
+ }
271
+ const gOuter = b.group('prim', 'outer'), gInner = b.group('prim', 'inner'), gRim = b.group('prim', 'rim');
272
+ let vOut = 0;
273
+ for (const p of polys) {
274
+ const s = g.primStart[p], e = g.primStart[p + 1], vs = [];
275
+ for (let v = s; v < e; v++)
276
+ vs.push(v);
277
+ gOuter.add(b.addPrim(vs.map((v) => outerPt[vp[v]]), true, p, vs));
278
+ if (uvA)
279
+ for (const v of vs)
280
+ uvA.set(vOut++, uvOf(v));
281
+ }
282
+ for (const p of polys) {
283
+ const s = g.primStart[p], e = g.primStart[p + 1], vs = [s];
284
+ for (let v = e - 1; v > s; v--)
285
+ vs.push(v);
286
+ gInner.add(b.addPrim(vs.map((v) => innerPt[vp[v]]), true, p, vs));
287
+ if (uvA)
288
+ for (const v of vs)
289
+ uvA.set(vOut++, uvOf(v));
290
+ }
291
+ let rims = 0;
292
+ if (o.fillRim) {
293
+ // boundary half-edges (a → b in face winding), chained into loops for the rim's u coordinate
294
+ const bnd = [];
295
+ for (const p of polys) {
296
+ const s = g.primStart[p], e = g.primStart[p + 1];
297
+ for (let v = s; v < e; v++) {
298
+ const w = v + 1 < e ? v + 1 : s;
299
+ if ((edgePrims.get(edgeKey(vp[v], vp[w]))?.length ?? 0) === 1)
300
+ bnd.push({ a: vp[v], b: vp[w], va: v, vb: w, p });
301
+ }
302
+ }
303
+ const fromPt = new Map();
304
+ bnd.forEach((h, k) => fromPt.set(h.a, k));
305
+ const seen = new Uint8Array(bnd.length), u0 = new Float64Array(bnd.length);
306
+ for (let k0 = 0; k0 < bnd.length; k0++) {
307
+ if (seen[k0])
308
+ continue;
309
+ let s = 0;
310
+ for (let k = k0; k !== undefined && !seen[k]; k = fromPt.get(bnd[k].b)) {
311
+ seen[k] = 1;
312
+ u0[k] = s;
313
+ const a = bnd[k].a * 3, c = bnd[k].b * 3;
314
+ s += Math.hypot(P[c] - P[a], P[c + 1] - P[a + 1], P[c + 2] - P[a + 2]);
315
+ }
316
+ }
317
+ bnd.forEach((h, k) => {
318
+ gRim.add(b.addPrim([outerPt[h.a], innerPt[h.a], innerPt[h.b], outerPt[h.b]], true, h.p, [h.va, h.va, h.vb, h.vb]));
319
+ if (uvA) {
320
+ const a = h.a * 3, c = h.b * 3, u1 = u0[k] + Math.hypot(P[c] - P[a], P[c + 1] - P[a + 1], P[c + 2] - P[a + 2]);
321
+ uvA.set(vOut++, [u0[k], t, 0]);
322
+ uvA.set(vOut++, [u0[k], 0, 0]);
323
+ uvA.set(vOut++, [u1, 0, 0]);
324
+ uvA.set(vOut++, [u1, t, 0]);
325
+ }
326
+ rims++;
327
+ });
328
+ }
329
+ const out = b.build();
330
+ // ---- result checks: no face of a surface copy flips, no self-intersection
331
+ const flipped = [];
332
+ const n2 = [0, 0, 0];
333
+ for (let q = 0; q < out.numPrims; q++) {
334
+ const src = q < polys.length ? polys[q] : q < 2 * polys.length ? polys[q - polys.length] : -1;
335
+ if (src < 0)
336
+ break;
337
+ primNewell(out, q, n2);
338
+ const sgn = q < polys.length ? 1 : -1;
339
+ if (!((n2[0] * fn[src * 3] + n2[1] * fn[src * 3 + 1] + n2[2] * fn[src * 3 + 2]) * sgn > 0))
340
+ flipped.push(src);
341
+ }
342
+ if (flipped.length)
343
+ throw new SolidifyError(`solidify: the ${flipped.length} offset cop${flipped.length === 1 ? 'y' : 'ies'} of polygon(s) ${list([...new Set(flipped)])} turn inside out: the wall is thicker than the surface's local radius of curvature`, 'lower the thickness, move the offset towards the convex side, or subdivide less tightly curved');
344
+ const si = selfIntersections(out, o.maxTests ?? 4_000_000, { strict: true });
345
+ if (si.capped)
346
+ throw new SolidifyError(`solidify: the self-intersection check ran out of its budget after ${si.tested.toLocaleString('en-US')} triangle pairs before finishing; the result was not verified`, 'reduce the polygon count (decimate / fewer divisions) or solidify parts separately and merge them');
347
+ if (si.pairs) {
348
+ const prims = [];
349
+ for (let q = 0; q < out.numPrims && prims.length < 8; q++)
350
+ if (si.prims[q])
351
+ prims.push(q);
352
+ const where = prims.map((q) => `${q} (${q < polys.length ? 'outer' : q < 2 * polys.length ? 'inner' : 'rim'})`);
353
+ throw new SolidifyError(`solidify: the shell intersects itself: ${si.pairs} triangle pair(s) cross, overlap or touch beyond their shared edges (result prims ${where.join(', ')}${si.pairs > 8 ? ', …' : ''})`, 'the wall is too thick for the clearance between parts of the surface: lower the thickness or change offset');
354
+ }
355
+ return { geo: out, stats: { outer: polys.length, inner: polys.length, rim: rims, maxMiter, maxResidual, tested: si.tested } };
356
+ }
@@ -0,0 +1,52 @@
1
+ import type { Geometry } from './geometry.ts';
2
+ /** Load (once) and initialise the MikkTSpace WebAssembly module. */
3
+ export declare function loadMikkTSpace(): Promise<void>;
4
+ /** True once loadMikkTSpace() has finished. */
5
+ export declare const mikkTSpaceReady: () => boolean;
6
+ export interface TangentDiagnostics {
7
+ triangles: number;
8
+ /** triangles with a non-finite uv corner */
9
+ uvNonFinite: number;
10
+ /** triangles whose uvs are collinear or coincide (zero uv area) */
11
+ uvDegenerate: number;
12
+ /** corners that received the fallback tangent */
13
+ fallbackCorners: number;
14
+ }
15
+ /**
16
+ * MikkTSpace tangents for a triangle soup: pos and nrm 9 floats per triangle, uv 6 (TopoTopo convention). Returns 12
17
+ * floats per triangle: xyz unit tangent and w = ±1 (bitangent = w · cross(N, T)). Throws when the module is not
18
+ * loaded.
19
+ */
20
+ export declare function mikkTangents(pos: ArrayLike<number>, nrm: ArrayLike<number>, uv: ArrayLike<number>): {
21
+ tangents: Float32Array;
22
+ diag: TangentDiagnostics;
23
+ };
24
+ /**
25
+ * MikkTSpace tangents for the triangles `tris` (vertex indices, as topology.triangulate returns them) of g, with the
26
+ * per-vertex normals N (3 per vertex, e.g. resolveVertexNormals) and per-vertex uv (2 per vertex, TopoTopo
27
+ * convention). 12 floats per triangle, in g's space.
28
+ */
29
+ export declare function cornerTangents(g: Geometry, tris: ArrayLike<number>, N: ArrayLike<number>, uv: ArrayLike<number>): {
30
+ tangents: Float32Array;
31
+ diag: TangentDiagnostics;
32
+ };
33
+ /** Per-vertex uv (2 per vertex) of a vertex or point attribute, or null when g has no such float attribute. */
34
+ export declare function vertexUV(g: Geometry, name?: string): Float64Array | null;
35
+ /**
36
+ * The orthonormal shading frame at a surface sample, as bake_normal writes and the PBR preview reads it: N normalised,
37
+ * T = the interpolated tangent made perpendicular to N and normalised, B = w · cross(N, T) with w the sign of the
38
+ * interpolated handedness. Fills out[0..8] with T, B, N; returns false (out untouched) when T is parallel to N.
39
+ */
40
+ export declare function shadingFrame(nx: number, ny: number, nz: number, tx: number, ty: number, tz: number, w: number, out: number[] | Float64Array): boolean;
41
+ /** The standard tangent attribute: float, 4 components (xyz unit tangent, w = ±1 handedness), point or vertex class. */
42
+ export declare const TANGENT_ATTRIB = "tangent";
43
+ /**
44
+ * Check a supplied tangent attribute: every element finite, |xyz| within 1e-3 of 1, w exactly ±1. Returns null when
45
+ * valid, else a description of the first problem (element class, index and value).
46
+ */
47
+ export declare function tangentProblem(g: Geometry): string | null;
48
+ /**
49
+ * Transform tangent vectors in place by the 3×3 linear part L (column-major, 9 numbers): xyz → normalize(L · xyz),
50
+ * w → w · sign(det L) (a mirror flips the bitangent relative to cross(N, T)). sel limits the elements.
51
+ */
52
+ export declare function transformTangents(d: Float64Array, count: number, L: ArrayLike<number>, sel?: (i: number) => boolean): void;
@@ -0,0 +1,214 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ let mod = null;
10
+ let loading = null;
11
+ /** Load (once) and initialise the MikkTSpace WebAssembly module. */
12
+ export async function loadMikkTSpace() {
13
+ if (mod)
14
+ return;
15
+ if (!loading) {
16
+ loading = (async () => {
17
+ const spec = 'three/examples/jsm/libs/mikktspace.module.js';
18
+ const m = await import(__rewriteRelativeImportExtension(spec));
19
+ await m.ready;
20
+ return m;
21
+ })();
22
+ loading.catch(() => { loading = null; });
23
+ }
24
+ mod = await loading;
25
+ }
26
+ /** True once loadMikkTSpace() has finished. */
27
+ export const mikkTSpaceReady = () => mod !== null;
28
+ /** uv triangles whose doubled area is below this fraction of their squared edge lengths are collapsed. */
29
+ const UV_DEGENERATE = 1e-9;
30
+ /**
31
+ * MikkTSpace tangents for a triangle soup: pos and nrm 9 floats per triangle, uv 6 (TopoTopo convention). Returns 12
32
+ * floats per triangle: xyz unit tangent and w = ±1 (bitangent = w · cross(N, T)). Throws when the module is not
33
+ * loaded.
34
+ */
35
+ export function mikkTangents(pos, nrm, uv) {
36
+ if (!mod)
37
+ throw new Error('MikkTSpace is not loaded: await loadMikkTSpace() first (exportGLB, renderPBR and bake_normal do)');
38
+ const nt = Math.floor(pos.length / 9);
39
+ const diag = { triangles: nt, uvNonFinite: 0, uvDegenerate: 0, fallbackCorners: 0 };
40
+ const bad = new Uint8Array(nt);
41
+ const P = Float32Array.from(pos), N = Float32Array.from(nrm), T = Float32Array.from(uv);
42
+ for (let t = 0; t < nt; t++) {
43
+ let finite = true;
44
+ for (let k = 0; k < 6; k++)
45
+ if (!Number.isFinite(T[t * 6 + k])) {
46
+ finite = false;
47
+ T[t * 6 + k] = 0;
48
+ }
49
+ if (!finite) {
50
+ diag.uvNonFinite++;
51
+ bad[t] = 1;
52
+ continue;
53
+ }
54
+ const u0 = T[t * 6], v0 = T[t * 6 + 1], du1 = T[t * 6 + 2] - u0, dv1 = T[t * 6 + 3] - v0, du2 = T[t * 6 + 4] - u0, dv2 = T[t * 6 + 5] - v0;
55
+ const e2 = du1 * du1 + dv1 * dv1 + du2 * du2 + dv2 * dv2 + (du2 - du1) ** 2 + (dv2 - dv1) ** 2;
56
+ if (!(Math.abs(du1 * dv2 - du2 * dv1) > UV_DEGENERATE * e2)) {
57
+ diag.uvDegenerate++;
58
+ bad[t] = 1;
59
+ }
60
+ }
61
+ for (let i = 0; i < N.length; i += 3) {
62
+ const l = Math.hypot(N[i], N[i + 1], N[i + 2]);
63
+ if (l > 0 && Number.isFinite(l)) {
64
+ N[i] /= l;
65
+ N[i + 1] /= l;
66
+ N[i + 2] /= l;
67
+ }
68
+ else {
69
+ N[i] = 0;
70
+ N[i + 1] = 0;
71
+ N[i + 2] = 1;
72
+ }
73
+ }
74
+ const out = nt ? mod.generateTangents(P, N, T) : new Float32Array(0);
75
+ for (let t = 0; t < nt; t++)
76
+ for (let k = 0; k < 3; k++) {
77
+ const c = t * 3 + k, o = c * 4, n = c * 3;
78
+ let x = out[o], y = out[o + 1], z = out[o + 2];
79
+ const nx = N[n], ny = N[n + 1], nz = N[n + 2];
80
+ // keep it exactly perpendicular to the (normalised, float) normal the consumer will see
81
+ const d = x * nx + y * ny + z * nz;
82
+ x -= nx * d;
83
+ y -= ny * d;
84
+ z -= nz * d;
85
+ const l = Math.hypot(x, y, z), w = out[o + 3];
86
+ if (!bad[t] && l > 1e-6 && Number.isFinite(l) && (w === 1 || w === -1)) {
87
+ out[o] = x / l;
88
+ out[o + 1] = y / l;
89
+ out[o + 2] = z / l;
90
+ continue;
91
+ }
92
+ diag.fallbackCorners++;
93
+ // the world axis least aligned with N, made perpendicular to it
94
+ const ax = Math.abs(nx), ay = Math.abs(ny), az = Math.abs(nz);
95
+ const a = ax <= ay && ax <= az ? [1, 0, 0] : ay <= az ? [0, 1, 0] : [0, 0, 1];
96
+ const e = a[0] * nx + a[1] * ny + a[2] * nz;
97
+ const fx = a[0] - nx * e, fy = a[1] - ny * e, fz = a[2] - nz * e, fl = Math.hypot(fx, fy, fz);
98
+ out[o] = fx / fl;
99
+ out[o + 1] = fy / fl;
100
+ out[o + 2] = fz / fl;
101
+ out[o + 3] = 1;
102
+ }
103
+ return { tangents: out, diag };
104
+ }
105
+ /**
106
+ * MikkTSpace tangents for the triangles `tris` (vertex indices, as topology.triangulate returns them) of g, with the
107
+ * per-vertex normals N (3 per vertex, e.g. resolveVertexNormals) and per-vertex uv (2 per vertex, TopoTopo
108
+ * convention). 12 floats per triangle, in g's space.
109
+ */
110
+ export function cornerTangents(g, tris, N, uv) {
111
+ const nc = tris.length, P = g.P, vp = g.vertexPoint;
112
+ const pos = new Float32Array(nc * 3), nrm = new Float32Array(nc * 3), tex = new Float32Array(nc * 2);
113
+ for (let c = 0; c < nc; c++) {
114
+ const v = tris[c], p = vp[v] * 3;
115
+ pos[c * 3] = P[p];
116
+ pos[c * 3 + 1] = P[p + 1];
117
+ pos[c * 3 + 2] = P[p + 2];
118
+ nrm[c * 3] = N[v * 3];
119
+ nrm[c * 3 + 1] = N[v * 3 + 1];
120
+ nrm[c * 3 + 2] = N[v * 3 + 2];
121
+ tex[c * 2] = uv[v * 2];
122
+ tex[c * 2 + 1] = uv[v * 2 + 1];
123
+ }
124
+ return mikkTangents(pos, nrm, tex);
125
+ }
126
+ /** Per-vertex uv (2 per vertex) of a vertex or point attribute, or null when g has no such float attribute. */
127
+ export function vertexUV(g, name = 'uv') {
128
+ const f = g.findAttrib(name, ['vertex', 'point']);
129
+ if (!f || f.attr.type !== 'float' || f.attr.isArray)
130
+ return null;
131
+ const a = f.attr, d = a.data, s = a.size;
132
+ const out = new Float64Array(g.numVertices * 2);
133
+ for (let v = 0; v < g.numVertices; v++) {
134
+ const i = (f.cls === 'vertex' ? v : g.vertexPoint[v]) * s;
135
+ out[v * 2] = d[i];
136
+ out[v * 2 + 1] = s > 1 ? d[i + 1] : 0;
137
+ }
138
+ return out;
139
+ }
140
+ /**
141
+ * The orthonormal shading frame at a surface sample, as bake_normal writes and the PBR preview reads it: N normalised,
142
+ * T = the interpolated tangent made perpendicular to N and normalised, B = w · cross(N, T) with w the sign of the
143
+ * interpolated handedness. Fills out[0..8] with T, B, N; returns false (out untouched) when T is parallel to N.
144
+ */
145
+ export function shadingFrame(nx, ny, nz, tx, ty, tz, w, out) {
146
+ const nl = Math.hypot(nx, ny, nz);
147
+ if (!(nl > 0))
148
+ return false;
149
+ nx /= nl;
150
+ ny /= nl;
151
+ nz /= nl;
152
+ const d = tx * nx + ty * ny + tz * nz;
153
+ tx -= nx * d;
154
+ ty -= ny * d;
155
+ tz -= nz * d;
156
+ const tl = Math.hypot(tx, ty, tz);
157
+ if (!(tl > 1e-12))
158
+ return false;
159
+ tx /= tl;
160
+ ty /= tl;
161
+ tz /= tl;
162
+ const sg = w < 0 ? -1 : 1;
163
+ out[0] = tx;
164
+ out[1] = ty;
165
+ out[2] = tz;
166
+ out[3] = (ny * tz - nz * ty) * sg;
167
+ out[4] = (nz * tx - nx * tz) * sg;
168
+ out[5] = (nx * ty - ny * tx) * sg;
169
+ out[6] = nx;
170
+ out[7] = ny;
171
+ out[8] = nz;
172
+ return true;
173
+ }
174
+ /** The standard tangent attribute: float, 4 components (xyz unit tangent, w = ±1 handedness), point or vertex class. */
175
+ export const TANGENT_ATTRIB = 'tangent';
176
+ /**
177
+ * Check a supplied tangent attribute: every element finite, |xyz| within 1e-3 of 1, w exactly ±1. Returns null when
178
+ * valid, else a description of the first problem (element class, index and value).
179
+ */
180
+ export function tangentProblem(g) {
181
+ const f = g.findAttrib(TANGENT_ATTRIB, ['vertex', 'point']);
182
+ if (!f)
183
+ return null;
184
+ const a = f.attr;
185
+ if (a.type !== 'float' || a.isArray || a.size !== 4)
186
+ return `"${TANGENT_ATTRIB}" is ${a.isArray ? 'an array' : `${a.type}[${a.size}]`}, not float[4]`;
187
+ const d = a.data, n = f.cls === 'vertex' ? g.numVertices : g.numPoints;
188
+ for (let i = 0; i < n; i++) {
189
+ const x = d[i * 4], y = d[i * 4 + 1], z = d[i * 4 + 2], w = d[i * 4 + 3];
190
+ const l = Math.hypot(x, y, z);
191
+ if (!Number.isFinite(l) || Math.abs(l - 1) > 1e-3 || (w !== 1 && w !== -1))
192
+ return `${f.cls} ${i} has tangent (${[x, y, z, w].map((q) => +q.toPrecision(4)).join(', ')}): xyz must be unit length and w ±1`;
193
+ }
194
+ return null;
195
+ }
196
+ /**
197
+ * Transform tangent vectors in place by the 3×3 linear part L (column-major, 9 numbers): xyz → normalize(L · xyz),
198
+ * w → w · sign(det L) (a mirror flips the bitangent relative to cross(N, T)). sel limits the elements.
199
+ */
200
+ export function transformTangents(d, count, L, sel) {
201
+ const det = L[0] * (L[4] * L[8] - L[7] * L[5]) - L[3] * (L[1] * L[8] - L[7] * L[2]) + L[6] * (L[1] * L[5] - L[4] * L[2]);
202
+ const s = det < 0 ? -1 : 1;
203
+ for (let i = 0; i < count; i++) {
204
+ if (sel && !sel(i))
205
+ continue;
206
+ const x = d[i * 4], y = d[i * 4 + 1], z = d[i * 4 + 2];
207
+ const tx = L[0] * x + L[3] * y + L[6] * z, ty = L[1] * x + L[4] * y + L[7] * z, tz = L[2] * x + L[5] * y + L[8] * z;
208
+ const l = Math.hypot(tx, ty, tz) || 1;
209
+ d[i * 4] = tx / l;
210
+ d[i * 4 + 1] = ty / l;
211
+ d[i * 4 + 2] = tz / l;
212
+ d[i * 4 + 3] *= s;
213
+ }
214
+ }
@@ -0,0 +1,4 @@
1
+ /** TopoTopo v ↔ glTF v (the mapping is its own inverse). */
2
+ export declare const gltfV: (v: number) => number;
3
+ /** Continuous image row coordinate (0 = top edge of row 0, h = bottom edge of the last row) of TopoTopo v. */
4
+ export declare const imageRowOfV: (v: number, h: number) => number;