stack3js 0.2.0 → 0.6.4

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 (73) hide show
  1. package/COMMAND.md +145 -0
  2. package/README.md +167 -4
  3. package/bin/stack3.mjs +1386 -186
  4. package/blender/import_stack.py +89 -0
  5. package/meshing/blocks.py +82 -0
  6. package/meshing/branches.py +62 -0
  7. package/meshing/dexel.py +67 -0
  8. package/meshing/field_data.py +19 -0
  9. package/meshing/finish_blender.py +203 -0
  10. package/meshing/finishing.py +155 -0
  11. package/meshing/geometry.py +71 -0
  12. package/meshing/guided.py +150 -0
  13. package/meshing/implicit.py +178 -0
  14. package/meshing/intersection.py +33 -0
  15. package/meshing/material.py +115 -0
  16. package/meshing/mesh.py +103 -0
  17. package/meshing/network.py +136 -0
  18. package/meshing/regularization.py +213 -0
  19. package/meshing/sections.py +165 -0
  20. package/meshing/signed_distance.py +93 -0
  21. package/package.json +9 -2
  22. package/references/hard-surface/README.md +40 -0
  23. package/references/hard-surface/atlas/concrete-barrier-4view.png +0 -0
  24. package/references/hard-surface/atlas/preview.pipeline.yaml +14 -0
  25. package/references/hard-surface/case-studies/benchmark/README.md +22 -0
  26. package/references/hard-surface/case-studies/benchmark/lod-bevel.pipeline.yaml +258 -0
  27. package/references/hard-surface/finishing/exports.yaml +10 -0
  28. package/references/hard-surface/finishing/finish-lod.pipeline.yaml +33 -0
  29. package/references/hard-surface/finishing/inputs/stack/stack.json +1 -0
  30. package/references/hard-surface/finishing/inputs/stack/stack.png +0 -0
  31. package/references/hard-surface/finishing/regularize.pipeline.yaml +46 -0
  32. package/references/hard-surface/measured-depth/sdf/compare.pipeline.yaml +12 -0
  33. package/references/hard-surface/measured-depth/sdf/inputs/field.npy +0 -0
  34. package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.json +1 -0
  35. package/references/hard-surface/measured-depth/sdf/inputs/stack/stack.png +0 -0
  36. package/references/hard-surface/measured-depth/sdf/inputs/truth.json +1 -0
  37. package/references/hard-surface/measured-depth/sdf/sdf.guide.json +3 -0
  38. package/references/hard-surface/measured-depth/triple-dexel/compare.pipeline.yaml +12 -0
  39. package/references/hard-surface/measured-depth/triple-dexel/dexel.guide.json +3 -0
  40. package/references/hard-surface/measured-depth/triple-dexel/inputs/fixture.json +22 -0
  41. package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.json +22 -0
  42. package/references/hard-surface/measured-depth/triple-dexel/inputs/stack/stack.png +0 -0
  43. package/references/hard-surface/measured-depth/triple-dexel/inputs/triple-dexel.npz +0 -0
  44. package/references/hard-surface/schema/pipeline-fragment.schema.json +5 -0
  45. package/references/hard-surface/schema/pipeline.schema.json +181 -0
  46. package/schema/pipeline-fragment.schema.json +5 -0
  47. package/schema/pipeline.schema.json +181 -0
  48. package/verification/assembly.py +96 -0
  49. package/verification/landmarks.py +53 -0
  50. package/verification/panels.py +137 -0
  51. package/verification/projections.py +135 -0
  52. package/verification/verify.py +108 -0
  53. package/viewer/dist/assets/{GLTFExporter--hziUXc8.js → GLTFExporter-xdVCArY-.js} +1 -1
  54. package/viewer/dist/assets/compare-Du4RoRQO.js +6 -0
  55. package/viewer/dist/assets/compare.worker-CgJq-znx.js +21 -0
  56. package/viewer/dist/assets/presets-jXE0t1fU.js +1 -0
  57. package/viewer/dist/assets/preview-cache-BKV0EZl9.js +1 -0
  58. package/viewer/dist/assets/project-DtHHhfo-.js +17 -0
  59. package/viewer/dist/assets/reconstruct.worker-ONc9GyFO.js +21 -0
  60. package/viewer/dist/assets/{script-engine-CLj7QMLe.js → script-engine-Bs3azDYZ.js} +1 -1
  61. package/viewer/dist/assets/style-D6eZHs3D.js +4004 -0
  62. package/viewer/dist/assets/viewer-DIjS0No7.js +2 -0
  63. package/viewer/dist/compare.html +4 -4
  64. package/viewer/dist/index.html +9 -8
  65. package/viewer/dist/project.html +3 -3
  66. package/viewer/dist/assets/compare-DJ8rV3Rn.js +0 -6
  67. package/viewer/dist/assets/compare.worker-DK2lJl0n.js +0 -21
  68. package/viewer/dist/assets/presets-DwdZVYhs.js +0 -1
  69. package/viewer/dist/assets/preview-cache-DRF_H5pq.js +0 -58
  70. package/viewer/dist/assets/project-D8tR6U-_.js +0 -17
  71. package/viewer/dist/assets/reconstruct.worker-Cf8iZwT3.js +0 -21
  72. package/viewer/dist/assets/style-CWGgpweN.js +0 -3947
  73. package/viewer/dist/assets/viewer-CyGodHLY.js +0 -2
package/bin/stack3.mjs CHANGED
@@ -42,14 +42,19 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
42
42
  ));
43
43
 
44
44
  // packages/core/src/views.ts
45
- function readPngSize(bytes) {
45
+ function readPngDimensions(bytes) {
46
46
  const signature = [137, 80, 78, 71, 13, 10, 26, 10];
47
47
  if (bytes.length < 33 || signature.some((value, index) => bytes[index] !== value) || String.fromCharCode(...bytes.subarray(12, 16)) !== "IHDR") {
48
48
  throw new Error("Expected a PNG image.");
49
49
  }
50
50
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
51
51
  const width = view.getUint32(16), height = view.getUint32(20);
52
- if (!width || !height || width > 8192 || height > 8192 || width * height > 16e6) {
52
+ if (!width || !height || !Number.isSafeInteger(width * height * 4)) throw new Error("Invalid PNG dimensions.");
53
+ return { width, height };
54
+ }
55
+ function readPngSize(bytes) {
56
+ const { width, height } = readPngDimensions(bytes);
57
+ if (width > 8192 || height > 8192 || width * height > 16e6) {
53
58
  throw new Error("PNG dimensions exceed the 8192 px or 16 MP input limit.");
54
59
  }
55
60
  return { width, height };
@@ -190,7 +195,12 @@ function inspectViews(views) {
190
195
  if (Math.abs(expected / observed - 1) > 0.2) warnings.push("Top, left, and front proportions differ by more than 20%. Check alignment.");
191
196
  if (Math.abs(rear.width / rear.height / observed - 1) > 0.2) warnings.push("Front and rear proportions differ by more than 20%.");
192
197
  const mapped = Object.entries(views).map(([direction, raster]) => ({ direction, width: raster.width, height: raster.height }));
193
- return { views: mapped, warnings };
198
+ const nativeSamples = {
199
+ x: Math.max(top.width, front.width, rear.width, views.bottom?.width ?? 0),
200
+ y: Math.max(top.height, left.width, views.right?.width ?? 0, views.bottom?.height ?? 0),
201
+ z: Math.max(left.height, front.height, rear.height, views.right?.height ?? 0)
202
+ };
203
+ return { views: mapped, nativeSamples, warnings };
194
204
  }
195
205
  var DIRECTIONS;
196
206
  var init_views = __esm({
@@ -200,6 +210,26 @@ var init_views = __esm({
200
210
  }
201
211
  });
202
212
 
213
+ // packages/core/src/sampling.ts
214
+ function samplingGrid(width, depth, resolution, layers) {
215
+ if (!Number.isSafeInteger(layers) || layers < 8) throw new Error("Layers must be a safe integer of at least 8.");
216
+ if (!Number.isSafeInteger(resolution) || resolution < 16) throw new Error("Resolution must be a safe integer of at least 16.");
217
+ const longest = Math.max(width, depth);
218
+ const columns2 = Math.max(2, Math.round(width / longest * resolution));
219
+ const rows = Math.max(2, Math.round(depth / longest * resolution));
220
+ if (!Number.isSafeInteger(columns2 * rows * layers * 4)) {
221
+ throw new Error("Requested grid is too large to address its RGBA samples.");
222
+ }
223
+ return { width: columns2, depth: rows, layers };
224
+ }
225
+ var DEFAULT_LAYERS;
226
+ var init_sampling = __esm({
227
+ "packages/core/src/sampling.ts"() {
228
+ "use strict";
229
+ DEFAULT_LAYERS = 128;
230
+ }
231
+ });
232
+
203
233
  // packages/core/src/texture-projection.ts
204
234
  function visibleFromAbove(mesh, bins) {
205
235
  const { positions: p, indices, size } = mesh;
@@ -241,7 +271,7 @@ function visibleFromAbove(mesh, bins) {
241
271
  }
242
272
  function projectUpperContour(mesh, plan, resolution, layers) {
243
273
  const { positions: p, normals, uvs, indices, texture, size } = mesh;
244
- resolution = Math.max(1, Math.min(192, Math.round(resolution) || 96));
274
+ resolution = Math.max(1, Math.min(Math.max(plan.width, plan.height), Math.round(resolution) || 96));
245
275
  const visible = visibleFromAbove(mesh, resolution);
246
276
  const axis = size[1] >= size[0] ? 2 : 0;
247
277
  const span = axis === 2 ? size[1] : size[0];
@@ -1668,7 +1698,7 @@ function inferSurfaceDepth(volume, size, directions) {
1668
1698
  const [axis, high] = depthAxes[direction];
1669
1699
  const plane = axes.filter((item) => item !== axis);
1670
1700
  const width = size[plane[0]], height = size[plane[1]];
1671
- const values = new Int16Array(width * height).fill(-1);
1701
+ const values = new Int32Array(width * height).fill(-1);
1672
1702
  const p = [0, 0, 0];
1673
1703
  for (let v = 0; v < height; v++) for (let u = 0; u < width; u++) {
1674
1704
  p[plane[0]] = u;
@@ -1820,7 +1850,7 @@ function regularizeDepth(occupancy, shape, pitch) {
1820
1850
  }
1821
1851
  return current;
1822
1852
  }
1823
- function extractSurface(volume, width, depth, layers, worldSize) {
1853
+ function paddedOccupancy(volume, width, depth, layers) {
1824
1854
  const nx = width + 2, ny = depth + 2, nz = layers + 2;
1825
1855
  const plane = nx * ny, count2 = plane * nz;
1826
1856
  const occupancy = new Uint8Array(count2);
@@ -1828,6 +1858,10 @@ function extractSurface(volume, width, depth, layers, worldSize) {
1828
1858
  const start = (z * depth + y) * width;
1829
1859
  occupancy.set(volume.subarray(start, start + width), (z + 1) * plane + (y + 1) * nx + 1);
1830
1860
  }
1861
+ return { nx, ny, nz, plane, count: count2, occupancy };
1862
+ }
1863
+ function extractSurface(volume, width, depth, layers, worldSize) {
1864
+ const { nx, ny, nz, plane, count: count2, occupancy } = paddedOccupancy(volume, width, depth, layers);
1831
1865
  const field = worldSize ? regularizeDepth(occupancy, [nx, ny, nz], [worldSize[0] / width, worldSize[1] / depth, worldSize[2] / layers]) : new Float32Array(count2);
1832
1866
  for (let z = 0; z < nz; z++) for (let y = 0; y < ny; y++) for (let x2 = 0; x2 < nx; x2++) {
1833
1867
  const index = z * plane + y * nx + x2;
@@ -1870,6 +1904,101 @@ function extractSurface(volume, width, depth, layers, worldSize) {
1870
1904
  }
1871
1905
  return { positions, gradients, indices };
1872
1906
  }
1907
+ function extractVoxelSurface(volume, width, depth, layers) {
1908
+ const dimensions = [width, depth, layers];
1909
+ const strides = [1, width, width * depth];
1910
+ const positions = [], gradients = [], indices = [];
1911
+ const corners = [[0, 0], [1, 0], [1, 1], [0, 1]];
1912
+ for (let z = 0; z < layers; z++) for (let y = 0; y < depth; y++) for (let x2 = 0; x2 < width; x2++) {
1913
+ const index = (z * depth + y) * width + x2;
1914
+ if (!volume[index]) continue;
1915
+ const cell = [x2, y, z];
1916
+ for (let axis = 0; axis < 3; axis++) {
1917
+ const u = (axis + 1) % 3, v = (axis + 2) % 3;
1918
+ for (const sign of [-1, 1]) {
1919
+ const neighbor = cell[axis] + sign;
1920
+ if (neighbor >= 0 && neighbor < dimensions[axis] && volume[index + sign * strides[axis]]) continue;
1921
+ const normal = [0, 0, 0];
1922
+ normal[axis] = sign;
1923
+ const base = positions.length / 3;
1924
+ for (const [du, dv] of corners) {
1925
+ const vertex = [...cell];
1926
+ vertex[axis] += Number(sign > 0);
1927
+ vertex[u] += du;
1928
+ vertex[v] += dv;
1929
+ positions.push(...vertex);
1930
+ gradients.push(...normal);
1931
+ }
1932
+ const a = base, b = base + 1, c = base + 2, d = base + 3;
1933
+ if (sign > 0) indices.push(a, b, c, a, c, d);
1934
+ else indices.push(a, c, b, a, d, c);
1935
+ }
1936
+ }
1937
+ }
1938
+ return { positions, gradients, indices };
1939
+ }
1940
+ function extractSurfaceNets(volume, width, depth, layers) {
1941
+ const { nx, ny, nz, plane, count: count2, occupancy } = paddedOccupancy(volume, width, depth, layers);
1942
+ const strides = [1, nx, plane];
1943
+ const corners = CORNERS.map(([x2, y, z]) => x2 + nx * y + plane * z);
1944
+ const vertexAt = new Int32Array(count2);
1945
+ const positions = [], gradients = [], indices = [];
1946
+ function faceNormal(a, b, c) {
1947
+ const ax = positions[b * 3] - positions[a * 3];
1948
+ const ay = positions[b * 3 + 1] - positions[a * 3 + 1];
1949
+ const az = positions[b * 3 + 2] - positions[a * 3 + 2];
1950
+ const bx = positions[c * 3] - positions[a * 3];
1951
+ const by = positions[c * 3 + 1] - positions[a * 3 + 1];
1952
+ const bz = positions[c * 3 + 2] - positions[a * 3 + 2];
1953
+ return [ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx];
1954
+ }
1955
+ function triangle(a, b, c) {
1956
+ indices.push(a, b, c);
1957
+ const [nx2, ny2, nz2] = faceNormal(a, b, c);
1958
+ for (const i2 of [a, b, c]) {
1959
+ gradients[i2 * 3] += nx2;
1960
+ gradients[i2 * 3 + 1] += ny2;
1961
+ gradients[i2 * 3 + 2] += nz2;
1962
+ }
1963
+ }
1964
+ for (let z = 0; z < nz - 1; z++) for (let y = 0; y < ny - 1; y++) for (let x2 = 0; x2 < nx - 1; x2++) {
1965
+ const cell = z * plane + y * nx + x2;
1966
+ let mask = 0;
1967
+ for (let i2 = 0; i2 < 8; i2++) mask |= occupancy[cell + corners[i2]] << i2;
1968
+ if (mask === 0 || mask === 255) continue;
1969
+ let sx = 0, sy = 0, sz = 0, crossings = 0;
1970
+ for (const [a2, b] of EDGES) {
1971
+ if ((mask >> a2 & 1) === (mask >> b & 1)) continue;
1972
+ sx += (CORNERS[a2][0] + CORNERS[b][0]) / 2;
1973
+ sy += (CORNERS[a2][1] + CORNERS[b][1]) / 2;
1974
+ sz += (CORNERS[a2][2] + CORNERS[b][2]) / 2;
1975
+ crossings++;
1976
+ }
1977
+ const a = positions.length / 3;
1978
+ vertexAt[cell] = a;
1979
+ positions.push(x2 - 0.5 + sx / crossings, y - 0.5 + sy / crossings, z - 0.5 + sz / crossings);
1980
+ gradients.push(0, 0, 0);
1981
+ for (let axis = 0; axis < 3; axis++) {
1982
+ if (occupancy[cell] === occupancy[cell + strides[axis]]) continue;
1983
+ const u = strides[(axis + 1) % 3], v = strides[(axis + 2) % 3];
1984
+ const b = vertexAt[cell - u], c = vertexAt[cell - u - v], d = vertexAt[cell - v];
1985
+ if (occupancy[cell]) {
1986
+ triangle(a, b, c);
1987
+ triangle(a, c, d);
1988
+ } else {
1989
+ triangle(a, d, c);
1990
+ triangle(a, c, b);
1991
+ }
1992
+ }
1993
+ }
1994
+ for (let i2 = 0; i2 < indices.length; i2++) {
1995
+ const p = indices[i2] * 3;
1996
+ if (Math.abs(gradients[p]) + Math.abs(gradients[p + 1]) + Math.abs(gradients[p + 2]) > 1e-10) continue;
1997
+ const start = i2 - i2 % 3;
1998
+ [gradients[p], gradients[p + 1], gradients[p + 2]] = faceNormal(indices[start], indices[start + 1], indices[start + 2]);
1999
+ }
2000
+ return { positions, gradients, indices };
2001
+ }
1873
2002
  var CORNERS, EDGES;
1874
2003
  var init_surface = __esm({
1875
2004
  "packages/core/src/surface.ts"() {
@@ -1935,27 +2064,23 @@ function rankedViews(views, nx, ny, nz) {
1935
2064
  if (!views.bottom) weights[0] = Math.abs(nz);
1936
2065
  return [...DIRECTIONS].filter((direction) => views[direction]).sort((a, b) => weights[DIRECTIONS.indexOf(b)] - weights[DIRECTIONS.indexOf(a)]);
1937
2066
  }
1938
- function dimensions(views, settings) {
2067
+ function reconstructionDimensions(views, settings) {
1939
2068
  const top = views.top, front = views.front, left = views.left;
1940
- const layers = settings.layers ?? 48;
2069
+ const layers = settings.layers ?? DEFAULT_LAYERS;
1941
2070
  const resolution = settings.resolution ?? 96;
1942
2071
  const height = settings.height ?? 1;
1943
- if (!Number.isInteger(layers) || layers < 8 || layers > 128) throw new Error("Layers must be an integer from 8 to 128.");
1944
- if (!Number.isInteger(resolution) || resolution < 16 || resolution > 192) throw new Error("Resolution must be an integer from 16 to 192.");
1945
2072
  if (!Number.isFinite(height) || height <= 0) throw new Error("Height must be positive.");
1946
2073
  if (settings.pivot && settings.pivot !== "center" && settings.pivot !== "ground") throw new Error("Pivot must be ground or center.");
1947
2074
  const depthFromView = left.width / left.height * height;
1948
2075
  const [x2, y, z] = settings.size ?? [(front.width / front.height * height + depthFromView * top.width / top.height) / 2, depthFromView, height];
1949
2076
  if (![x2, y, z].every((value) => Number.isFinite(value) && value > 0)) throw new Error("Part dimensions must be positive.");
1950
- const width = Math.max(2, Math.round(x2 / Math.max(x2, y) * resolution));
1951
- const depth = Math.max(2, Math.round(y / Math.max(x2, y) * resolution));
2077
+ const { width, depth } = samplingGrid(x2, y, resolution, layers);
1952
2078
  const size = [x2, y, z];
1953
2079
  const pivot = [0, 0, settings.pivot === "center" ? z / 2 : 0];
1954
2080
  return { width, depth, layers, size, pivot };
1955
2081
  }
1956
2082
  function grid(views, settings, fallback) {
1957
- const { width, depth, layers, size, pivot } = dimensions(views, settings);
1958
- if (width * depth * layers > 3e6) throw new Error("The grid is too large. Reduce layers or XY resolution.");
2083
+ const { width, depth, layers, size, pivot } = reconstructionDimensions(views, settings);
1959
2084
  const aligned = {};
1960
2085
  for (const direction of DIRECTIONS) {
1961
2086
  const view = views[direction];
@@ -2027,12 +2152,13 @@ function textureAtlas(views, accentViews = {}, bleed = false) {
2027
2152
  }
2028
2153
  return { tiles, accents, texture: { width, height, data } };
2029
2154
  }
2030
- function makeMesh(g, views, mode = "rgb") {
2155
+ function makeMesh(g, views, mode = "rgb", method = "marching-cubes") {
2031
2156
  const { width, depth, layers, size, pivot, volume } = g;
2032
- const surface = extractSurface(volume, width, depth, layers, mode === "depth" ? size : void 0);
2157
+ const extract2 = { "marching-cubes": extractSurface, "surface-nets": extractSurfaceNets, voxel: extractVoxelSurface }[method];
2158
+ const surface = extract2(volume, width, depth, layers, mode === "depth" ? size : void 0);
2033
2159
  if (!surface.indices.length && mode === "depth") return makeMesh(g, views, "id");
2034
- const roof = new Int16Array(width * depth).fill(-1);
2035
- const floor = new Int16Array(width * depth).fill(layers);
2160
+ const roof = new Int32Array(width * depth).fill(-1);
2161
+ const floor = new Int32Array(width * depth).fill(layers);
2036
2162
  const area3 = width * depth;
2037
2163
  for (let z = 0; z < layers; z++) for (let i2 = 0; i2 < area3; i2++) {
2038
2164
  if (!volume[z * area3 + i2]) continue;
@@ -2117,7 +2243,7 @@ function makeMesh(g, views, mode = "rgb") {
2117
2243
  cache.set(key, index);
2118
2244
  const p = original * 3;
2119
2245
  const x2 = surface.positions[p] / width, y = surface.positions[p + 1] / depth, z = surface.positions[p + 2] / layers;
2120
- positions.push((x2 - 0.5) * size[0], z * size[2] - pivot[2], (0.5 - y) * size[1]);
2246
+ positions.push((x2 - 0.5) * size[0] - pivot[0], z * size[2] - pivot[2], (0.5 - y) * size[1] + pivot[1]);
2121
2247
  const nx = surface.gradients[p] * width / size[0], ny = surface.gradients[p + 1] * depth / size[1];
2122
2248
  const nz = surface.gradients[p + 2] * layers / size[2];
2123
2249
  const magnitude = Math.hypot(nx, ny, nz) || 1;
@@ -2143,13 +2269,50 @@ function makeMesh(g, views, mode = "rgb") {
2143
2269
  ...frontDecal?.mesh && { frontAccents: frontDecal.mesh }
2144
2270
  };
2145
2271
  }
2272
+ function meshFromStack(stack, method = "marching-cubes") {
2273
+ const { width, depth, layers, columns: columns2, spacing, pivot, texture } = stack;
2274
+ const size = [stack.size[0], stack.size[1], spacing * layers];
2275
+ const volume = new Uint8Array(width * depth * layers);
2276
+ const raster = (w, h) => ({ width: w, height: h, data: new Uint8Array(w * h * 4) });
2277
+ const views = {
2278
+ top: raster(width, depth),
2279
+ bottom: raster(width, depth),
2280
+ left: raster(depth, layers),
2281
+ right: raster(depth, layers),
2282
+ front: raster(width, layers),
2283
+ rear: raster(width, layers)
2284
+ };
2285
+ function paint(view, u, v, src, first) {
2286
+ const dst = (v * view.width + u) * 4;
2287
+ if (first && view.data[dst + 3]) return;
2288
+ for (let channel = 0; channel < 4; channel++) view.data[dst + channel] = texture.data[src + channel];
2289
+ }
2290
+ let occupied = 0;
2291
+ for (let z = 0; z < layers; z++) {
2292
+ const left = z % columns2 * width, top = Math.floor(z / columns2) * depth;
2293
+ for (let y = 0; y < depth; y++) for (let x2 = 0; x2 < width; x2++) {
2294
+ const src = ((top + y) * texture.width + left + x2) * 4;
2295
+ if (texture.data[src + 3] < 128) continue;
2296
+ volume[(z * depth + y) * width + x2] = 1;
2297
+ occupied++;
2298
+ paint(views.top, x2, y, src, false);
2299
+ paint(views.bottom, x2, depth - 1 - y, src, true);
2300
+ paint(views.left, depth - 1 - y, layers - 1 - z, src, true);
2301
+ paint(views.right, y, layers - 1 - z, src, false);
2302
+ paint(views.front, x2, layers - 1 - z, src, false);
2303
+ paint(views.rear, width - 1 - x2, layers - 1 - z, src, true);
2304
+ }
2305
+ }
2306
+ if (!occupied) throw new Error("The saved stack contains no occupied samples.");
2307
+ return makeMesh({ width, depth, layers, volume, size, pivot, aligned: views }, views, "rgb", method);
2308
+ }
2146
2309
  function makeStack(g, views) {
2147
2310
  const { width, depth, layers, size, pivot, volume } = g;
2148
2311
  const columns2 = Math.min(layers, Math.max(1, Math.floor(4096 / width)));
2149
2312
  const imageWidth = width * columns2, imageHeight = depth * Math.ceil(layers / columns2);
2150
2313
  const data = new Uint8Array(imageWidth * imageHeight * 4);
2151
2314
  const filled = (x2, y, z) => Number(x2 >= 0 && x2 < width && y >= 0 && y < depth && z >= 0 && z < layers && volume[(z * depth + y) * width + x2] > 0);
2152
- const roof = new Int16Array(width * depth).fill(-1);
2315
+ const roof = new Int32Array(width * depth).fill(-1);
2153
2316
  for (let z = 0; z < layers; z++) for (let i2 = 0; i2 < roof.length; i2++) {
2154
2317
  if (volume[z * roof.length + i2]) roof[i2] = z;
2155
2318
  }
@@ -2205,13 +2368,10 @@ function makeStack(g, views) {
2205
2368
  texture: { width: imageWidth, height: imageHeight, data }
2206
2369
  };
2207
2370
  }
2208
- function reconstruct(input, target, settings = {}) {
2209
- return reconstructPrepared(prepareViews(input, settings.threshold), target, settings);
2210
- }
2211
2371
  function reconstructPrepared(views, target, settings) {
2212
2372
  let mesh;
2213
2373
  if (target === "mesh" && settings.meshMethod === "contour") {
2214
- const { size, pivot } = dimensions(views, settings);
2374
+ const { size, pivot } = reconstructionDimensions(views, settings);
2215
2375
  const { tiles, texture } = textureAtlas(views, {}, true);
2216
2376
  const front = views.front;
2217
2377
  const scale = Math.min(1, 1024 / Math.max(front.width, front.height));
@@ -2223,13 +2383,14 @@ function reconstructPrepared(views, target, settings) {
2223
2383
  mesh = makeMesh(g, views);
2224
2384
  }
2225
2385
  if (settings.textureProjection === "top-contour")
2226
- projectUpperContour(mesh, views.top, settings.resolution ?? 96, settings.layers ?? 48);
2386
+ projectUpperContour(mesh, views.top, settings.resolution ?? 96, settings.layers ?? DEFAULT_LAYERS);
2227
2387
  return mesh;
2228
2388
  }
2229
2389
  var clamp2;
2230
2390
  var init_reconstruct = __esm({
2231
2391
  "packages/core/src/reconstruct.ts"() {
2232
2392
  "use strict";
2393
+ init_sampling();
2233
2394
  init_texture_projection();
2234
2395
  init_contour();
2235
2396
  init_atlas_comparison();
@@ -2823,11 +2984,25 @@ function padded(bytes, pad = 0) {
2823
2984
  function asBytes(data) {
2824
2985
  return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
2825
2986
  }
2826
- function encodeGlb(mesh) {
2987
+ function encodeGlb(mesh, { lit, instances } = {}) {
2827
2988
  const sources = [asBytes(mesh.positions), asBytes(mesh.normals), asBytes(mesh.uvs), asBytes(mesh.indices), encodePng(mesh.texture)];
2989
+ const attributes = { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 };
2990
+ const count2 = mesh.positions.length / 3;
2991
+ const optionalAccessors = [];
2992
+ if (mesh.colors) {
2993
+ attributes.COLOR_0 = 4;
2994
+ optionalAccessors.push({ bufferView: sources.length, componentType: 5126, count: count2, type: "VEC4" });
2995
+ sources.push(asBytes(mesh.colors));
2996
+ }
2997
+ const instanceExtension = "EXT_mesh_gpu_instancing";
2998
+ const translation = instances?.length ? 4 + optionalAccessors.length : void 0;
2999
+ if (instances?.length) {
3000
+ optionalAccessors.push({ bufferView: sources.length, componentType: 5126, count: instances.length, type: "VEC3" });
3001
+ sources.push(asBytes(Float32Array.from(instances.flat())));
3002
+ }
2828
3003
  let offset = 0;
2829
3004
  const bufferViews = sources.map((source, index) => {
2830
- const target = index < 3 ? 34962 : index === 3 ? 34963 : void 0;
3005
+ const target = index === 3 ? 34963 : index === 4 ? void 0 : 34962;
2831
3006
  const entry = { buffer: 0, byteOffset: offset, byteLength: source.length, target };
2832
3007
  offset += align(source.length);
2833
3008
  return entry;
@@ -2837,23 +3012,32 @@ function encodeGlb(mesh) {
2837
3012
  min[i2 % 3] = Math.min(min[i2 % 3], mesh.positions[i2]);
2838
3013
  max2[i2 % 3] = Math.max(max2[i2 % 3], mesh.positions[i2]);
2839
3014
  }
2840
- const count2 = mesh.positions.length / 3;
3015
+ const extensions = [...lit ? [] : ["KHR_materials_unlit"], ...translation === void 0 ? [] : [instanceExtension]];
2841
3016
  const json2 = padded(encoder.encode(JSON.stringify({
2842
3017
  asset: { version: "2.0", generator: "stack3.js" },
2843
- extensionsUsed: ["KHR_materials_unlit"],
3018
+ extensionsUsed: extensions.length ? extensions : void 0,
3019
+ extensionsRequired: translation === void 0 ? void 0 : [instanceExtension],
2844
3020
  scene: 0,
2845
3021
  scenes: [{ nodes: [0] }],
2846
- nodes: [{ mesh: 0, extras: { size: mesh.size, pivot: mesh.pivot } }],
2847
- meshes: [{ primitives: [{ attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }, indices: 3, material: 0 }] }],
2848
- materials: [{ extensions: { KHR_materials_unlit: {} }, pbrMetallicRoughness: { baseColorTexture: { index: 0 } } }],
3022
+ nodes: [{
3023
+ mesh: 0,
3024
+ extras: { size: mesh.size, pivot: mesh.pivot },
3025
+ extensions: translation === void 0 ? void 0 : { [instanceExtension]: { attributes: { TRANSLATION: translation } } }
3026
+ }],
3027
+ meshes: [{ primitives: [{ attributes, indices: 3, material: 0 }] }],
3028
+ materials: [{
3029
+ extensions: lit ? void 0 : { KHR_materials_unlit: {} },
3030
+ pbrMetallicRoughness: { baseColorTexture: { index: 0 }, ...lit ? { metallicFactor: 0, roughnessFactor: 0.65 } : {} }
3031
+ }],
2849
3032
  textures: [{ source: 0, sampler: 0 }],
2850
- samplers: [{ magFilter: 9729, minFilter: 9729, wrapS: 33071, wrapT: 33071 }],
3033
+ samplers: [{ magFilter: mesh.nearestTexture ? 9728 : 9729, minFilter: mesh.nearestTexture ? 9728 : 9729, wrapS: 33071, wrapT: 33071 }],
2851
3034
  images: [{ mimeType: "image/png", bufferView: 4 }],
2852
3035
  accessors: [
2853
3036
  { bufferView: 0, componentType: 5126, count: count2, type: "VEC3", min, max: max2 },
2854
3037
  { bufferView: 1, componentType: 5126, count: count2, type: "VEC3" },
2855
3038
  { bufferView: 2, componentType: 5126, count: count2, type: "VEC2" },
2856
- { bufferView: 3, componentType: 5125, count: mesh.indices.length, type: "SCALAR" }
3039
+ { bufferView: 3, componentType: 5125, count: mesh.indices.length, type: "SCALAR" },
3040
+ ...optionalAccessors
2857
3041
  ],
2858
3042
  bufferViews,
2859
3043
  buffers: [{ byteLength: offset }]
@@ -2890,21 +3074,32 @@ function encodeStack(stack) {
2890
3074
  }
2891
3075
  };
2892
3076
  }
2893
- function readStackBundle(manifest, texture) {
3077
+ function stackMetadata(manifest, texture) {
2894
3078
  if (!manifest || typeof manifest !== "object") throw new Error("Expected a stack3 stack manifest.");
2895
3079
  const { version: version2, atlas, layout, layerOrder, axes: axes2, width, depth, layers, columns: columns2, spacing, size, pivot } = manifest;
2896
3080
  const dimension = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
2897
3081
  const vector2 = (value) => Array.isArray(value) && value.length === 3 && value.every(Number.isFinite);
2898
- if (version2 !== 1 || atlas !== "stack.png" || layout !== "row-major" || layerOrder !== "bottom-to-top" || axes2 !== "xy-ground-z-up-y-forward" || !dimension(width) || !dimension(depth) || !dimension(layers) || !dimension(columns2) || columns2 > layers || layers > 128 || !vector2(size) || size.some((value) => value <= 0) || !vector2(pivot) || typeof spacing !== "number" || !Number.isFinite(spacing) || spacing <= 0 || texture.width !== width * columns2 || texture.height !== depth * Math.ceil(layers / columns2) || texture.data.length !== texture.width * texture.height * 4) {
3082
+ if (version2 !== 1 || atlas !== "stack.png" || layout !== "row-major" || layerOrder !== "bottom-to-top" || axes2 !== "xy-ground-z-up-y-forward" || !dimension(width) || !dimension(depth) || !dimension(layers) || !dimension(columns2) || columns2 > layers || !Number.isSafeInteger(texture.width * texture.height * 4) || !vector2(size) || size.some((value) => value <= 0) || !vector2(pivot) || typeof spacing !== "number" || !Number.isFinite(spacing) || spacing <= 0 || texture.width !== width * columns2 || texture.height !== depth * Math.ceil(layers / columns2)) {
2899
3083
  throw new Error("The stack manifest does not match the PNG or uses an unsupported layout.");
2900
3084
  }
2901
- return { target: "stack", texture, width, depth, layers, columns: columns2, spacing, size, pivot };
3085
+ return { width, depth, layers, columns: columns2, spacing, size, pivot };
3086
+ }
3087
+ function readStackPngSize(bytes, manifest) {
3088
+ const dimensions = readPngDimensions(bytes);
3089
+ stackMetadata(manifest, dimensions);
3090
+ return dimensions;
3091
+ }
3092
+ function readStackBundle(manifest, texture) {
3093
+ const meta = stackMetadata(manifest, texture);
3094
+ if (texture.data.length !== texture.width * texture.height * 4) throw new Error("Invalid stack texture data length.");
3095
+ return { target: "stack", texture, ...meta };
2902
3096
  }
2903
3097
  var encoder, crcTable, align;
2904
3098
  var init_export = __esm({
2905
3099
  "packages/core/src/export.ts"() {
2906
3100
  "use strict";
2907
3101
  init_esm();
3102
+ init_views();
2908
3103
  encoder = new TextEncoder();
2909
3104
  crcTable = Uint32Array.from({ length: 256 }, (_, index) => {
2910
3105
  let value = index;
@@ -3317,11 +3512,12 @@ var nodeDefaults, number2, choice, string, boolean, idOrNull, vector, settingsFi
3317
3512
  var init_project = __esm({
3318
3513
  "packages/core/src/project.ts"() {
3319
3514
  "use strict";
3515
+ init_sampling();
3320
3516
  init_views();
3321
3517
  init_scripts();
3322
3518
  nodeDefaults = {
3323
3519
  format: "stack",
3324
- layers: 48,
3520
+ layers: DEFAULT_LAYERS,
3325
3521
  resolution: 96,
3326
3522
  spacing: 1,
3327
3523
  height: 1,
@@ -3343,8 +3539,8 @@ var init_project = __esm({
3343
3539
  meshMethod: choice("marching-cubes", "contour"),
3344
3540
  contourHub: boolean,
3345
3541
  format: choice("stack", "glb"),
3346
- layers: number2(8, 128, "integer"),
3347
- resolution: number2(16, 192, "integer"),
3542
+ layers: number2(8, Number.MAX_SAFE_INTEGER, "integer"),
3543
+ resolution: number2(16, Number.MAX_SAFE_INTEGER, "integer"),
3348
3544
  spacing: number2(0.05, 20),
3349
3545
  height: number2(0.01, 100),
3350
3546
  threshold: number2(0, 255, "integer"),
@@ -3559,6 +3755,7 @@ var init_depth_fit = __esm({
3559
3755
  var init_mapped_atlas = __esm({
3560
3756
  "packages/core/src/mapped-atlas.ts"() {
3561
3757
  "use strict";
3758
+ init_sampling();
3562
3759
  init_depth_png();
3563
3760
  init_depth_fit();
3564
3761
  init_surface();
@@ -3570,6 +3767,7 @@ var init_src = __esm({
3570
3767
  "packages/core/src/index.ts"() {
3571
3768
  "use strict";
3572
3769
  init_views();
3770
+ init_sampling();
3573
3771
  init_reconstruct();
3574
3772
  init_export();
3575
3773
  init_project();
@@ -3581,20 +3779,1010 @@ var init_src = __esm({
3581
3779
  }
3582
3780
  });
3583
3781
 
3782
+ // apps/cli/src/atlas-input.ts
3783
+ import { readFile } from "node:fs/promises";
3784
+ import { dirname, extname, resolve } from "node:path";
3785
+ import { PNG } from "pngjs";
3786
+ async function png(path) {
3787
+ const bytes = await readFile(path);
3788
+ readPngSize(bytes);
3789
+ const image = PNG.sync.read(bytes);
3790
+ return { width: image.width, height: image.height, data: image.data };
3791
+ }
3792
+ async function readInput(path, layout, threshold) {
3793
+ if (extname(path).toLowerCase() === ".png") {
3794
+ if (!layout) throw new Error("A PNG atlas needs an explicit --layout.");
3795
+ return splitAtlas(await png(path), parseLayout(layout), threshold);
3796
+ }
3797
+ if (extname(path).toLowerCase() !== ".json") throw new Error("Choose a PNG atlas or a JSON view manifest.");
3798
+ if (layout) throw new Error("View manifests define their directions in the views field.");
3799
+ const manifest = JSON.parse(await readFile(path, "utf8"));
3800
+ const views = manifest && typeof manifest === "object" && "views" in manifest ? manifest.views : null;
3801
+ if (!views || typeof views !== "object" || Array.isArray(views)) throw new Error("The manifest needs a views object.");
3802
+ const entries = Object.entries(views);
3803
+ parseLayout(entries.map(([name]) => name).join(","));
3804
+ return Object.fromEntries(await Promise.all(entries.map(async ([name, file]) => {
3805
+ if (!DIRECTIONS.includes(name) || typeof file !== "string" || !file) throw new Error(`Invalid view entry: ${name}`);
3806
+ return [name, await png(resolve(dirname(path), file))];
3807
+ })));
3808
+ }
3809
+ var init_atlas_input = __esm({
3810
+ "apps/cli/src/atlas-input.ts"() {
3811
+ "use strict";
3812
+ init_src();
3813
+ }
3814
+ });
3815
+
3816
+ // apps/cli/src/grid-build.ts
3817
+ import { totalmem } from "node:os";
3818
+ function buildFromPreparedViews(views, target, settings) {
3819
+ if (target === "stack" || settings.meshMethod !== "contour") {
3820
+ const { width, depth, layers } = reconstructionDimensions(views, settings);
3821
+ const { nativeSamples } = inspectViews(views);
3822
+ if (width > nativeSamples.x || depth > nativeSamples.y || layers > nativeSamples.z) {
3823
+ console.error(`Sampling ${width} \xD7 ${depth} \xD7 ${layers} from up to ${nativeSamples.x} \xD7 ${nativeSamples.y} \xD7 ${nativeSamples.z} source pixels along X, Y, Z. Oversampled axes reuse input pixels.`);
3824
+ }
3825
+ checkGridMemory(width, depth, layers, target);
3826
+ }
3827
+ return reconstructPrepared(views, target, settings);
3828
+ }
3829
+ function checkGridMemory(width, depth, layers, target) {
3830
+ const cells = width * depth * layers;
3831
+ const bytes = target === "stack" ? cells * 5 : cells + (width + 2) * (depth + 2) * (layers + 2) * 17;
3832
+ const budget = Math.min(totalmem(), process.constrainedMemory() || Infinity);
3833
+ if (bytes > budget) {
3834
+ throw new Error(`Grid ${width} \xD7 ${depth} \xD7 ${layers} needs at least ${Math.ceil(bytes / 2 ** 20)} MiB, exceeding the system memory budget. Reduce layers or resolution.`);
3835
+ }
3836
+ }
3837
+ var init_grid_build = __esm({
3838
+ "apps/cli/src/grid-build.ts"() {
3839
+ "use strict";
3840
+ init_src();
3841
+ }
3842
+ });
3843
+
3844
+ // apps/cli/src/blender.ts
3845
+ var blender_exports = {};
3846
+ __export(blender_exports, {
3847
+ blenderExecutable: () => blenderExecutable,
3848
+ openBlenderStack: () => openBlenderStack
3849
+ });
3850
+ import { execFile, spawn } from "node:child_process";
3851
+ import { existsSync } from "node:fs";
3852
+ import { link, mkdir, mkdtemp, rm } from "node:fs/promises";
3853
+ import { tmpdir } from "node:os";
3854
+ import { basename, dirname as dirname2, extname as extname2, join, resolve as resolve2 } from "node:path";
3855
+ import { fileURLToPath } from "node:url";
3856
+ import { promisify } from "node:util";
3857
+ function blenderExecutable() {
3858
+ const macApp = "/Applications/Blender.app/Contents/MacOS/Blender";
3859
+ return process.env.BLENDER_BIN || (process.platform === "darwin" && existsSync(macApp) ? macApp : "blender");
3860
+ }
3861
+ async function openBlenderStack(directory2, output, open2) {
3862
+ const blender = blenderExecutable();
3863
+ const script = fileURLToPath(new URL("../blender/import_stack.py", import.meta.url));
3864
+ const destination = output && resolve2(output);
3865
+ if (destination && extname2(destination).toLowerCase() !== ".blend") throw new Error("Use a .blend output file.");
3866
+ if (destination && existsSync(destination)) throw new Error("Output already exists: " + destination);
3867
+ if (destination) await mkdir(dirname2(destination), { recursive: true });
3868
+ const scratch = await mkdtemp(join(destination ? dirname2(destination) : tmpdir(), "stack3-blender-"));
3869
+ const generated = join(scratch, (basename(directory2) || "stack") + ".blend");
3870
+ const scene = destination || generated;
3871
+ let keepPreview = false;
3872
+ try {
3873
+ await promisify(execFile)(blender, ["-b", "--factory-startup", "--python-exit-code", "1", "-P", script, "--", directory2, generated]);
3874
+ if (destination) await link(generated, destination);
3875
+ console.log("Blender scene " + scene);
3876
+ if (open2) {
3877
+ const child = spawn(blender, [scene], { detached: true, stdio: "ignore" });
3878
+ await new Promise((ok, fail) => {
3879
+ child.once("error", fail);
3880
+ child.once("spawn", ok);
3881
+ });
3882
+ child.unref();
3883
+ }
3884
+ keepPreview = !destination;
3885
+ } catch (error) {
3886
+ if (error.code === "ENOENT" && error.path === blender) {
3887
+ throw new Error("Blender was not found. Set BLENDER_BIN to its executable, or use stack3 view --web.");
3888
+ }
3889
+ throw error;
3890
+ } finally {
3891
+ if (!keepPreview) await rm(scratch, { recursive: true, force: true });
3892
+ }
3893
+ }
3894
+ var init_blender = __esm({
3895
+ "apps/cli/src/blender.ts"() {
3896
+ "use strict";
3897
+ }
3898
+ });
3899
+
3900
+ // apps/cli/src/part-mesh.ts
3901
+ import { execFile as execFile2 } from "node:child_process";
3902
+ import { mkdtemp as mkdtemp2, readFile as readFile2, rm as rm2, writeFile } from "node:fs/promises";
3903
+ import { tmpdir as tmpdir2 } from "node:os";
3904
+ import { dirname as dirname3, join as join2, resolve as resolve3 } from "node:path";
3905
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
3906
+ import { promisify as promisify2 } from "node:util";
3907
+ function isCoreMeshMethod(method) {
3908
+ return method === "marching-cubes" || method === "surface-nets" || method === "voxel";
3909
+ }
3910
+ function isStackMeshMethod(method) {
3911
+ return isCoreMeshMethod(method) || partMethods.some((name) => name === method);
3912
+ }
3913
+ async function readStackMesh(stack, method, guide, finish) {
3914
+ checkGridMemory(stack.width, stack.depth, stack.layers, "mesh");
3915
+ if (finish && isCoreMeshMethod(method)) throw new Error("Surface finishing needs a Python mesh method, such as hermite-dc or mc33.");
3916
+ return isCoreMeshMethod(method) ? meshFromStack(stack, method) : partMesh(stack, method, guide, finish);
3917
+ }
3918
+ async function partMesh(stack, method, guidePath, finish) {
3919
+ const guide = guidePath ? JSON.parse(await readFile2(guidePath, "utf8")) : {};
3920
+ const { width, depth, layers, columns: columns2, spacing, pivot } = stack;
3921
+ const size = [stack.size[0], stack.size[1], layers * spacing];
3922
+ const temporary = await mkdtemp2(join2(tmpdir2(), "stack3-part-"));
3923
+ try {
3924
+ await Promise.all([
3925
+ writeFile(join2(temporary, "stack.rgba"), stack.texture.data),
3926
+ writeFile(join2(temporary, "input.json"), JSON.stringify({
3927
+ width,
3928
+ depth,
3929
+ layers,
3930
+ columns: columns2,
3931
+ size,
3932
+ pivot,
3933
+ guide,
3934
+ guideDirectory: guidePath && dirname3(resolve3(guidePath)),
3935
+ finish,
3936
+ blender: finish && blenderExecutable()
3937
+ }))
3938
+ ]);
3939
+ const scriptName = method === "signed-distance-dc" ? "signed_distance.py" : "mesh.py";
3940
+ const script = fileURLToPath2(new URL("../meshing/" + scriptName, import.meta.url));
3941
+ const python = process.env.STACK3_PYTHON;
3942
+ const args = python ? [script] : ["run", "--no-project", "--script", script];
3943
+ try {
3944
+ const { stdout } = await promisify2(execFile2)(
3945
+ python || "uv",
3946
+ [...args, method, temporary],
3947
+ { env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } }
3948
+ );
3949
+ if (stdout.trim()) console.error(stdout.trim());
3950
+ } catch (error) {
3951
+ const e = error;
3952
+ throw new Error(e.code === "ENOENT" ? "Install uv or set STACK3_PYTHON to a Python environment with the meshing dependencies." : e.stderr?.trim() || e.message);
3953
+ }
3954
+ const read = async (name) => {
3955
+ const bytes = await readFile2(join2(temporary, name));
3956
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
3957
+ };
3958
+ const [positions, normals, uvs, indices, pixels, metadata] = await Promise.all(
3959
+ ["positions", "normals", "uvs", "indices", "texture", "output.json"].map(read)
3960
+ );
3961
+ const dims = JSON.parse(new TextDecoder().decode(metadata));
3962
+ const colors = dims.colors ? new Float32Array(await read("colors")) : void 0;
3963
+ return {
3964
+ target: "mesh",
3965
+ size,
3966
+ pivot,
3967
+ positions: new Float32Array(positions),
3968
+ normals: new Float32Array(normals),
3969
+ uvs: new Float32Array(uvs),
3970
+ indices: new Uint32Array(indices),
3971
+ ...colors && { colors },
3972
+ texture: {
3973
+ width: dims.width,
3974
+ height: dims.height,
3975
+ data: new Uint8Array(pixels)
3976
+ },
3977
+ nearestTexture: method === "greedy" || method === "monotone"
3978
+ };
3979
+ } finally {
3980
+ await rm2(temporary, { recursive: true, force: true });
3981
+ }
3982
+ }
3983
+ var partMethods;
3984
+ var init_part_mesh = __esm({
3985
+ "apps/cli/src/part-mesh.ts"() {
3986
+ "use strict";
3987
+ init_src();
3988
+ init_grid_build();
3989
+ init_blender();
3990
+ partMethods = [
3991
+ "section-loft",
3992
+ "heightfield",
3993
+ "smooth-loft",
3994
+ "revolve",
3995
+ "extended-mc",
3996
+ "hermite-dc",
3997
+ "mc33",
3998
+ "branch-loft",
3999
+ "path-sweep",
4000
+ "section-network",
4001
+ "greedy",
4002
+ "monotone",
4003
+ "signed-distance-dc"
4004
+ ];
4005
+ }
4006
+ });
4007
+
4008
+ // apps/cli/src/stack-input.ts
4009
+ import { readFile as readFile3 } from "node:fs/promises";
4010
+ import { join as join3 } from "node:path";
4011
+ import { PNG as PNG2 } from "pngjs";
4012
+ async function loadStack(directory2) {
4013
+ const [metadata, png2] = await Promise.all([
4014
+ readFile3(join3(directory2, "stack.json"), "utf8"),
4015
+ readFile3(join3(directory2, "stack.png"))
4016
+ ]);
4017
+ const manifest = JSON.parse(metadata);
4018
+ readStackPngSize(png2, manifest);
4019
+ const stack = readStackBundle(manifest, PNG2.sync.read(png2));
4020
+ return { metadata, png: png2, stack };
4021
+ }
4022
+ var init_stack_input = __esm({
4023
+ "apps/cli/src/stack-input.ts"() {
4024
+ "use strict";
4025
+ init_src();
4026
+ }
4027
+ });
4028
+
4029
+ // apps/cli/src/build-cache.ts
4030
+ import { createHash, randomUUID } from "node:crypto";
4031
+ import { mkdir as mkdir2, readdir, readFile as readFile4, rename, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
4032
+ import { homedir } from "node:os";
4033
+ import { join as join4, resolve as resolve4 } from "node:path";
4034
+ import { deserialize, serialize } from "node:v8";
4035
+ async function readCache(key) {
4036
+ try {
4037
+ return deserialize(await readFile4(join4(directory, key + ".cache")));
4038
+ } catch {
4039
+ }
4040
+ }
4041
+ function buildCacheKey(views, format, settings, spacing) {
4042
+ const hash = createHash("sha256");
4043
+ hash.update(JSON.stringify([version, format, settings, spacing]));
4044
+ for (const direction of DIRECTIONS) {
4045
+ const view = views[direction];
4046
+ if (!view) continue;
4047
+ hash.update(JSON.stringify([direction, view.width, view.height]));
4048
+ hash.update(view.data);
4049
+ }
4050
+ return hash.digest("hex");
4051
+ }
4052
+ async function readBuildCache(key, format) {
4053
+ const data = await readCache(key);
4054
+ if (data?.format !== format) return;
4055
+ if (data.format === "glb" ? data.bytes instanceof Uint8Array : data.png instanceof Uint8Array && typeof data.manifest === "string") return data;
4056
+ }
4057
+ async function readSurfaceCache(key) {
4058
+ const data = await readCache(key);
4059
+ if (data?.format === "surface" && data.mesh?.positions instanceof Float32Array && data.mesh.indices instanceof Uint32Array) return data.mesh;
4060
+ }
4061
+ async function writeBuildCache(key, output) {
4062
+ const temporary = join4(directory, randomUUID() + ".tmp");
4063
+ try {
4064
+ await mkdir2(directory, { recursive: true });
4065
+ await writeFile2(temporary, serialize(output), { flag: "wx" });
4066
+ await rename(temporary, join4(directory, key + ".cache"));
4067
+ const entries = (await readdir(directory)).filter((name) => /^[0-9a-f]{64}\.cache$/.test(name));
4068
+ if (entries.length <= 12) return;
4069
+ const dated = await Promise.all(entries.map(async (name) => ({ name, time: (await stat(join4(directory, name))).mtimeMs })));
4070
+ await Promise.all(dated.sort((a, b) => b.time - a.time).slice(12).map(({ name }) => unlink(join4(directory, name))));
4071
+ } catch {
4072
+ await unlink(temporary).catch(() => {
4073
+ });
4074
+ }
4075
+ }
4076
+ var version, directory;
4077
+ var init_build_cache = __esm({
4078
+ "apps/cli/src/build-cache.ts"() {
4079
+ "use strict";
4080
+ init_src();
4081
+ version = "render-data-4";
4082
+ directory = process.env.STACK3_CACHE_DIR ? resolve4(process.env.STACK3_CACHE_DIR) : join4(process.env.XDG_CACHE_HOME || join4(homedir(), ".cache"), "stack3", version);
4083
+ }
4084
+ });
4085
+
4086
+ // apps/cli/src/capabilities.ts
4087
+ var capabilities_exports = {};
4088
+ __export(capabilities_exports, {
4089
+ capabilitiesCommand: () => capabilitiesCommand,
4090
+ printPipelineSchema: () => printPipelineSchema
4091
+ });
4092
+ import { existsSync as existsSync2 } from "node:fs";
4093
+ import { readFile as readFile5 } from "node:fs/promises";
4094
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
4095
+ import { parseArgs } from "node:util";
4096
+ async function printPipelineSchema(kind) {
4097
+ if (kind !== "recipe" && kind !== "fragment") throw new Error("Use stack3 pipeline schema [recipe|fragment].");
4098
+ const recipe = await readFile5(schemaFiles.recipe, "utf8");
4099
+ if (kind === "recipe") {
4100
+ process.stdout.write(recipe);
4101
+ return;
4102
+ }
4103
+ const fragment = JSON.parse(await readFile5(schemaFiles.fragment, "utf8"));
4104
+ const definitions = JSON.parse(recipe).$defs;
4105
+ process.stdout.write(JSON.stringify({ ...fragment, $ref: "#/$defs/manifest", $defs: definitions }, null, 2) + "\n");
4106
+ }
4107
+ function sampleRoot() {
4108
+ const packaged = new URL("../references/hard-surface/", import.meta.url);
4109
+ return existsSync2(packaged) ? packaged : new URL("../../../skills/stack3/references/hard-surface/", import.meta.url);
4110
+ }
4111
+ function catalog() {
4112
+ const root = sampleRoot();
4113
+ return {
4114
+ version: 1,
4115
+ pipeline: {
4116
+ commands: { render: "stack3 pipeline render", run: "stack3 pipeline run", schema: "stack3 pipeline schema [recipe|fragment]" },
4117
+ nodes: {
4118
+ "load-stack": { output: "stack", backend: "node" },
4119
+ "reconstruct-stack": { output: "stack", backend: "node" },
4120
+ "extract-mesh": { input: "stack", output: "mesh", backend: "selected by method and finish options" },
4121
+ "write-glb": { input: "mesh", output: "glb", backend: "node" }
4122
+ },
4123
+ schemas: Object.fromEntries(Object.entries(schemaFiles).map(([kind, file]) => [kind, fileURLToPath3(file)]))
4124
+ },
4125
+ meshMethods: stackMethods.map((id) => ({
4126
+ id,
4127
+ backend: isCoreMeshMethod(id) ? "node" : "python",
4128
+ supportsFinish: !isCoreMeshMethod(id),
4129
+ ...meshInfo[id],
4130
+ ...id === "signed-distance-dc" && { dependencies: ["gpytoolbox"] }
4131
+ })),
4132
+ stages,
4133
+ samples: samples.map(({ id, path, backends }) => ({ id, path: fileURLToPath3(new URL(path, root)), backends })),
4134
+ backendConfiguration: { python: "uv or STACK3_PYTHON", blender: "Blender executable or BLENDER_BIN" }
4135
+ };
4136
+ }
4137
+ function capabilitiesCommand(args) {
4138
+ const { values } = parseArgs({ args, options: { json: { type: "boolean" }, help: { type: "boolean", short: "h" } } });
4139
+ if (values.help) {
4140
+ console.log(help);
4141
+ return;
4142
+ }
4143
+ const data = catalog();
4144
+ if (values.json) {
4145
+ process.stdout.write(JSON.stringify(data, null, 2) + "\n");
4146
+ return;
4147
+ }
4148
+ console.log(help);
4149
+ console.log("\nPipeline nodes:", Object.keys(data.pipeline.nodes).join(", "));
4150
+ console.log("Mesh methods:", data.meshMethods.map(({ id }) => id).join(", "));
4151
+ console.log("\nGeometry and export stages");
4152
+ for (const { name, backend, options } of data.stages) console.log(` ${name} (${backend}) ${options.join(", ")}`);
4153
+ console.log("\nJSON Schemas");
4154
+ console.log(" stack3 pipeline schema recipe");
4155
+ console.log(" stack3 pipeline schema fragment");
4156
+ console.log("\nBundled recipes");
4157
+ for (const { id, path, backends } of data.samples) console.log(` ${id} (${backends.join(", ")})
4158
+ ${path}`);
4159
+ }
4160
+ var schemaFiles, meshInfo, stackMethods, stages, samples, help;
4161
+ var init_capabilities = __esm({
4162
+ "apps/cli/src/capabilities.ts"() {
4163
+ "use strict";
4164
+ init_part_mesh();
4165
+ schemaFiles = {
4166
+ recipe: new URL("../schema/pipeline.schema.json", import.meta.url),
4167
+ fragment: new URL("../schema/pipeline-fragment.schema.json", import.meta.url)
4168
+ };
4169
+ meshInfo = {
4170
+ "marching-cubes": { description: "Default interpolated surface from saved occupancy.", guideFields: [] },
4171
+ "surface-nets": { description: "Averaged dual mesh for fast previews.", guideFields: [] },
4172
+ voxel: { description: "Exposed voxel faces.", guideFields: [] },
4173
+ "section-loft": { description: "Connect sections with linear interpolation.", guideFields: ["axis", "stations"] },
4174
+ heightfield: { description: "Build top and bottom surfaces along one axis.", guideFields: ["axis"] },
4175
+ "smooth-loft": { description: "Connect sections with smooth interpolation.", guideFields: ["axis", "stations"] },
4176
+ revolve: { description: "Revolve a sampled meridian.", guideFields: ["axis", "origin", "segments"] },
4177
+ "extended-mc": { description: "Marching Cubes with QEF feature vertices.", guideFields: [] },
4178
+ "hermite-dc": { description: "Dual Contouring with QEF from estimated or supplied Hermite data.", guideFields: ["field", "dexel"] },
4179
+ mc33: { description: "Topology-aware Marching Cubes for ambiguous configurations.", guideFields: [] },
4180
+ "branch-loft": { description: "Connect sections through branch and merge events.", guideFields: ["axis"] },
4181
+ "path-sweep": { description: "Sweep a section along a specified path.", guideFields: ["path", "up", "profile"] },
4182
+ "section-network": { description: "Reconstruct using independently measured sections.", guideFields: ["sections", "tolerance"] },
4183
+ greedy: { description: "Merge adjoining voxel faces into rectangles.", guideFields: [] },
4184
+ monotone: { description: "Triangulate merged voxel surface regions.", guideFields: [] },
4185
+ "signed-distance-dc": { description: "Carrera Dual Contouring of Signed Distance Data.", guideFields: ["field", "outerIterations", "innerIterations"] }
4186
+ };
4187
+ stackMethods = ["marching-cubes", "surface-nets", "voxel", ...partMethods];
4188
+ stages = [
4189
+ {
4190
+ name: "Voxel Reconstruction",
4191
+ options: ["reconstruct-stack", "load-stack"],
4192
+ backend: "node",
4193
+ description: "Carve occupancy from calibrated silhouettes or reopen saved RGBA slices."
4194
+ },
4195
+ {
4196
+ name: "SDF and Normal Estimation",
4197
+ options: ["hermite-dc", "signed-distance-dc"],
4198
+ backend: "python",
4199
+ description: "Estimate normals or distances from occupancy, or use aligned SDF samples in guide.field."
4200
+ },
4201
+ {
4202
+ name: "Triple-Dexel Hermite Data",
4203
+ options: ["guide.dexel", "hermite-dc"],
4204
+ backend: "python",
4205
+ description: "Use axis-aligned crossing positions and outward normals from a registered NPZ."
4206
+ },
4207
+ {
4208
+ name: "Feature Segmentation and Plane Fitting",
4209
+ options: ["fitTolerance"],
4210
+ backend: "python",
4211
+ description: "Group adjacent faces by normal and fit supported planes with SVD."
4212
+ },
4213
+ {
4214
+ name: "Primitive Fitting",
4215
+ options: ["fitTolerance", "primitives"],
4216
+ backend: "python",
4217
+ description: "Fit supported spherical and cylindrical patches."
4218
+ },
4219
+ {
4220
+ name: "Feature Boundary Stitching",
4221
+ options: ["fitTolerance"],
4222
+ backend: "python",
4223
+ description: "Solve shared boundary vertices together while fitting patches."
4224
+ },
4225
+ {
4226
+ name: "Guided Geometry Regularization",
4227
+ options: ["regularization.tolerance", "regularization.features", "regularization.relations"],
4228
+ backend: "python",
4229
+ description: "Fit selected planes, rim circles, fixed-axis cylinders and polygons. Jointly optimize explicit plane relations."
4230
+ },
4231
+ {
4232
+ name: "Procedural Bevel",
4233
+ options: ["bevelWidth", "bevelSegments"],
4234
+ backend: "blender",
4235
+ description: "Bevel eligible edges in headless Blender."
4236
+ },
4237
+ {
4238
+ name: "Selective Rim Bevel after QEM",
4239
+ options: ["lodBevel.preTriangleBudget", "lodBevel.rims", "triangleBudget", "bevelWidth", "bevelSegments"],
4240
+ backend: "blender",
4241
+ description: "Reserve triangles with QEM, bevel specified circular rims, and verify the final budget and closed topology."
4242
+ },
4243
+ {
4244
+ name: "Mesh Optimization and LOD",
4245
+ options: ["dissolveAngle", "triangleBudget"],
4246
+ backend: "blender",
4247
+ description: "Apply planar dissolve and QEM with topology checks. Use separate branches for LODs."
4248
+ },
4249
+ {
4250
+ name: "Multi-view Texture Projection",
4251
+ options: ["extract-mesh"],
4252
+ backend: "node or python",
4253
+ description: "Project saved RGB from stack views onto the extracted surface."
4254
+ },
4255
+ {
4256
+ name: "Weighted Normals",
4257
+ options: ["extract-mesh", "finish"],
4258
+ backend: "python",
4259
+ description: "Use area-weighted normal accumulation and split hard creases for hard-surface outputs."
4260
+ },
4261
+ {
4262
+ name: "Ambient Occlusion",
4263
+ options: ["aoRadius"],
4264
+ backend: "blender",
4265
+ description: "Bake vertex AO for GLB COLOR_0."
4266
+ },
4267
+ {
4268
+ name: "GLB Export and GPU Instancing",
4269
+ options: ["write-glb", "lit", "instances"],
4270
+ backend: "node",
4271
+ description: "Write GLB and optional per-instance translations."
4272
+ }
4273
+ ];
4274
+ samples = [
4275
+ { id: "atlas-preview", path: "atlas/preview.pipeline.yaml", backends: ["node"] },
4276
+ { id: "finish-lod", path: "finishing/finish-lod.pipeline.yaml", backends: ["node", "python", "blender"] },
4277
+ { id: "guided-regularization", path: "finishing/regularize.pipeline.yaml", backends: ["node", "python"] },
4278
+ { id: "benchmark-beveled-lod", path: "case-studies/benchmark/lod-bevel.pipeline.yaml", backends: ["node", "python", "blender"] },
4279
+ { id: "triple-dexel", path: "measured-depth/triple-dexel/compare.pipeline.yaml", backends: ["node", "python"] },
4280
+ { id: "signed-distance", path: "measured-depth/sdf/compare.pipeline.yaml", backends: ["node", "python", "gpytoolbox"] }
4281
+ ];
4282
+ help = "Usage: stack3 capabilities [--json]\nList pipeline nodes, mesh methods, backends, schemas and runnable samples.";
4283
+ }
4284
+ });
4285
+
4286
+ // apps/cli/src/pipeline.ts
4287
+ var pipeline_exports = {};
4288
+ __export(pipeline_exports, {
4289
+ pipelineCommand: () => pipelineCommand
4290
+ });
4291
+ import { createHash as createHash2 } from "node:crypto";
4292
+ import { mkdir as mkdir3, readFile as readFile6, realpath, writeFile as writeFile3 } from "node:fs/promises";
4293
+ import { dirname as dirname4, extname as extname3, resolve as resolve5 } from "node:path";
4294
+ import { parseArgs as parseArgs2 } from "node:util";
4295
+ import { parse, stringify } from "yaml";
4296
+ function isMapping(value) {
4297
+ return !!value && typeof value === "object" && !Array.isArray(value);
4298
+ }
4299
+ function mapping(value, name, fields) {
4300
+ if (!isMapping(value)) throw new Error(`${name} must be a mapping.`);
4301
+ const invalid = fields && Object.keys(value).find((key) => !fields.includes(key));
4302
+ if (invalid) throw new Error(`${name} has unknown field ${invalid}.`);
4303
+ return value;
4304
+ }
4305
+ function requiredText(value, name) {
4306
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${name} must be a nonempty string.`);
4307
+ return value;
4308
+ }
4309
+ async function readYaml(path) {
4310
+ try {
4311
+ return parse(await readFile6(path, "utf8"), { maxAliasCount: 0 });
4312
+ } catch (error) {
4313
+ throw new Error(`${path}: ${error.message}`);
4314
+ }
4315
+ }
4316
+ function mergeValues(base, overrides) {
4317
+ const merged = { ...base, ...overrides };
4318
+ for (const [key, value] of Object.entries(overrides)) {
4319
+ if (Object.hasOwn(base, key) && isMapping(base[key]) && isMapping(value)) {
4320
+ Object.defineProperty(merged, key, { value: mergeValues(base[key], value) });
4321
+ }
4322
+ }
4323
+ return merged;
4324
+ }
4325
+ function renderValue(value, values, name) {
4326
+ if (Array.isArray(value)) return value.map((entry, i2) => renderValue(entry, values, `${name}[${i2}]`));
4327
+ if (isMapping(value)) return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, renderValue(entry, values, `${name}.${key}`)]));
4328
+ if (typeof value !== "string" || !value.includes("{{")) return value;
4329
+ const reference = /\{\{\s*\.Values\.([\w-]+(?:\.[\w-]+)*)\s*\}\}/g;
4330
+ const get = (path) => {
4331
+ let current = values;
4332
+ for (const key of path.split(".")) {
4333
+ if (!isMapping(current) || !Object.hasOwn(current, key)) throw new Error(`${name}: missing .Values.${path}.`);
4334
+ current = current[key];
4335
+ }
4336
+ if (!["number", "string", "boolean"].includes(typeof current)) throw new Error(`${name}: .Values.${path} must be a scalar.`);
4337
+ return current;
4338
+ };
4339
+ const match = [...value.matchAll(reference)];
4340
+ if (value.replace(reference, "").includes("{{")) throw new Error(`${name}: use {{ .Values.name }} references.`);
4341
+ if (match.length === 1 && value.trim() === match[0][0]) return get(match[0][1]);
4342
+ return value.replace(reference, (_full, path) => String(get(path)));
4343
+ }
4344
+ function optionalBoolean(value, name) {
4345
+ if (value === void 0 || typeof value === "boolean") return value;
4346
+ throw new Error(`${name} must be a boolean.`);
4347
+ }
4348
+ function xyzPoint(value, label) {
4349
+ if (!Array.isArray(value) || value.length !== 3 || value.some((v) => typeof v !== "number" || !Number.isFinite(v))) {
4350
+ throw new Error(`${label} must be three finite XYZ numbers.`);
4351
+ }
4352
+ return [value[0], value[1], value[2]];
4353
+ }
4354
+ function parseRegularization(value, name) {
4355
+ const options = mapping(value, name, ["tolerance", "features", "relations"]);
4356
+ const { tolerance } = options;
4357
+ if (typeof tolerance !== "number" || !Number.isFinite(tolerance) || tolerance <= 0) throw new Error(`${name}.tolerance must be positive.`);
4358
+ if (!Array.isArray(options.features) || !options.features.length) throw new Error(`${name}.features must be a nonempty list.`);
4359
+ const features = options.features.map((value2, index) => {
4360
+ const label = `${name}.features[${index}]`;
4361
+ const entry = mapping(value2, label);
4362
+ const id = requiredText(entry.id, `${label}.id`);
4363
+ const fields = (...keys) => mapping(entry, label, ["id", "type", ...keys]);
4364
+ const direction = (key) => {
4365
+ const result = xyzPoint(entry[key], `${label}.${key}`);
4366
+ if (!Math.hypot(...result)) throw new Error(`${label}.${key} must be nonzero.`);
4367
+ return result;
4368
+ };
4369
+ const bounds2 = () => {
4370
+ if (!Array.isArray(entry.bounds) || entry.bounds.length !== 2) throw new Error(`${label}.bounds must contain minimum and maximum XYZ points.`);
4371
+ const minimum = xyzPoint(entry.bounds[0], `${label}.bounds[0]`), maximum = xyzPoint(entry.bounds[1], `${label}.bounds[1]`);
4372
+ if (minimum.some((v, i2) => v > maximum[i2])) throw new Error(`${label}.bounds minimum must not exceed maximum.`);
4373
+ return [minimum, maximum];
4374
+ };
4375
+ if (entry.type === "plane") {
4376
+ fields("normal", "bounds");
4377
+ return { id, type: entry.type, normal: direction("normal"), bounds: bounds2() };
4378
+ }
4379
+ if (entry.type === "circle" || entry.type === "cylinder") {
4380
+ fields("center", "axis", "radius", ...entry.type === "cylinder" ? ["bounds"] : []);
4381
+ const { radius } = entry;
4382
+ if (typeof radius !== "number" || !Number.isFinite(radius) || radius <= 0) throw new Error(`${label}.radius must be positive.`);
4383
+ const seed = { id, center: xyzPoint(entry.center, `${label}.center`), axis: direction("axis"), radius };
4384
+ return entry.type === "circle" ? { ...seed, type: "circle" } : { ...seed, type: "cylinder", bounds: bounds2() };
4385
+ }
4386
+ if (entry.type === "polygon") {
4387
+ fields("corners");
4388
+ if (!Array.isArray(entry.corners) || entry.corners.length < 3) throw new Error(`${label}.corners needs at least three ordered XYZ points.`);
4389
+ return { id, type: "polygon", corners: entry.corners.map((v, i2) => xyzPoint(v, `${label}.corners[${i2}]`)) };
4390
+ }
4391
+ throw new Error(`${label}.type must be plane, circle, cylinder or polygon.`);
4392
+ });
4393
+ const featureTypes = new Map(features.map(({ id, type }) => [id, type]));
4394
+ if (featureTypes.size !== features.length) throw new Error(`${name}.features has a duplicate id.`);
4395
+ const rawRelations = options.relations === void 0 ? [] : options.relations;
4396
+ if (!Array.isArray(rawRelations)) throw new Error(`${name}.relations must be a list.`);
4397
+ const relations = rawRelations.map((value2, i2) => {
4398
+ const label = `${name}.relations[${i2}]`;
4399
+ const relation = mapping(value2, label, ["type", "features"]);
4400
+ const { type, features: pair } = relation;
4401
+ if (type !== "parallel" && type !== "perpendicular" && type !== "coplanar") throw new Error(`${label}.type must be parallel, perpendicular or coplanar.`);
4402
+ if (!Array.isArray(pair) || pair.length !== 2 || pair[0] === pair[1] || pair.some((id) => featureTypes.get(id) !== "plane")) {
4403
+ throw new Error(`${label}.features must name two different plane features.`);
4404
+ }
4405
+ return { type, features: [pair[0], pair[1]] };
4406
+ });
4407
+ return { tolerance, features, relations };
4408
+ }
4409
+ function parseLodBevel(value, name, finalBudget) {
4410
+ const options = mapping(value, name, ["preTriangleBudget", "rims"]);
4411
+ const { preTriangleBudget } = options;
4412
+ if (typeof preTriangleBudget !== "number" || !Number.isSafeInteger(preTriangleBudget) || preTriangleBudget < 4 || preTriangleBudget >= finalBudget) {
4413
+ throw new Error(`${name}.preTriangleBudget must be an integer of at least 4 and lower than finish.triangleBudget.`);
4414
+ }
4415
+ if (!Array.isArray(options.rims) || !options.rims.length) throw new Error(`${name}.rims must be a nonempty list.`);
4416
+ const rims = options.rims.map((value2, i2) => {
4417
+ const label = `${name}.rims[${i2}]`;
4418
+ const rim = mapping(value2, label, ["id", "axis", "center", "radius", "radialTolerance", "axialTolerance"]);
4419
+ const { axis } = rim;
4420
+ if (axis !== "x" && axis !== "y" && axis !== "z") throw new Error(`${label}.axis must be x, y or z.`);
4421
+ const positive = (key) => {
4422
+ const n = rim[key];
4423
+ if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) throw new Error(`${label}.${key} must be positive.`);
4424
+ return n;
4425
+ };
4426
+ return {
4427
+ id: requiredText(rim.id, `${label}.id`),
4428
+ axis,
4429
+ center: xyzPoint(rim.center, `${label}.center`),
4430
+ radius: positive("radius"),
4431
+ radialTolerance: positive("radialTolerance"),
4432
+ axialTolerance: positive("axialTolerance")
4433
+ };
4434
+ });
4435
+ if (new Set(rims.map((rim) => rim.id)).size !== rims.length) throw new Error(`${name}.rims has a duplicate id.`);
4436
+ return { preTriangleBudget, rims };
4437
+ }
4438
+ function parseFinish(value, id) {
4439
+ if (value === void 0) return;
4440
+ const limits = {
4441
+ fitTolerance: [0, Infinity],
4442
+ bevelWidth: [0, Infinity],
4443
+ bevelSegments: [0, 16],
4444
+ dissolveAngle: [0, 45],
4445
+ triangleBudget: [3, Infinity],
4446
+ aoRadius: [0, Infinity]
4447
+ };
4448
+ const config = mapping(value, `${id}.finish`, [...Object.keys(limits), "primitives", "regularization", "lodBevel"]);
4449
+ const output = {};
4450
+ for (const [key, [min, max2]] of Object.entries(limits)) {
4451
+ const number3 = config[key];
4452
+ if (number3 === void 0) continue;
4453
+ const integer = key === "bevelSegments" || key === "triangleBudget";
4454
+ if (typeof number3 !== "number" || !Number.isFinite(number3) || number3 <= min || number3 > max2 || integer && !Number.isSafeInteger(number3)) {
4455
+ throw new Error(`${id}.finish.${key} must be ${integer ? "an integer" : "a number"} greater than ${min}${max2 !== Infinity ? ` and at most ${max2}` : ""}.`);
4456
+ }
4457
+ output[key] = number3;
4458
+ }
4459
+ const primitives = optionalBoolean(config.primitives, `${id}.finish.primitives`);
4460
+ if (primitives !== void 0) output.primitives = primitives;
4461
+ if (primitives && !output.fitTolerance) throw new Error(`${id}.finish.primitives requires fitTolerance.`);
4462
+ if (output.bevelSegments && !output.bevelWidth) throw new Error(`${id}.finish.bevelSegments requires bevelWidth.`);
4463
+ if (config.regularization !== void 0) output.regularization = parseRegularization(config.regularization, `${id}.finish.regularization`);
4464
+ if (config.lodBevel !== void 0) {
4465
+ if (output.triangleBudget === void 0 || output.bevelWidth === void 0) {
4466
+ throw new Error(`${id}.finish.lodBevel requires triangleBudget and bevelWidth.`);
4467
+ }
4468
+ output.lodBevel = parseLodBevel(config.lodBevel, `${id}.finish.lodBevel`, output.triangleBudget);
4469
+ }
4470
+ return Object.keys(output).length ? output : void 0;
4471
+ }
4472
+ function parseInstances(value, id) {
4473
+ if (value === void 0) return;
4474
+ if (!Array.isArray(value) || !value.length || value.some((row) => !Array.isArray(row) || row.length !== 3 || row.some((number3) => typeof number3 !== "number" || !Number.isFinite(Math.fround(number3))))) {
4475
+ throw new Error(`${id}.instances must be a nonempty list of finite XYZ translations.`);
4476
+ }
4477
+ return value;
4478
+ }
4479
+ function parseAtlasSettings(node) {
4480
+ const settings = {};
4481
+ for (const [key, min, max2] of [["layers", 8, Infinity], ["resolution", 16, Infinity], ["threshold", 0, 255]]) {
4482
+ const value = node[key];
4483
+ if (value === void 0) continue;
4484
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < min || value > max2) {
4485
+ throw new Error(`${key} must be an integer ${max2 === Infinity ? `\u2265 ${min}` : `from ${min} to ${max2}`}.`);
4486
+ }
4487
+ settings[key] = value;
4488
+ }
4489
+ const { height, pivot, profile } = node;
4490
+ if (height !== void 0) {
4491
+ if (typeof height !== "number" || !Number.isFinite(height) || height <= 0) throw new Error("height must be positive.");
4492
+ settings.height = height;
4493
+ }
4494
+ if (pivot !== void 0) {
4495
+ if (pivot !== "ground" && pivot !== "center") throw new Error("pivot must be ground or center.");
4496
+ settings.pivot = pivot;
4497
+ }
4498
+ if (profile !== void 0) {
4499
+ if (profile !== "silhouette" && profile !== "round" && profile !== "round-base") throw new Error("Unknown reconstruction profile.");
4500
+ settings.profile = profile;
4501
+ }
4502
+ return settings;
4503
+ }
4504
+ function parseNode(raw, values, root, name) {
4505
+ const node = Object.fromEntries(Object.entries(mapping(raw, name)).map(([key, value]) => [key, renderValue(value, values, `${name}.${key}`)]));
4506
+ const id = requiredText(node.id, `${name}.id`);
4507
+ if (!/^[\w-]+$/.test(id)) throw new Error(`${name}.id must use letters, digits, underscores, or hyphens.`);
4508
+ const fields = (...keys) => mapping(node, id, ["id", "type", ...keys]);
4509
+ const path = (key) => resolve5(root, requiredText(node[key], `${id}.${key}`));
4510
+ const input = () => requiredText(node.input, `${id}.input`);
4511
+ switch (node.type) {
4512
+ case "load-stack":
4513
+ fields("path");
4514
+ return { id, type: node.type, path: path("path") };
4515
+ case "reconstruct-stack": {
4516
+ fields("path", "layout", "layers", "resolution", "height", "pivot", "threshold", "profile");
4517
+ const source = path("path");
4518
+ const extension = extname3(source).toLowerCase();
4519
+ const settings = parseAtlasSettings(node);
4520
+ if (extension === ".json" && node.layout === void 0) return { id, type: node.type, path: source, ...settings };
4521
+ if (extension !== ".png") throw new Error(`${id}: use a PNG atlas with layout or a JSON view manifest.`);
4522
+ const layout = parseLayout(requiredText(node.layout, `${id}.layout`)).join(",");
4523
+ return { id, type: node.type, path: source, layout, ...settings };
4524
+ }
4525
+ case "extract-mesh": {
4526
+ fields("input", "method", "guide", "finish", "cache");
4527
+ const method = requiredText(node.method, `${id}.method`);
4528
+ if (!isStackMeshMethod(method)) throw new Error(`${id}: unknown mesh method ${method}.`);
4529
+ const finish = parseFinish(node.finish, id);
4530
+ if (isCoreMeshMethod(method) && (node.guide !== void 0 || finish)) throw new Error(`${id}: ${method} does not accept ${finish ? "finishing options" : "a guide"}.`);
4531
+ const guide = node.guide === void 0 ? void 0 : path("guide");
4532
+ const cache = optionalBoolean(node.cache, `${id}.cache`);
4533
+ return { id, type: node.type, input: input(), method, ...guide && { guide }, ...finish && { finish }, ...cache !== void 0 && { cache } };
4534
+ }
4535
+ case "write-glb": {
4536
+ fields("input", "path", "lit", "instances");
4537
+ const output = path("path");
4538
+ if (extname3(output).toLowerCase() !== ".glb") throw new Error(`${id}: output must have the .glb extension.`);
4539
+ const lit = optionalBoolean(node.lit, `${id}.lit`);
4540
+ const instances = parseInstances(node.instances, id);
4541
+ return { id, type: node.type, input: input(), path: output, ...lit !== void 0 && { lit }, ...instances && { instances } };
4542
+ }
4543
+ default:
4544
+ throw new Error(`${id}: unknown node type ${String(node.type)}.`);
4545
+ }
4546
+ }
4547
+ function orderNodes(nodes) {
4548
+ const byId = /* @__PURE__ */ new Map();
4549
+ const outputs = /* @__PURE__ */ new Set();
4550
+ for (const node of nodes) {
4551
+ if (byId.has(node.id)) throw new Error(`Duplicate node ID ${node.id}.`);
4552
+ byId.set(node.id, node);
4553
+ if (node.type === "write-glb") {
4554
+ if (outputs.has(node.path)) throw new Error(`Duplicate output path ${node.path}.`);
4555
+ outputs.add(node.path);
4556
+ }
4557
+ }
4558
+ if (!outputs.size) throw new Error("The pipeline needs at least one write-glb node.");
4559
+ const ordered = [];
4560
+ const visiting = /* @__PURE__ */ new Set();
4561
+ const visited = /* @__PURE__ */ new Set();
4562
+ function visit(node) {
4563
+ if (visiting.has(node.id)) throw new Error(`Dependency cycle: ${[...visiting, node.id].join(" \u2192 ")}.`);
4564
+ if (visited.has(node.id)) return;
4565
+ visiting.add(node.id);
4566
+ if ("input" in node) {
4567
+ const source = byId.get(node.input);
4568
+ if (!source) throw new Error(`${node.id}: unknown input ${node.input}.`);
4569
+ visit(source);
4570
+ const accepted = node.type === "write-glb" ? source.type === "extract-mesh" : source.type === "load-stack" || source.type === "reconstruct-stack";
4571
+ if (!accepted) throw new Error(`${node.id}: unsupported input type ${source.type} from ${source.id}.`);
4572
+ }
4573
+ visiting.delete(node.id);
4574
+ visited.add(node.id);
4575
+ ordered.push(node);
4576
+ }
4577
+ nodes.forEach(visit);
4578
+ return ordered;
4579
+ }
4580
+ async function renderPipeline(path, overridePaths) {
4581
+ let values = {};
4582
+ const rawNodes = [];
4583
+ const loaded = /* @__PURE__ */ new Set();
4584
+ const loading = /* @__PURE__ */ new Set();
4585
+ async function load(file, root) {
4586
+ const canonical = await realpath(file);
4587
+ if (loading.has(canonical)) throw new Error(`Include cycle at ${file}.`);
4588
+ if (loaded.has(canonical)) return;
4589
+ loading.add(canonical);
4590
+ const doc = mapping(await readYaml(file), file, ["version", "includes", "values", "nodes"]);
4591
+ if ((root || doc.version !== void 0) && doc.version !== 1) throw new Error(`${file}: expected version 1.`);
4592
+ for (const key of ["includes", "nodes"]) {
4593
+ if (doc[key] !== void 0 && !Array.isArray(doc[key])) throw new Error(`${file}.${key} must be a list.`);
4594
+ }
4595
+ if (Array.isArray(doc.includes)) {
4596
+ for (const include of doc.includes) {
4597
+ await load(resolve5(dirname4(file), requiredText(include, `${file}.includes item`)), false);
4598
+ }
4599
+ }
4600
+ if (doc.values !== void 0) values = mergeValues(values, mapping(doc.values, `${file}.values`));
4601
+ if (Array.isArray(doc.nodes)) doc.nodes.forEach((raw, index) => rawNodes.push({ raw, name: `${file}.nodes[${index}]` }));
4602
+ loading.delete(canonical);
4603
+ loaded.add(canonical);
4604
+ }
4605
+ await load(path, true);
4606
+ for (const overridePath of overridePaths) values = mergeValues(values, mapping(await readYaml(overridePath), overridePath));
4607
+ const nodes = orderNodes(rawNodes.map(({ raw, name }) => parseNode(raw, values, dirname4(path), name)));
4608
+ return { version: 1, nodes };
4609
+ }
4610
+ async function surfaceCacheKey(node, stack) {
4611
+ const { texture, ...bounds2 } = stack;
4612
+ const hash = createHash2("sha256");
4613
+ hash.update(JSON.stringify([
4614
+ "surface-v4",
4615
+ node.method,
4616
+ node.finish,
4617
+ bounds2,
4618
+ texture.width,
4619
+ texture.height,
4620
+ process.env.STACK3_PYTHON,
4621
+ process.env.BLENDER_BIN
4622
+ ]));
4623
+ hash.update(texture.data);
4624
+ if (node.guide) {
4625
+ const guide = await readFile6(node.guide);
4626
+ hash.update(guide);
4627
+ if (node.method === "signed-distance-dc" || node.method === "hermite-dc") {
4628
+ const { field, dexel } = JSON.parse(guide.toString("utf8"));
4629
+ for (const source of [field, dexel]) {
4630
+ if (typeof source === "string") hash.update(await readFile6(resolve5(dirname4(node.guide), source)));
4631
+ }
4632
+ }
4633
+ }
4634
+ return hash.digest("hex");
4635
+ }
4636
+ async function extract(node, stack) {
4637
+ const key = node.cache ? await surfaceCacheKey(node, stack) : void 0;
4638
+ const cached = key ? await readSurfaceCache(key) : void 0;
4639
+ if (cached) {
4640
+ console.error(`${node.id}: geometry cache hit`);
4641
+ return cached;
4642
+ }
4643
+ const mesh = await readStackMesh(stack, node.method, node.guide, node.finish);
4644
+ if (key && key === await surfaceCacheKey(node, stack)) await writeBuildCache(key, { format: "surface", mesh });
4645
+ return mesh;
4646
+ }
4647
+ async function runPipeline(nodes) {
4648
+ const assets = /* @__PURE__ */ new Map();
4649
+ const remaining = /* @__PURE__ */ new Map();
4650
+ for (const node of nodes) if ("input" in node) remaining.set(node.input, (remaining.get(node.input) ?? 0) + 1);
4651
+ for (const node of nodes) {
4652
+ try {
4653
+ if (node.type === "load-stack") {
4654
+ assets.set(node.id, (await loadStack(node.path)).stack);
4655
+ } else if (node.type === "reconstruct-stack") {
4656
+ const { id, type, path, layout, ...settings } = node;
4657
+ const threshold = settings.threshold ?? 238;
4658
+ const views = prepareViews(await readInput(path, layout, threshold), threshold);
4659
+ assets.set(node.id, buildFromPreparedViews(views, "stack", settings));
4660
+ } else {
4661
+ const source = assets.get(node.input);
4662
+ if (node.type === "extract-mesh" && source?.target === "stack") {
4663
+ assets.set(node.id, await extract(node, source));
4664
+ } else if (node.type === "write-glb" && source?.target === "mesh") {
4665
+ await mkdir3(dirname4(node.path), { recursive: true });
4666
+ await writeFile3(node.path, encodeGlb(source, node));
4667
+ console.log(`${node.id}: ${node.path}`);
4668
+ } else {
4669
+ throw new Error(`Missing resolved input ${node.input}.`);
4670
+ }
4671
+ const count2 = (remaining.get(node.input) ?? 1) - 1;
4672
+ remaining.set(node.input, count2);
4673
+ if (!count2) assets.delete(node.input);
4674
+ }
4675
+ if (!remaining.has(node.id)) assets.delete(node.id);
4676
+ } catch (error) {
4677
+ throw new Error(`${node.id} (${node.type}): ${error.message}`);
4678
+ }
4679
+ }
4680
+ }
4681
+ async function pipelineCommand(args) {
4682
+ const { positionals, values } = parseArgs2({ args, allowPositionals: true, options: {
4683
+ values: { type: "string", short: "f", multiple: true },
4684
+ help: { type: "boolean", short: "h" }
4685
+ } });
4686
+ if (values.help || !args.length) {
4687
+ console.log(help2);
4688
+ return;
4689
+ }
4690
+ const [verb, file] = positionals;
4691
+ if (verb === "schema") {
4692
+ if (positionals.length > 2 || values.values) throw new Error("Use stack3 pipeline schema [recipe|fragment].");
4693
+ await printPipelineSchema(file ?? "recipe");
4694
+ return;
4695
+ }
4696
+ if (verb !== "render" && verb !== "run" || positionals.length !== 2) throw new Error(help2);
4697
+ const pipeline = await renderPipeline(resolve5(file), values.values ?? []);
4698
+ if (verb === "render") process.stdout.write(stringify(pipeline));
4699
+ else await runPipeline(pipeline.nodes);
4700
+ }
4701
+ var help2;
4702
+ var init_pipeline = __esm({
4703
+ "apps/cli/src/pipeline.ts"() {
4704
+ "use strict";
4705
+ init_src();
4706
+ init_atlas_input();
4707
+ init_build_cache();
4708
+ init_capabilities();
4709
+ init_grid_build();
4710
+ init_part_mesh();
4711
+ init_stack_input();
4712
+ help2 = `Usage: stack3 pipeline <render|run> <pipeline.yaml> [-f <values.yaml> ...]
4713
+ stack3 pipeline schema [recipe|fragment]
4714
+ render Resolve includes and values, then print the validated pipeline YAML.
4715
+ run Execute the same resolved pipeline and write its GLB outputs.
4716
+ schema Print a standalone JSON Schema. The default is recipe.
4717
+ -f, --values Override defaults in order. The last file takes precedence.
4718
+
4719
+ Nodes: load-stack, reconstruct-stack, extract-mesh, write-glb.
4720
+ Run stack3 capabilities --json for backends, guide fields and sample paths.`;
4721
+ }
4722
+ });
4723
+
4724
+ // apps/cli/src/verify-command.ts
4725
+ var verify_command_exports = {};
4726
+ __export(verify_command_exports, {
4727
+ verifyCommand: () => verifyCommand
4728
+ });
4729
+ import { spawn as spawn2 } from "node:child_process";
4730
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
4731
+ import { parseArgs as parseArgs3 } from "node:util";
4732
+ async function verifyCommand(args) {
4733
+ const { positionals, values } = parseArgs3({ args, allowPositionals: true, options: {
4734
+ file: { type: "string", short: "f" },
4735
+ output: { type: "string", short: "o" },
4736
+ check: { type: "string" },
4737
+ part: { type: "string" },
4738
+ "output-dir": { type: "string" },
4739
+ help: { type: "boolean", short: "h" }
4740
+ } });
4741
+ if (values.help || !args.length) {
4742
+ console.log(help3);
4743
+ return;
4744
+ }
4745
+ const [kind] = positionals;
4746
+ if (positionals.length > 1 || kind !== void 0 && !["atlas", "assembly"].includes(kind) || !values.file || values.output !== void 0 && values.output !== "json" || values.check !== void 0 && (kind !== "atlas" || !["projections", "landmarks"].includes(values.check)) || values.part !== void 0 && (kind !== "assembly" || !values.part)) throw new Error(help3);
4747
+ const script = fileURLToPath4(new URL("../verification/verify.py", import.meta.url));
4748
+ const python = process.env.STACK3_PYTHON;
4749
+ const params = [...python ? [] : ["run", "--no-project", "--script"], script, values.file];
4750
+ if (kind) params.push("--kind", kind);
4751
+ for (const key of ["check", "part", "output-dir"]) {
4752
+ if (values[key] !== void 0) params.push("--" + key, values[key]);
4753
+ }
4754
+ await new Promise((done, reject) => {
4755
+ const child = spawn2(python || "uv", params, { stdio: "inherit", env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" } });
4756
+ child.once("error", (error) => reject(new Error(`Cannot start verifier: ${error.message}. Install uv or set STACK3_PYTHON.`)));
4757
+ child.once("close", (code) => code === 0 ? done() : reject(new Error("Verification could not complete.")));
4758
+ });
4759
+ }
4760
+ var help3;
4761
+ var init_verify_command = __esm({
4762
+ "apps/cli/src/verify-command.ts"() {
4763
+ "use strict";
4764
+ help3 = `stack3 verify -f <manifest.yaml> [--output-dir <dir>]
4765
+ Print one JSON measurement report to stdout.
4766
+ Atlas: projections and landmarks. Assembly: whole and part atlases plus mount measurements.
4767
+ --output-dir <dir> Also save report.json and annotated PNG overlays
4768
+ -f, --file Image and child manifest paths are relative to their YAML file.`;
4769
+ }
4770
+ });
4771
+
3584
4772
  // apps/cli/src/project-store.ts
3585
4773
  import { randomUUID as randomUUID2 } from "node:crypto";
3586
- import { mkdir as mkdir2, open, readFile as readFile2, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
3587
- import { dirname } from "node:path";
4774
+ import { mkdir as mkdir4, open, readFile as readFile7, rename as rename2, stat as stat2, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
4775
+ import { dirname as dirname5 } from "node:path";
3588
4776
  import { setTimeout as setTimeout2 } from "node:timers/promises";
3589
4777
  async function readProject(file) {
3590
- const data = JSON.parse(await readFile2(file, "utf8"));
4778
+ const data = JSON.parse(await readFile7(file, "utf8"));
3591
4779
  if (data.version !== 1 || !Number.isInteger(data.revision) || !Array.isArray(data.nodes) || !Array.isArray(data.atlases) || !data.view || !data.play) throw new Error("Expected a version 1 stack3 scene project.");
3592
4780
  return data;
3593
4781
  }
3594
4782
  async function initProject(file, name) {
3595
- await mkdir2(dirname(file), { recursive: true });
4783
+ await mkdir4(dirname5(file), { recursive: true });
3596
4784
  const project = newProject(name);
3597
- await writeFile2(file, JSON.stringify(project) + "\n", { flag: "wx", mode: 384 });
4785
+ await writeFile4(file, JSON.stringify(project) + "\n", { flag: "wx", mode: 384 });
3598
4786
  return project;
3599
4787
  }
3600
4788
  async function editProject(file, actions, expected) {
@@ -3615,7 +4803,7 @@ async function editProject(file, actions, expected) {
3615
4803
  const project = await readProject(file);
3616
4804
  if (expected !== void 0 && project.revision !== expected) throw new RevisionConflict("Project revision changed.");
3617
4805
  const next = applyProjectActions(project, actions);
3618
- await writeFile2(temporary, JSON.stringify(next) + "\n", { flag: "wx", mode: 384 });
4806
+ await writeFile4(temporary, JSON.stringify(next) + "\n", { flag: "wx", mode: 384 });
3619
4807
  await rename2(temporary, file);
3620
4808
  return next;
3621
4809
  } finally {
@@ -3645,13 +4833,13 @@ var init_project_store = __esm({
3645
4833
  });
3646
4834
 
3647
4835
  // apps/cli/src/preview-server.ts
3648
- import { existsSync } from "node:fs";
3649
- import { fileURLToPath } from "node:url";
4836
+ import { existsSync as existsSync3 } from "node:fs";
4837
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
3650
4838
  import { createServer, preview } from "vite";
3651
4839
  async function serveViewer(page, open2, middleware) {
3652
4840
  const server = { host: "127.0.0.1", port: 0, cors: false, open: open2 ? page : false };
3653
- const packagedRoot = fileURLToPath(new URL("../viewer/", import.meta.url));
3654
- if (existsSync(new URL("../viewer/dist/index.html", import.meta.url))) {
4841
+ const packagedRoot = fileURLToPath5(new URL("../viewer/", import.meta.url));
4842
+ if (existsSync3(new URL("../viewer/dist/index.html", import.meta.url))) {
3655
4843
  const built = await preview({
3656
4844
  root: packagedRoot,
3657
4845
  configFile: false,
@@ -3666,7 +4854,7 @@ async function serveViewer(page, open2, middleware) {
3666
4854
  return new URL(page, built.resolvedUrls.local[0]);
3667
4855
  }
3668
4856
  const dev = await createServer({
3669
- root: fileURLToPath(new URL("../../viewer/", import.meta.url)),
4857
+ root: fileURLToPath5(new URL("../../viewer/", import.meta.url)),
3670
4858
  server,
3671
4859
  plugins: [{
3672
4860
  name: "stack3-cli-preview",
@@ -3689,7 +4877,7 @@ var project_server_exports = {};
3689
4877
  __export(project_server_exports, {
3690
4878
  openProject: () => openProject
3691
4879
  });
3692
- import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
4880
+ import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
3693
4881
  async function body(request) {
3694
4882
  const chunks = [];
3695
4883
  let size = 0;
@@ -3774,7 +4962,7 @@ var init_project_server = __esm({
3774
4962
  init_src();
3775
4963
  init_project_store();
3776
4964
  limit = 80 * 1024 * 1024;
3777
- fingerprint = (png2) => createHash2("sha256").update(png2).digest("hex");
4965
+ fingerprint = (png2) => createHash3("sha256").update(png2).digest("hex");
3778
4966
  }
3779
4967
  });
3780
4968
 
@@ -3783,18 +4971,18 @@ var project_command_exports = {};
3783
4971
  __export(project_command_exports, {
3784
4972
  projectCommand: () => projectCommand
3785
4973
  });
3786
- import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
3787
- import { readFile as readFile3, writeFile as writeFile3, mkdir as mkdir3 } from "node:fs/promises";
3788
- import { basename, dirname as dirname2, extname, join as join2, resolve as resolve2 } from "node:path";
3789
- import { parseArgs } from "node:util";
3790
- import { PNG } from "pngjs";
4974
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
4975
+ import { readFile as readFile8, writeFile as writeFile5, mkdir as mkdir5 } from "node:fs/promises";
4976
+ import { basename as basename2, dirname as dirname6, extname as extname4, join as join5, resolve as resolve6 } from "node:path";
4977
+ import { parseArgs as parseArgs4 } from "node:util";
4978
+ import { PNG as PNG3 } from "pngjs";
3791
4979
  async function stdin() {
3792
4980
  const chunks = [];
3793
4981
  for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
3794
4982
  return Buffer.concat(chunks).toString("utf8");
3795
4983
  }
3796
4984
  async function projectCommand(args) {
3797
- const { positionals: [verb, file, ...inputs], values } = parseArgs({
4985
+ const { positionals: [verb, file, ...inputs], values } = parseArgs4({
3798
4986
  args,
3799
4987
  allowPositionals: true,
3800
4988
  options: {
@@ -3811,7 +4999,7 @@ async function projectCommand(args) {
3811
4999
  }
3812
5000
  });
3813
5001
  if (!verb || values.help) {
3814
- console.log(help);
5002
+ console.log(help4);
3815
5003
  return;
3816
5004
  }
3817
5005
  if (verb === "schema") {
@@ -3830,11 +5018,11 @@ async function projectCommand(args) {
3830
5018
  return;
3831
5019
  }
3832
5020
  if (!file) throw new Error("Provide a project file.");
3833
- const path = resolve2(file);
5021
+ const path = resolve6(file);
3834
5022
  switch (verb) {
3835
5023
  case "init": {
3836
5024
  if (inputs.length) throw new Error("init expects only a project file.");
3837
- print(summarizeProject(await initProject(path, values.name || basename(path, extname(path)))));
5025
+ print(summarizeProject(await initProject(path, values.name || basename2(path, extname4(path)))));
3838
5026
  return;
3839
5027
  }
3840
5028
  case "get":
@@ -3849,7 +5037,7 @@ async function projectCommand(args) {
3849
5037
  if (inputs.length !== 1) throw new Error("Provide a JSON action file or - for standard input.");
3850
5038
  const revision = values.revision === void 0 ? void 0 : Number(values.revision);
3851
5039
  if (revision !== void 0 && (!Number.isInteger(revision) || revision < 0)) throw new Error("Invalid project revision.");
3852
- print(summarizeProject(await editProject(path, JSON.parse(inputs[0] === "-" ? await stdin() : await readFile3(inputs[0], "utf8")), revision)));
5040
+ print(summarizeProject(await editProject(path, JSON.parse(inputs[0] === "-" ? await stdin() : await readFile8(inputs[0], "utf8")), revision)));
3853
5041
  return;
3854
5042
  }
3855
5043
  case "preset": {
@@ -3873,9 +5061,9 @@ async function projectCommand(args) {
3873
5061
  const actions = [];
3874
5062
  const nodes = [];
3875
5063
  for (const image of inputs) {
3876
- const bytes = await readFile3(image);
3877
- const name = basename(image, extname(image));
3878
- const atlasId = createHash3("sha256").update(layout).update(bytes).digest("hex");
5064
+ const bytes = await readFile8(image);
5065
+ const name = basename2(image, extname4(image));
5066
+ const atlasId = createHash4("sha256").update(layout).update(bytes).digest("hex");
3879
5067
  const id = randomUUID4();
3880
5068
  nodes.push(id);
3881
5069
  actions.push(
@@ -3894,21 +5082,22 @@ async function projectCommand(args) {
3894
5082
  const node = project.nodes.find((item) => item.id === inputs[0]);
3895
5083
  const atlas = project.atlases.find((item) => item.id === node?.atlasId);
3896
5084
  if (!node || !atlas) throw new Error("Export requires an atlas-backed node.");
3897
- const format = values.format ?? (extname(values.output).toLowerCase() === ".glb" ? "glb" : node.settings.format);
5085
+ const format = values.format ?? (extname4(values.output).toLowerCase() === ".glb" ? "glb" : node.settings.format);
3898
5086
  if (format !== "glb" && format !== "stack") throw new Error("Use --format glb or --format stack.");
3899
- const output = resolve2(values.output);
3900
- if (format === "glb" && extname(output).toLowerCase() !== ".glb") throw new Error("GLB output must end in .glb.");
3901
- const image = PNG.sync.read(Buffer.from(atlas.png, "base64"));
5087
+ const output = resolve6(values.output);
5088
+ if (format === "glb" && extname4(output).toLowerCase() !== ".glb") throw new Error("GLB output must end in .glb.");
5089
+ const image = PNG3.sync.read(Buffer.from(atlas.png, "base64"));
3902
5090
  const settings = node.settings;
3903
- const asset = reconstruct(splitAtlas(image, parseLayout(atlas.layout), settings.threshold), format === "glb" ? "mesh" : "stack", settings);
5091
+ const views = prepareViews(splitAtlas(image, parseLayout(atlas.layout), settings.threshold), settings.threshold);
5092
+ const asset = buildFromPreparedViews(views, format === "glb" ? "mesh" : "stack", settings);
3904
5093
  if (asset.target === "mesh") {
3905
- await mkdir3(dirname2(output), { recursive: true });
3906
- await writeFile3(output, encodeGlb(asset));
5094
+ await mkdir5(dirname6(output), { recursive: true });
5095
+ await writeFile5(output, encodeGlb(asset));
3907
5096
  } else {
3908
5097
  const bundle = encodeStack(respaceStack(asset, settings.spacing));
3909
- await mkdir3(output, { recursive: true });
3910
- await writeFile3(join2(output, "stack.png"), bundle.png);
3911
- await writeFile3(join2(output, "stack.json"), JSON.stringify(bundle.manifest, null, 2) + "\n");
5098
+ await mkdir5(output, { recursive: true });
5099
+ await writeFile5(join5(output, "stack.png"), bundle.png);
5100
+ await writeFile5(join5(output, "stack.json"), JSON.stringify(bundle.manifest, null, 2) + "\n");
3912
5101
  }
3913
5102
  print({ node: node.id, format, output });
3914
5103
  return;
@@ -3917,13 +5106,14 @@ async function projectCommand(args) {
3917
5106
  throw new Error("Unknown project command: " + verb);
3918
5107
  }
3919
5108
  }
3920
- var help, print;
5109
+ var help4, print;
3921
5110
  var init_project_command = __esm({
3922
5111
  "apps/cli/src/project-command.ts"() {
3923
5112
  "use strict";
5113
+ init_grid_build();
3924
5114
  init_src();
3925
5115
  init_project_store();
3926
- help = `Usage: stack3 project <verb> [project-file] [options]
5116
+ help4 = `Usage: stack3 project <verb> [project-file] [options]
3927
5117
 
3928
5118
  schema List agent actions and field constraints as JSON
3929
5119
  components [component-id] List built-in script components or inspect one
@@ -3952,16 +5142,14 @@ __export(view_exports, {
3952
5142
  viewStack: () => viewStack
3953
5143
  });
3954
5144
  import { randomUUID as randomUUID5 } from "node:crypto";
3955
- import { readFile as readFile4 } from "node:fs/promises";
3956
- import { join as join3 } from "node:path";
3957
- import { PNG as PNG2 } from "pngjs";
3958
- async function viewStack(directory2, open2) {
3959
- const [metadata, png2] = await Promise.all([
3960
- readFile4(join3(directory2, "stack.json"), "utf8"),
3961
- readFile4(join3(directory2, "stack.png"))
3962
- ]);
3963
- readPngSize(png2);
3964
- readStackBundle(JSON.parse(metadata), PNG2.sync.read(png2));
5145
+ async function viewStack(directory2, open2, web = false, output) {
5146
+ if (web && output) throw new Error("Choose --web or a .blend output file.");
5147
+ const { metadata, png: png2 } = await loadStack(directory2);
5148
+ if (!web && (open2 || output)) {
5149
+ const { openBlenderStack: openBlenderStack2 } = await Promise.resolve().then(() => (init_blender(), blender_exports));
5150
+ await openBlenderStack2(directory2, output, open2);
5151
+ return;
5152
+ }
3965
5153
  const token = randomUUID5();
3966
5154
  const prefix = "/__stack3/" + token + "/";
3967
5155
  const url = await serveViewer("/?stack=" + token, open2, (request, response, next) => {
@@ -3983,69 +5171,46 @@ var init_view = __esm({
3983
5171
  "apps/cli/src/view.ts"() {
3984
5172
  "use strict";
3985
5173
  init_preview_server();
3986
- init_src();
5174
+ init_stack_input();
3987
5175
  }
3988
5176
  });
3989
5177
 
3990
5178
  // apps/cli/src/main.ts
5179
+ init_atlas_input();
5180
+ init_part_mesh();
5181
+ init_stack_input();
5182
+ init_grid_build();
3991
5183
  init_src();
3992
- import { constants, existsSync as existsSync2 } from "node:fs";
3993
- import { copyFile, mkdir as mkdir4, readFile as readFile5, writeFile as writeFile4 } from "node:fs/promises";
3994
- import { dirname as dirname3, extname as extname2, join as join4, resolve as resolve3 } from "node:path";
3995
- import { parseArgs as parseArgs2 } from "node:util";
3996
- import { PNG as PNG3 } from "pngjs";
3997
-
3998
- // apps/cli/src/build-cache.ts
3999
- init_src();
4000
- import { createHash, randomUUID } from "node:crypto";
4001
- import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
4002
- import { homedir } from "node:os";
4003
- import { join, resolve } from "node:path";
4004
- import { deserialize, serialize } from "node:v8";
4005
- var version = "render-data-3";
4006
- var directory = process.env.STACK3_CACHE_DIR ? resolve(process.env.STACK3_CACHE_DIR) : join(process.env.XDG_CACHE_HOME || join(homedir(), ".cache"), "stack3", version);
4007
- function buildCacheKey(views, format, settings, spacing) {
4008
- const hash = createHash("sha256");
4009
- hash.update(JSON.stringify([version, format, settings, spacing]));
4010
- for (const direction of DIRECTIONS) {
4011
- const view = views[direction];
4012
- if (!view) continue;
4013
- hash.update(JSON.stringify([direction, view.width, view.height]));
4014
- hash.update(view.data);
4015
- }
4016
- return hash.digest("hex");
4017
- }
4018
- async function readBuildCache(key, format) {
4019
- try {
4020
- const data = deserialize(await readFile(join(directory, key + ".cache")));
4021
- if (data.format !== format) return;
4022
- if (data.format === "glb" ? data.bytes instanceof Uint8Array : data.png instanceof Uint8Array && typeof data.manifest === "string") return data;
4023
- } catch {
4024
- }
4025
- }
4026
- async function writeBuildCache(key, output) {
4027
- const temporary = join(directory, randomUUID() + ".tmp");
4028
- try {
4029
- await mkdir(directory, { recursive: true });
4030
- await writeFile(temporary, serialize(output), { flag: "wx" });
4031
- await rename(temporary, join(directory, key + ".cache"));
4032
- const entries = (await readdir(directory)).filter((name) => /^[0-9a-f]{64}\.cache$/.test(name));
4033
- if (entries.length <= 12) return;
4034
- const dated = await Promise.all(entries.map(async (name) => ({ name, time: (await stat(join(directory, name))).mtimeMs })));
4035
- await Promise.all(dated.sort((a, b) => b.time - a.time).slice(12).map(({ name }) => unlink(join(directory, name))));
4036
- } catch {
4037
- await unlink(temporary).catch(() => {
4038
- });
4039
- }
4040
- }
4041
-
4042
- // apps/cli/src/main.ts
5184
+ init_build_cache();
5185
+ import { constants, existsSync as existsSync4 } from "node:fs";
5186
+ import { copyFile, mkdir as mkdir6, readFile as readFile9, writeFile as writeFile6 } from "node:fs/promises";
5187
+ import { dirname as dirname7, extname as extname5, join as join6, resolve as resolve7 } from "node:path";
5188
+ import { parseArgs as parseArgs5 } from "node:util";
4043
5189
  var HELP = `Usage: stack3 <verb> <input> [options]
4044
5190
 
5191
+ help [topic] Show command help (pipeline, mesh, or capabilities)
5192
+ capabilities [--json] List mesh methods, runtime requirements, schemas and example recipes
4045
5193
  example <name> Copy future-tank or traffic-cone into the current directory
5194
+ verify -f <manifest> Measure atlas views and mounts in one JSON report
4046
5195
  inspect <input> Check mapped directions and fitted image sizes
4047
5196
  build <input> Build an asset and save it to --output
4048
- view <directory> Open a stack bundle in the local viewer (--no-open to print the URL only)
5197
+ pipeline --help Render or run YAML, or export its JSON Schema
5198
+ mesh <stack-directory> Extract a surface from saved stack.png + stack.json (--output mesh.glb)
5199
+ --mesh-method marching-cubes (default), surface-nets, voxel
5200
+ or ${partMethods.join(", ")}
5201
+ --guide <part.json> uses pivot-relative stack XYZ scene units.
5202
+ section-loft, smooth-loft, branch-loft, heightfield: optional axis (x/y/z, default z)
5203
+ section-loft, smooth-loft: optional stations [{slice,outer?,holes?}]
5204
+ revolve: axis + origin, optional segments (8-512, default 64)
5205
+ path-sweep: path; optional up and profile {outer,holes?} (defaults to first stack section)
5206
+ section-network: sections [{source:"independent",origin,u,v,outer,holes?}], optional tolerance
5207
+ hermite-dc: optional field (.npy SDF) or dexel (.npz crossings and normals)
5208
+ signed-distance-dc: optional field, outerIterations and innerIterations
5209
+ extended-mc, mc33, greedy, monotone: no guide
5210
+ New methods use uv or STACK3_PYTHON. See the stack3 skill for guide examples.
5211
+ view <directory> Open a stack bundle in Blender (use --web for the browser viewer)
5212
+ --output scene.blend saves a named scene; add --no-open for headless export
5213
+ --no-open alone prints the web preview URL
4049
5214
  project --help Edit a level and control its live viewer and playground
4050
5215
 
4051
5216
  Inputs
@@ -4059,38 +5224,15 @@ Build options
4059
5224
  --texture-projection <name> auto (default) or top-contour for GLB output
4060
5225
  --mesh-method <name> marching-cubes (default) or contour for GLB output
4061
5226
  --contour-hub Add a centered round axle measured from TOP and LEFT
4062
- --layers <integer> Vertical samples (default 48)
5227
+ --layers <integer|native> Vertical samples (default ${DEFAULT_LAYERS})
4063
5228
  --spacing <number> Sprite stack spacing multiplier (default 1)
4064
5229
  --profile <name> silhouette, round, or round-base
4065
5230
  --no-cache Bypass the local build cache
4066
- --resolution <integer> Maximum horizontal axis samples (default 96)
5231
+ --resolution <integer|native> Longer horizontal axis samples (default 96)
4067
5232
  --height <number> Asset height in scene units (default 1)
4068
5233
  --pivot ground|center Origin position (default ground)
4069
5234
  --threshold <0\u2013255> Background threshold for opaque PNGs (default 238)
4070
5235
  `;
4071
- async function png(path) {
4072
- const bytes = await readFile5(path);
4073
- readPngSize(bytes);
4074
- const image = PNG3.sync.read(bytes);
4075
- return { width: image.width, height: image.height, data: image.data };
4076
- }
4077
- async function readInput(path, layout, threshold) {
4078
- if (extname2(path).toLowerCase() === ".png") {
4079
- if (!layout) throw new Error("A PNG atlas needs an explicit --layout.");
4080
- return splitAtlas(await png(path), parseLayout(layout), threshold);
4081
- }
4082
- if (extname2(path).toLowerCase() !== ".json") throw new Error("Choose a PNG atlas or a JSON view manifest.");
4083
- if (layout) throw new Error("View manifests define their directions in the views field.");
4084
- const manifest = JSON.parse(await readFile5(path, "utf8"));
4085
- const views = manifest && typeof manifest === "object" && "views" in manifest ? manifest.views : null;
4086
- if (!views || typeof views !== "object" || Array.isArray(views)) throw new Error("The manifest needs a views object.");
4087
- const entries = Object.entries(views);
4088
- parseLayout(entries.map(([name]) => name).join(","));
4089
- return Object.fromEntries(await Promise.all(entries.map(async ([name, file]) => {
4090
- if (!DIRECTIONS.includes(name) || typeof file !== "string" || !file) throw new Error(`Invalid view entry: ${name}`);
4091
- return [name, await png(resolve3(dirname3(path), file))];
4092
- })));
4093
- }
4094
5236
  function outputFormat(output, format, target) {
4095
5237
  if (format !== void 0 && format !== "glb" && format !== "stack") {
4096
5238
  throw new Error("Use --format glb or --format stack.");
@@ -4100,7 +5242,7 @@ function outputFormat(output, format, target) {
4100
5242
  }
4101
5243
  const legacyFormat = target === "mesh" ? "glb" : target;
4102
5244
  if (format && legacyFormat && format !== legacyFormat) throw new Error("--format and --target disagree.");
4103
- const isGlbPath = extname2(output).toLowerCase() === ".glb";
5245
+ const isGlbPath = extname5(output).toLowerCase() === ".glb";
4104
5246
  const selected = format ?? legacyFormat ?? (isGlbPath ? "glb" : void 0);
4105
5247
  if (!selected) throw new Error("Use --format stack for a stack directory or specify a .glb output file.");
4106
5248
  if (selected === "glb" && !isGlbPath) throw new Error("GLB output must have the .glb extension.");
@@ -4115,18 +5257,45 @@ async function copyExample(name, output) {
4115
5257
  if (!example) throw new Error("Choose future-tank or traffic-cone.");
4116
5258
  const [filename, workspacePath] = example;
4117
5259
  const packaged = new URL("../examples/" + filename, import.meta.url);
4118
- const source = existsSync2(packaged) ? packaged : new URL("../../../" + workspacePath, import.meta.url);
4119
- const destination = resolve3(output ?? filename);
5260
+ const source = existsSync4(packaged) ? packaged : new URL("../../../" + workspacePath, import.meta.url);
5261
+ const destination = resolve7(output ?? filename);
4120
5262
  await copyFile(source, destination, constants.COPYFILE_EXCL);
4121
5263
  console.log(destination);
4122
5264
  }
4123
5265
  async function main() {
4124
- if (process.argv[2] === "project") {
5266
+ const args = process.argv.slice(2);
5267
+ if (args[0] === "help") {
5268
+ if (args.length === 1) {
5269
+ console.log(HELP);
5270
+ return;
5271
+ }
5272
+ if (args.length !== 2 || !["pipeline", "mesh", "capabilities"].includes(args[1])) {
5273
+ throw new Error("Use stack3 help [pipeline|mesh|capabilities].");
5274
+ }
5275
+ args.splice(0, 2, args[1], "--help");
5276
+ }
5277
+ if (args[0] === "capabilities") {
5278
+ const { capabilitiesCommand: capabilitiesCommand2 } = await Promise.resolve().then(() => (init_capabilities(), capabilities_exports));
5279
+ capabilitiesCommand2(args.slice(1));
5280
+ return;
5281
+ }
5282
+ if (args[0] === "pipeline") {
5283
+ const { pipelineCommand: pipelineCommand2 } = await Promise.resolve().then(() => (init_pipeline(), pipeline_exports));
5284
+ await pipelineCommand2(args.slice(1));
5285
+ return;
5286
+ }
5287
+ if (args[0] === "verify") {
5288
+ const { verifyCommand: verifyCommand2 } = await Promise.resolve().then(() => (init_verify_command(), verify_command_exports));
5289
+ await verifyCommand2(args.slice(1));
5290
+ return;
5291
+ }
5292
+ if (args[0] === "project") {
4125
5293
  const { projectCommand: projectCommand2 } = await Promise.resolve().then(() => (init_project_command(), project_command_exports));
4126
- await projectCommand2(process.argv.slice(3));
5294
+ await projectCommand2(args.slice(1));
4127
5295
  return;
4128
5296
  }
4129
- const { positionals, values } = parseArgs2({
5297
+ const { positionals, values } = parseArgs5({
5298
+ args,
4130
5299
  allowPositionals: true,
4131
5300
  options: {
4132
5301
  help: { type: "boolean", short: "h" },
@@ -4142,15 +5311,17 @@ async function main() {
4142
5311
  threshold: { type: "string" },
4143
5312
  "texture-projection": { type: "string" },
4144
5313
  "mesh-method": { type: "string" },
5314
+ guide: { type: "string" },
4145
5315
  "contour-hub": { type: "boolean" },
4146
5316
  spacing: { type: "string" },
4147
5317
  profile: { type: "string" },
4148
5318
  "no-cache": { type: "boolean" },
4149
- "no-open": { type: "boolean" }
5319
+ "no-open": { type: "boolean" },
5320
+ web: { type: "boolean" }
4150
5321
  }
4151
5322
  });
4152
5323
  if (values.version) {
4153
- const manifest = JSON.parse(await readFile5(new URL("../package.json", import.meta.url), "utf8"));
5324
+ const manifest = JSON.parse(await readFile9(new URL("../package.json", import.meta.url), "utf8"));
4154
5325
  console.log(manifest.version);
4155
5326
  return;
4156
5327
  }
@@ -4159,16 +5330,39 @@ async function main() {
4159
5330
  return;
4160
5331
  }
4161
5332
  const [verb, input] = positionals;
5333
+ if (values.guide !== void 0 && verb !== "mesh") throw new Error("--guide requires stack3 mesh.");
4162
5334
  if (verb === "example" && positionals.length === 2) {
4163
5335
  await copyExample(input, values.output);
4164
5336
  return;
4165
5337
  }
4166
- if (positionals.length !== 2 || verb !== "inspect" && verb !== "build" && verb !== "view") {
5338
+ if (positionals.length !== 2 || verb !== "inspect" && verb !== "build" && verb !== "mesh" && verb !== "view") {
4167
5339
  throw new Error("See stack3 --help for available commands and arguments.");
4168
5340
  }
5341
+ if (verb === "mesh") {
5342
+ if (!values.output || extname5(values.output).toLowerCase() !== ".glb" || Object.keys(values).some((k) => k !== "output" && k !== "mesh-method" && k !== "guide")) {
5343
+ throw new Error("Use stack3 mesh <stack-directory> --output <file.glb>. Geometry settings come from the saved stack.");
5344
+ }
5345
+ const method = values["mesh-method"] ?? "marching-cubes";
5346
+ if (!isStackMeshMethod(method)) {
5347
+ throw new Error(`Stack mesh methods: marching-cubes, surface-nets, voxel, ${partMethods.join(", ")}.`);
5348
+ }
5349
+ if (isCoreMeshMethod(method) && values.guide !== void 0) throw new Error(`${input}: ${method} does not accept --guide.`);
5350
+ const { stack } = await loadStack(resolve7(input));
5351
+ let bytes;
5352
+ try {
5353
+ bytes = encodeGlb(await readStackMesh(stack, method, values.guide));
5354
+ } catch (error) {
5355
+ throw new Error(`${input} (${method}): ${error.message}`);
5356
+ }
5357
+ const output2 = resolve7(values.output);
5358
+ await mkdir6(dirname7(output2), { recursive: true });
5359
+ await writeFile6(output2, bytes);
5360
+ console.log(`Meshed ${stack.layers} saved layers with ${method} into ${output2}`);
5361
+ return;
5362
+ }
4169
5363
  if (verb === "view") {
4170
5364
  const { viewStack: viewStack2 } = await Promise.resolve().then(() => (init_view(), view_exports));
4171
- await viewStack2(resolve3(input), !values["no-open"]);
5365
+ await viewStack2(resolve7(input), !values["no-open"], values.web ?? false, values.output);
4172
5366
  return;
4173
5367
  }
4174
5368
  const threshold = values.threshold === void 0 ? 238 : Number(values.threshold);
@@ -4179,7 +5373,7 @@ async function main() {
4179
5373
  return;
4180
5374
  }
4181
5375
  if (!values.output) throw new Error("Build requires --output <path>.");
4182
- const output = resolve3(values.output);
5376
+ const output = resolve7(values.output);
4183
5377
  const format = outputFormat(output, values.format, values.target);
4184
5378
  const spacing = values.spacing === void 0 ? 1 : Number(values.spacing);
4185
5379
  if (!Number.isFinite(spacing) || spacing <= 0) throw new Error("Spacing must be a positive, finite multiplier.");
@@ -4199,34 +5393,40 @@ async function main() {
4199
5393
  if ((meshMethod || values["contour-hub"]) && format !== "glb") throw new Error("Mesh methods require GLB output.");
4200
5394
  if (values["contour-hub"] && meshMethod !== "contour") throw new Error("--contour-hub requires --mesh-method contour.");
4201
5395
  if (meshMethod === "contour" && profile && profile !== "silhouette") throw new Error("Contour extrusion uses the FRONT silhouette.");
5396
+ const views = prepareViews(await readInput(input, values.layout, threshold), threshold);
5397
+ const { nativeSamples } = inspectViews(views);
4202
5398
  const settings = {
4203
5399
  textureProjection,
4204
5400
  meshMethod,
4205
5401
  contourHub: values["contour-hub"],
4206
- layers: values.layers === void 0 ? void 0 : Number(values.layers),
4207
- resolution: values.resolution === void 0 ? void 0 : Number(values.resolution),
5402
+ layers: values.layers === "native" ? Math.max(8, nativeSamples.z) : Number(values.layers ?? DEFAULT_LAYERS),
5403
+ resolution: values.resolution === "native" || values.resolution === void 0 ? void 0 : Number(values.resolution),
4208
5404
  height: values.height === void 0 ? void 0 : Number(values.height),
4209
5405
  pivot: values.pivot,
4210
5406
  threshold,
4211
5407
  profile
4212
5408
  };
4213
- const views = await readInput(input, values.layout, threshold);
5409
+ if (values.resolution === "native") {
5410
+ const { size: [width, depth] } = reconstructionDimensions(views, settings);
5411
+ const samples2 = width === depth ? Math.max(nativeSamples.x, nativeSamples.y) : width > depth ? nativeSamples.x : nativeSamples.y;
5412
+ settings.resolution = Math.max(16, samples2);
5413
+ }
4214
5414
  const key = values["no-cache"] ? void 0 : buildCacheKey(views, format, settings, spacing);
4215
5415
  const cached = key ? await readBuildCache(key, format) : void 0;
4216
5416
  const artifact = cached ?? buildOutput(views, format, settings, spacing);
4217
5417
  if (artifact.format === "glb") {
4218
- await mkdir4(dirname3(output), { recursive: true });
4219
- await writeFile4(output, artifact.bytes);
5418
+ await mkdir6(dirname7(output), { recursive: true });
5419
+ await writeFile6(output, artifact.bytes);
4220
5420
  } else {
4221
- await mkdir4(output, { recursive: true });
4222
- await writeFile4(join4(output, "stack.png"), artifact.png);
4223
- await writeFile4(join4(output, "stack.json"), artifact.manifest);
5421
+ await mkdir6(output, { recursive: true });
5422
+ await writeFile6(join6(output, "stack.png"), artifact.png);
5423
+ await writeFile6(join6(output, "stack.json"), artifact.manifest);
4224
5424
  }
4225
5425
  if (key && !cached) await writeBuildCache(key, artifact);
4226
5426
  console.log(`Built ${format} at ${output}${cached ? " \xB7 disk cache" : ""}`);
4227
5427
  }
4228
5428
  function buildOutput(views, format, settings, spacing) {
4229
- const asset = reconstruct(views, format === "glb" ? "mesh" : "stack", settings);
5429
+ const asset = buildFromPreparedViews(views, format === "glb" ? "mesh" : "stack", settings);
4230
5430
  if (asset.target === "mesh") return { format: "glb", bytes: encodeGlb(asset) };
4231
5431
  const bundle = encodeStack(respaceStack(asset, spacing));
4232
5432
  return { format: "stack", png: bundle.png, manifest: JSON.stringify(bundle.manifest, null, 2) + "\n" };