topotopo 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/NOTICE +30 -0
  2. package/README.md +54 -16
  3. package/dist/cli.js +95 -14
  4. package/dist/core/analysis.d.ts +5 -1
  5. package/dist/core/analysis.js +8 -3
  6. package/dist/core/bake.d.ts +2 -5
  7. package/dist/core/bake.js +12 -25
  8. package/dist/core/bevel.js +165 -97
  9. package/dist/core/geometry.js +1 -1
  10. package/dist/core/imageops.d.ts +6 -0
  11. package/dist/core/imageops.js +51 -0
  12. package/dist/core/materials.d.ts +4 -0
  13. package/dist/core/materials.js +11 -0
  14. package/dist/core/packed.js +11 -0
  15. package/dist/core/particles.d.ts +1 -1
  16. package/dist/core/particles.js +1 -1
  17. package/dist/core/rbd.js +13 -1
  18. package/dist/core/scatter.d.ts +1 -1
  19. package/dist/core/scatter.js +1 -1
  20. package/dist/core/scene.d.ts +20 -0
  21. package/dist/core/scene.js +71 -0
  22. package/dist/core/snippet-lib.d.ts +1 -1
  23. package/dist/core/snippet-lib.js +1 -1
  24. package/dist/core/solidify.d.ts +38 -0
  25. package/dist/core/solidify.js +356 -0
  26. package/dist/core/tangents.d.ts +52 -0
  27. package/dist/core/tangents.js +214 -0
  28. package/dist/core/texcoord.d.ts +4 -0
  29. package/dist/core/texcoord.js +14 -0
  30. package/dist/core/topology.d.ts +22 -0
  31. package/dist/core/topology.js +70 -7
  32. package/dist/core/traceimage.d.ts +7 -0
  33. package/dist/core/traceimage.js +221 -0
  34. package/dist/core/tritri.d.ts +5 -0
  35. package/dist/core/tritri.js +120 -0
  36. package/dist/core/uv.d.ts +13 -0
  37. package/dist/core/uv.js +3 -3
  38. package/dist/core/uvreport.d.ts +66 -0
  39. package/dist/core/uvreport.js +308 -0
  40. package/dist/core/xatlas.js +32 -2
  41. package/dist/gallery/app/gallery.css +100 -0
  42. package/dist/gallery/app/gallery.js +80 -0
  43. package/dist/gallery/bake.d.ts +34 -0
  44. package/dist/gallery/bake.js +144 -0
  45. package/dist/gallery/cli.d.ts +4 -0
  46. package/dist/gallery/cli.js +157 -0
  47. package/dist/gallery/library.d.ts +124 -0
  48. package/dist/gallery/library.js +366 -0
  49. package/dist/gallery/pages.d.ts +94 -0
  50. package/dist/gallery/pages.js +148 -0
  51. package/dist/gallery/server.d.ts +21 -0
  52. package/dist/gallery/server.js +391 -0
  53. package/dist/graph/engine.js +14 -0
  54. package/dist/graph/types.d.ts +17 -0
  55. package/dist/host/artifacts.d.ts +21 -0
  56. package/dist/host/artifacts.js +58 -0
  57. package/dist/host/export-targets.d.ts +33 -0
  58. package/dist/host/export-targets.js +84 -0
  59. package/dist/index.d.ts +3 -1
  60. package/dist/index.js +2 -1
  61. package/dist/inspect.d.ts +6 -1
  62. package/dist/inspect.js +13 -1
  63. package/dist/io/common.d.ts +8 -0
  64. package/dist/io/gltf.js +236 -19
  65. package/dist/io/targets.d.ts +31 -0
  66. package/dist/io/targets.js +75 -0
  67. package/dist/mcp/docs.d.ts +1 -1
  68. package/dist/mcp/docs.js +73 -6
  69. package/dist/mcp/library.d.ts +12 -0
  70. package/dist/mcp/library.js +159 -0
  71. package/dist/mcp/server.js +29 -12
  72. package/dist/mcp/tools.d.ts +1 -1
  73. package/dist/mcp/tools.js +102 -43
  74. package/dist/nodes/bake.js +56 -36
  75. package/dist/nodes/bevel.js +4 -3
  76. package/dist/nodes/code.js +33 -7
  77. package/dist/nodes/curves.js +7 -0
  78. package/dist/nodes/generate.js +1 -1
  79. package/dist/nodes/imageops.d.ts +1 -0
  80. package/dist/nodes/imageops.js +206 -0
  81. package/dist/nodes/index.d.ts +3 -0
  82. package/dist/nodes/index.js +3 -0
  83. package/dist/nodes/material.js +3 -0
  84. package/dist/nodes/measure.js +3 -2
  85. package/dist/nodes/rbd.js +1 -1
  86. package/dist/nodes/scene.d.ts +1 -0
  87. package/dist/nodes/scene.js +53 -0
  88. package/dist/nodes/solidify.d.ts +1 -0
  89. package/dist/nodes/solidify.js +52 -0
  90. package/dist/nodes/transform.js +5 -1
  91. package/dist/nodes/util.d.ts +1 -1
  92. package/dist/nodes/wasmcall.js +1 -1
  93. package/dist/render/options.js +1 -1
  94. package/dist/render/pbr.d.ts +28 -0
  95. package/dist/render/pbr.js +378 -0
  96. package/dist/render/preview.d.ts +58 -0
  97. package/dist/render/preview.js +24 -0
  98. package/dist/render/raster.d.ts +12 -2
  99. package/dist/render/raster.js +98 -11
  100. package/dist/render/texview.d.ts +1 -1
  101. package/dist/render/texview.js +7 -2
  102. package/dist/viewer/app/camera.js +27 -7
  103. package/dist/viewer/app/embed.js +80 -0
  104. package/dist/viewer/app/export-popover.js +68 -0
  105. package/dist/viewer/app/grid.js +1 -1
  106. package/dist/viewer/app/guides.js +1 -1
  107. package/dist/viewer/app/image-view.js +114 -0
  108. package/dist/viewer/app/keymap.js +15 -3
  109. package/dist/viewer/app/layers.js +24 -5
  110. package/dist/viewer/app/main.js +71 -15
  111. package/dist/viewer/app/markers.js +1 -1
  112. package/dist/viewer/app/outliner.js +56 -15
  113. package/dist/viewer/app/outputs.css +73 -0
  114. package/dist/viewer/app/outputs.js +240 -0
  115. package/dist/viewer/app/props.js +1 -1
  116. package/dist/viewer/app/scene.js +6 -2
  117. package/dist/viewer/app/select.js +14 -3
  118. package/dist/viewer/app/selection.js +1 -1
  119. package/dist/viewer/app/status.js +20 -0
  120. package/dist/viewer/app/style.css +2 -1
  121. package/dist/viewer/app/units.js +1 -1
  122. package/dist/viewer/app/vars.js +1 -1
  123. package/dist/viewer/index.html +20 -6
  124. package/dist/viewer/outputs.d.ts +54 -0
  125. package/dist/viewer/outputs.js +436 -0
  126. package/dist/viewer/server.d.ts +19 -2
  127. package/dist/viewer/server.js +77 -9
  128. package/dist/workspace.d.ts +21 -2
  129. package/dist/workspace.js +124 -4
  130. package/kernels/pkg/README.md +21 -28
  131. package/kernels/pkg-simd/README.md +21 -28
  132. package/package.json +11 -4
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export type { CookReport, NodeResult, Issue } from './graph/engine.ts';
4
4
  export type { GraphSpec, NodeSpec, NodeDef, ParamDef } from './graph/types.ts';
5
5
  export { allNodeDefs, getNodeDef, CATEGORY_ORDER } from './graph/registry.ts';
6
6
  export { Geometry, GeoBuilder } from './core/geometry.ts';
7
- export { renderGeometry } from './render/raster.ts';
7
+ export { renderGeometry, renderGeometryAsync } from './render/raster.ts';
8
8
  export { encodePNG } from './render/png.ts';
9
9
  export { exportGeometry, exportGeometryAsync } from './io/export.ts';
10
10
  export type { ExportFormat, ExportOptions } from './io/export.ts';
@@ -23,3 +23,5 @@ export { decodePNG, inflateZlib, pngChannel } from './io/png-decode.ts';
23
23
  export { Image, imagesOf, findImage, imageToBytes } from './core/image.ts';
24
24
  export { imagePNG, texturesExport } from './io/textures.ts';
25
25
  export { summarize, inspect } from './inspect.ts';
26
+ export { uvReport } from './core/uvreport.ts';
27
+ export type { UVReport, UVReportOptions } from './core/uvreport.ts';
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import './nodes/index.js';
4
4
  export { Engine } from './graph/engine.js';
5
5
  export { allNodeDefs, getNodeDef, CATEGORY_ORDER } from './graph/registry.js';
6
6
  export { Geometry, GeoBuilder } from './core/geometry.js';
7
- export { renderGeometry } from './render/raster.js';
7
+ export { renderGeometry, renderGeometryAsync } from './render/raster.js';
8
8
  export { encodePNG } from './render/png.js';
9
9
  export { exportGeometry, exportGeometryAsync } from './io/export.js';
10
10
  export { importGeometry, importGeometryAsync } from './io/import.js';
@@ -18,3 +18,4 @@ export { decodePNG, inflateZlib, pngChannel } from './io/png-decode.js';
18
18
  export { Image, imagesOf, findImage, imageToBytes } from './core/image.js';
19
19
  export { imagePNG, texturesExport } from './io/textures.js';
20
20
  export { summarize, inspect } from './inspect.js';
21
+ export { uvReport } from './core/uvreport.js';
package/dist/inspect.d.ts CHANGED
@@ -1,11 +1,16 @@
1
1
  import { Geometry } from './core/geometry.ts';
2
2
  export declare function summarize(g: Geometry): string;
3
3
  export interface InspectOptions {
4
- detail?: 'summary' | 'attributes' | 'topology' | 'elements' | 'all';
4
+ /** 'uv': the structured uv report (core/uvreport.ts); not part of 'all' */
5
+ detail?: 'summary' | 'attributes' | 'topology' | 'elements' | 'all' | 'uv';
5
6
  cls?: 'point' | 'prim' | 'vertex' | 'detail' | 'edge';
6
7
  attribs?: string[];
7
8
  start?: number;
8
9
  count?: number;
9
10
  group?: string;
11
+ /** detail 'uv': uv attribute (default "uv"), texture size for texel density, and the report as JSON after the text */
12
+ uvAttrib?: string;
13
+ uvResolution?: number | [number, number];
14
+ json?: boolean;
10
15
  }
11
16
  export declare function inspect(g: Geometry, o?: InspectOptions): string;
package/dist/inspect.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // Text-first geometry introspection for LLMs: compact summaries, attribute statistics,
2
2
  // topology health, and element listings.
3
3
  import { Geometry } from './core/geometry.js';
4
- import { primArea, signedVolume, topologyReport } from './core/topology.js';
4
+ import { primArea, signedVolume, topologyReport, triangleReport } from './core/topology.js';
5
5
  import { evalGroup } from './core/groups.js';
6
6
  import { edgeList } from './core/edges.js';
7
7
  import { halfEdges } from './core/halfedge.js';
@@ -10,6 +10,7 @@ import { packedSummaryLine } from './core/packed.js';
10
10
  import { heightfieldSummary, volumeCounts } from './core/heightfield.js';
11
11
  import { imageSummary } from './core/image.js';
12
12
  import { sdfGridSummary } from './core/sdfgrid.js';
13
+ import { uvReport, uvReportText } from './core/uvreport.js';
13
14
  const n = (x) => x.toLocaleString('en-US');
14
15
  const v3 = (a) => `(${a.map(fmtNum).join(', ')})`;
15
16
  const typeCode = (a) => (a.isArray ? a.type : (a.type === 'float' ? 'f' : a.type === 'int' ? 'i' : 's') + a.size);
@@ -226,6 +227,11 @@ export function inspect(g, o = {}) {
226
227
  out.push('topology:');
227
228
  out.push(` ${r.closed ? 'CLOSED manifold surface (watertight)' : `open/non-manifold: ${r.boundaryEdges} boundary edges, ${r.nonManifoldEdges} non-manifold edges`}`);
228
229
  out.push(` ${r.pieces} connected piece(s); ${r.edges} edges; ${r.degenerate} degenerate prims; ${r.unusedPoints} unused points`);
230
+ const t = triangleReport(g);
231
+ if (t.triangles) {
232
+ const ids = (a) => (a.length ? ` (prims ${a.slice(0, 12).join(' ')}${a.length > 12 ? ' …' : ''})` : '');
233
+ out.push(` ${t.triangles} render/export triangles; min area ${fmtNum(t.minArea)}, min quality ${fmtNum(t.minQuality)}; ${t.degenerate} degenerate${ids(t.degeneratePrims)}, ${t.nearDegenerate} near-degenerate${ids(t.nearDegeneratePrims)}`);
234
+ }
229
235
  const flipped = halfEdges(g).flippedEdges.size;
230
236
  if (flipped)
231
237
  out.push(` ${flipped} edge(s) with inconsistent winding between neighbouring polygons (use reverse on part of the mesh or clean fix_winding)`);
@@ -236,6 +242,12 @@ export function inspect(g, o = {}) {
236
242
  if (r.closed && r.pieces === 1)
237
243
  out.push(` euler ${r.euler} → genus ${(2 - r.euler) / 2}`);
238
244
  }
245
+ if (detail === 'uv') {
246
+ const r = uvReport(g, { attribute: o.uvAttrib, resolution: o.uvResolution });
247
+ out.push(...uvReportText(r));
248
+ if (o.json)
249
+ out.push('uv report (JSON):', JSON.stringify(r));
250
+ }
239
251
  if ((detail === 'elements' || detail === 'all') && o.cls === 'edge')
240
252
  out.push(...edgeElements(g, o));
241
253
  else if (detail === 'elements' || detail === 'all') {
@@ -16,6 +16,14 @@ export interface ExportOptions {
16
16
  custom?: boolean;
17
17
  /** glTF: write NORMAL (N if present, else computed with cuspAngle). false = only when N exists. Default true. */
18
18
  normals?: boolean;
19
+ /**
20
+ * glTF TANGENT accessors (MikkTSpace, xyz + handedness w): 'auto' (default) generates them for primitives whose
21
+ * material has a normal map and writes a valid supplied point/vertex "tangent" (float[4]) attribute on the others
22
+ * (a malformed one is dropped with a warning); 'preserve' writes the supplied attribute everywhere it exists (a
23
+ * malformed one is an error) and generates only where it is missing on normal-mapped primitives; 'none' never
24
+ * writes TANGENT.
25
+ */
26
+ tangents?: 'auto' | 'preserve' | 'none';
19
27
  /** glTF: 'none' (default), 'meshopt' (EXT_meshopt_compression + KHR_mesh_quantization), 'draco' (needs draco3dgltf) */
20
28
  compress?: 'none' | 'meshopt' | 'draco';
21
29
  /** glTF: KHR_mesh_quantization (16-bit positions, 8-bit normals, 16-bit uv/colour) without compression */
package/dist/io/gltf.js CHANGED
@@ -12,7 +12,17 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
12
12
  // Export layout
13
13
  // one node + mesh per prim "name" (splitByName), one primitive per material within a mesh:
14
14
  // polygons → TRIANGLES, polylines → one LINE_STRIP per curve (or LINES), isolated points → POINTS.
15
- // POSITION · NORMAL (N, else computed) · TEXCOORD_0/1 from uv/uv2 (V flipped) · COLOR_0 from Cd (+Alpha → VEC4).
15
+ // Scene empties (isolated points marked scene_empty, core/scene.ts; the scene_null node) → nodes without a mesh, under
16
+ // their parent (the scene, another empty or a uniquely named mesh node), with the local TRS that reproduces their
17
+ // geometry-space transform; other set point attributes → node extras. Missing, ambiguous or cyclic parents, and
18
+ // parents that are GPU-instanced meshes, are errors.
19
+ // POSITION · NORMAL (N, else computed) · TANGENT (see below) · TEXCOORD_0/1 from uv/uv2 (V flipped, core/texcoord.ts)
20
+ // · COLOR_0 from Cd (+Alpha → VEC4).
21
+ // TANGENT (option tangents, default 'auto'): MikkTSpace tangents (core/tangents.ts) computed per triangle corner from
22
+ // the exported positions, normals and uv BEFORE vertices are welded, so uv seams, hard normals and mirrored islands
23
+ // keep their own frames, for every primitive whose material has a normal map; a supplied point/vertex "tangent"
24
+ // float[4] attribute is written on the others ('preserve': everywhere it exists). Collapsed or missing uvs are
25
+ // reported, never written as invalid tangents.
16
26
  // Custom attributes: every other numeric point/vertex attribute of size 1–4 becomes `_NAME` (upper-cased; float,
17
27
  // or the smallest integer type that holds an int attribute). The original names and types are kept in mesh
18
28
  // extras (topotopo.attributes), so imports restore them exactly. POINTS always carry pscale as `_PSCALE`.
@@ -43,11 +53,13 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
43
53
  // both the metallicRoughness and the occlusion texture (metallicFactor 1).
44
54
  //
45
55
  // Import
46
- // node hierarchy flattened with world transforms, EXT_mesh_gpu_instancing as packed prims (one source per mesh;
56
+ // node hierarchy flattened with world transforms (nodes without a mesh → scene empties: points with scene_empty 1,
57
+ // name, parent = the nearest imported ancestor, P / orient / scale in world space, extras as attributes), EXT_mesh_gpu_instancing as packed prims (one source per mesh;
47
58
  // instancing 'expand' = real geometry), every primitive mode,
48
59
  // meshopt (meshoptimizer decoder) and Draco (when draco3dgltf is installed) decoded, external .bin files read
49
60
  // relative to the file. Mesh/node names → prim "name", materials → prim "material" + table, COLOR_0 → Cd/Alpha,
50
- // TEXCOORD_0/1 → uv/uv2, custom `_X` → attributes, instance `_X` accessors → anchor attributes. Texture images are
61
+ // TEXCOORD_0/1 → uv/uv2, TANGENT → point "tangent" (float[4]; node transforms applied, w flipped under mirrors),
62
+ // custom `_X` → attributes, instance `_X` accessors → anchor attributes. Texture images are
51
63
  // not decoded: their paths (URI resolved against the file, or "embedded:<name>" for images inside a GLB) go into the
52
64
  // material table's textures entries; files written by topotopo restore the original paths from material extras,
53
65
  // and their "image:<name>" textures are decoded back into image volumes (8-bit precision).
@@ -56,8 +68,11 @@ import { ALL_EXTENSIONS, EXTMeshGPUInstancing, EXTMeshoptCompression, KHRDracoMe
56
68
  import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
57
69
  import { Attribute, AttribTable, Geometry, defaultValueFor } from '../core/geometry.js';
58
70
  import { resolveVertexNormals, triangulate } from '../core/topology.js';
59
- import { DEFAULT_MATERIAL, mergeMaterialTables, normalizeMaterial, primMaterials, texturePaths, writeMaterials } from '../core/materials.js';
60
- import { m4apply, m4applyDir, m4fromQuat, m4mul, m4normalMatrix, m4scale, m4translate } from '../core/math.js';
71
+ import { TANGENT_ATTRIB, cornerTangents, loadMikkTSpace, tangentProblem, transformTangents, vertexUV } from '../core/tangents.js';
72
+ import { gltfV } from '../core/texcoord.js';
73
+ import { DEFAULT_MATERIAL, materialAlphaMode, mergeMaterialTables, normalizeMaterial, primMaterials, texturePaths, writeMaterials } from '../core/materials.js';
74
+ import { m4apply, m4applyDir, m4fromQuat, m4invert, m4mul, m4normalMatrix, m4scale, m4translate } from '../core/math.js';
75
+ import { EMPTY_ATTRIB, PARENT_ATTRIB, sceneEmpties } from '../core/scene.js';
61
76
  import { INSTANCE_ATTRIB_SKIP, anchorAttribs, anchorValue, baseOf, decomposeXform, isolatedMask, packedSourceNames, pieces, xf, xfDir, xfLinear } from './common.js';
62
77
  import { DEFAULT_TRANSFER, expandPacked, flattenSource, packedFromMatrices, stripPacked, xform3 } from '../core/packed.js';
63
78
  import { hasSplinesDeep, splinesToPolylinesDeep } from '../core/splines.js';
@@ -67,7 +82,7 @@ import { imageRef } from '../core/image.js';
67
82
  /** Above this many polylines per material and mesh, curves go into one LINES primitive instead of LINE_STRIPs. */
68
83
  const MAX_LINE_STRIPS = 256;
69
84
  /** Attributes with a dedicated glTF semantic (never exported as `_NAME`). */
70
- const RESERVED = new Set(['P', 'N', 'uv', 'uv2', 'Cd', 'Alpha', 'material', 'name']);
85
+ const RESERVED = new Set(['P', 'N', 'uv', 'uv2', 'Cd', 'Alpha', 'material', 'name', TANGENT_ATTRIB]);
71
86
  const TYPES = ['SCALAR', 'VEC2', 'VEC3', 'VEC4'];
72
87
  const DRACO_MODULE = 'draco3dgltf';
73
88
  // ------------------------------------------------------------------ IO
@@ -171,14 +186,14 @@ function colorChannel(g) {
171
186
  const size = al ? 4 : 3;
172
187
  return {
173
188
  semantic: 'COLOR_0', size, int: false, perPoint: (!cd || cd.perPoint) && (!al || al.perPoint),
174
- read(v, pt, pr, out, o) {
189
+ read(v, pt, pr, out, o, k) {
175
190
  if (cd)
176
- cd.read(v, pt, pr, out, o);
191
+ cd.read(v, pt, pr, out, o, k);
177
192
  else {
178
193
  out[o] = out[o + 1] = out[o + 2] = 1;
179
194
  }
180
195
  if (al)
181
- al.read(v, pt, pr, out, o + 3);
196
+ al.read(v, pt, pr, out, o + 3, k);
182
197
  },
183
198
  };
184
199
  }
@@ -220,7 +235,7 @@ function emit(channels, corners, vprim, g, weld) {
220
235
  const v = corners[k];
221
236
  const pt = v >= 0 ? g.vertexPoint[v] : -1 - v;
222
237
  const pr = v >= 0 && vprim ? vprim[v] : -1;
223
- channels.forEach((c, ci) => c.read(v >= 0 ? v : -1, pt, pr, tmp[ci], 0));
238
+ channels.forEach((c, ci) => c.read(v >= 0 ? v : -1, pt, pr, tmp[ci], 0, k));
224
239
  let key = pt;
225
240
  if (weld && keyed.length) {
226
241
  let s = String(pt);
@@ -314,8 +329,9 @@ function getMaterial(st, name, vertexColors, blend, tint) {
314
329
  }
315
330
  else
316
331
  m.setEmissiveFactor([toLinear(mat.emissive[0]), toLinear(mat.emissive[1]), toLinear(mat.emissive[2])]);
317
- if (mat.alpha < 1 || blend)
318
- m.setAlphaMode('BLEND');
332
+ m.setAlphaMode(materialAlphaMode(mat, blend));
333
+ if (mat.alphaMode === 'MASK')
334
+ m.setAlphaCutoff(mat.alphaCutoff ?? 0.5);
319
335
  if (mat.unlit)
320
336
  m.setExtension('KHR_materials_unlit', st.doc.createExtension(KHRMaterialsUnlit).createUnlit());
321
337
  m.setExtras({ topotopo: isDefault ? { default: true } : { material: mat } });
@@ -323,7 +339,7 @@ function getMaterial(st, name, vertexColors, blend, tint) {
323
339
  return m;
324
340
  }
325
341
  /** Display (sRGB-encoded) value to linear and back: glTF's factors and COLOR_0 are linear, TopoTopo colours are display
326
- * values (docs/DESIGN.md, colour). */
342
+ * values. */
327
343
  const toLinear = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
328
344
  const toDisplay = (c) => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055);
329
345
  /** True when every element of a colour stream has the same rgb. */
@@ -345,6 +361,27 @@ const rgbAllOnes = (d, size) => {
345
361
  export function gltfDocument(g, o = {}) {
346
362
  if (hasSplinesDeep(g))
347
363
  g = splinesToPolylinesDeep(g).geo; // Bezier/NURBS prims (also in packed sources) as polylines
364
+ // scene empties become nodes, not POINTS
365
+ const empties = sceneEmpties(g);
366
+ if (empties.length) {
367
+ const keep = new Uint8Array(g.numPoints).fill(1);
368
+ for (const e of empties)
369
+ keep[e.point] = 0;
370
+ g = g.subsetPoints(keep);
371
+ // the empties' own attributes are no mesh data: merged meshes only hold their default fill
372
+ g.points.delete(EMPTY_ATTRIB);
373
+ for (const n of ['orient', 'scale']) {
374
+ const a = g.points.get(n);
375
+ if (!a || a.type !== 'float' || typeof a.def === 'string')
376
+ continue;
377
+ const d = a.def, sz = a.size, data = a.data;
378
+ let fill = true;
379
+ for (let i = 0; i < data.length && fill; i++)
380
+ fill = data[i] === d[i % sz] || data[i] === 0;
381
+ if (fill)
382
+ g.points.delete(n);
383
+ }
384
+ }
348
385
  const doc = new Document();
349
386
  doc.getRoot().getAsset().generator = 'topotopo';
350
387
  const buffer = doc.createBuffer();
@@ -358,6 +395,7 @@ export function gltfDocument(g, o = {}) {
358
395
  };
359
396
  let noUV = 0;
360
397
  const custom = o.custom !== false;
398
+ const tangentMode = o.tangents ?? 'auto';
361
399
  const lineMode = o.lineMode ?? 'strip';
362
400
  // what to write: the geometry, or (packed) its non-instanced part plus one instanced mesh per packed source
363
401
  const split = o.splitByName ?? true;
@@ -379,7 +417,7 @@ export function gltfDocument(g, o = {}) {
379
417
  semantic: 'POSITION', size: 3, int: false, perPoint: true,
380
418
  read(_v, pt, _pr, out, oo) { const P = geo.P; const p = xf(P[pt * 3], P[pt * 3 + 1], P[pt * 3 + 2], o); out[oo] = p[0]; out[oo + 1] = p[1]; out[oo + 2] = p[2]; },
381
419
  };
382
- const uvCh = (n, sem) => attribChannel(geo, n, sem, ['vertex', 'point', 'prim', 'detail'], (s, out, oo) => { out[oo] = s[0]; out[oo + 1] = 1 - (s[1] ?? 0); }, 2);
420
+ const uvCh = (n, sem) => attribChannel(geo, n, sem, ['vertex', 'point', 'prim', 'detail'], (s, out, oo) => { out[oo] = s[0]; out[oo + 1] = gltfV(s[1] ?? 0); }, 2);
383
421
  const color = colorChannel(geo);
384
422
  const customs = custom ? customChannels(geo, used, info) : [];
385
423
  // group prims by (closed, material)
@@ -425,6 +463,60 @@ export function gltfDocument(g, o = {}) {
425
463
  noUV++;
426
464
  }
427
465
  };
466
+ /**
467
+ * TANGENT of one triangle primitive (option tangents): the supplied tangent attribute where the mode takes it
468
+ * (validated), else MikkTSpace per corner for a normal-mapped material, else none.
469
+ */
470
+ const tangentChannel = (tris, nrm, mat, piece) => {
471
+ if (tangentMode === 'none')
472
+ return null;
473
+ const m = mat ? st.table[mat] : undefined;
474
+ const normalMapped = !!(m?.textures?.normal && textureFor(st, m.textures.normal));
475
+ const supplied = geo.findAttrib(TANGENT_ATTRIB, ['vertex', 'point']);
476
+ const where = `mesh "${piece}"${mat ? ` material "${mat}"` : ''}`;
477
+ if (supplied && (tangentMode === 'preserve' || !normalMapped)) {
478
+ const bad = tangentProblem(geo);
479
+ if (bad && tangentMode === 'preserve')
480
+ throw new Error(`glTF: tangents "preserve": ${where}: ${bad}`);
481
+ if (bad)
482
+ o.warn?.(`glTF: ${where}: supplied tangent attribute not written (${bad})`);
483
+ else if (!nrm)
484
+ o.warn?.(`glTF: ${where}: tangent attribute without NORMAL (normals: false): no TANGENT written`);
485
+ else {
486
+ const L = xfLinear([1, 0, 0, 0, 1, 0, 0, 0, 1], 0, o), tmp = new Float64Array(4);
487
+ return attribChannel(geo, TANGENT_ATTRIB, 'TANGENT', ['vertex', 'point'], (s, out, oo) => {
488
+ tmp[0] = s[0];
489
+ tmp[1] = s[1];
490
+ tmp[2] = s[2];
491
+ tmp[3] = s[3];
492
+ transformTangents(tmp, 1, L);
493
+ out[oo] = tmp[0];
494
+ out[oo + 1] = tmp[1];
495
+ out[oo + 2] = tmp[2];
496
+ out[oo + 3] = tmp[3];
497
+ }, 4);
498
+ }
499
+ }
500
+ if (!normalMapped)
501
+ return null;
502
+ if (!nrm) {
503
+ o.warn?.(`glTF: ${where}: normal map without NORMAL (normals: false): no TANGENT written`);
504
+ return null;
505
+ }
506
+ const uv = vertexUV(geo, 'uv');
507
+ if (!uv)
508
+ return null; // reported once, as a textured primitive without uv
509
+ const { tangents, diag } = cornerTangents(geo, tris, nrm, uv);
510
+ if (diag.uvNonFinite || diag.uvDegenerate) {
511
+ o.warn?.(`glTF: ${where}: ${diag.uvDegenerate} of ${diag.triangles} triangles have collapsed uvs${diag.uvNonFinite ? ` and ${diag.uvNonFinite} non-finite uvs` : ''}; their ${diag.fallbackCorners} corners get a fallback tangent (the normal map has no orientation there)`);
512
+ }
513
+ else if (diag.fallbackCorners)
514
+ o.warn?.(`glTF: ${where}: MikkTSpace left ${diag.fallbackCorners} corners without a tangent; a fallback was written`);
515
+ return {
516
+ semantic: 'TANGENT', size: 4, int: false, perPoint: false,
517
+ read(_v, _pt, _pr, out, oo, k) { const d = xfDir(tangents[k * 4], tangents[k * 4 + 1], tangents[k * 4 + 2], o); out[oo] = d[0]; out[oo + 1] = d[1]; out[oo + 2] = d[2]; out[oo + 3] = tangents[k * 4 + 3]; },
518
+ };
519
+ };
428
520
  for (const gr of groups.values()) {
429
521
  if (gr.closed) {
430
522
  const { tris } = triangulate(geo, gr.mask);
@@ -440,6 +532,9 @@ export function gltfDocument(g, o = {}) {
440
532
  chans.push({ semantic: 'NORMAL', size: 3, int: false, perPoint: pointN, read(v, _pt, _pr, out, oo) { const d = xfDir(nn[v * 3], nn[v * 3 + 1], nn[v * 3 + 2], o); out[oo] = d[0]; out[oo + 1] = d[1]; out[oo + 2] = d[2]; } });
441
533
  }
442
534
  const uv0 = uvCh('uv', 'TEXCOORD_0'), uv1 = uvCh('uv2', 'TEXCOORD_1');
535
+ const tan = tangentChannel(tris, normals, gr.mat, name);
536
+ if (tan)
537
+ chans.push(tan);
443
538
  if (uv0)
444
539
  chans.push(uv0);
445
540
  if (uv1)
@@ -528,12 +623,110 @@ export function gltfDocument(g, o = {}) {
528
623
  const w = writeMesh(doc, buffer, scene, name, outs, info, quantize);
529
624
  job.onMesh?.(w);
530
625
  }
626
+ if (empties.length)
627
+ writeEmpties(doc, scene, empties, o);
531
628
  if (quantize)
532
629
  doc.createExtension(KHRMeshQuantization).setRequired(true);
533
630
  if (noUV)
534
631
  o.warn?.(`glTF: ${noUV} primitive(s) use a textured material but have no uv attribute (add uv_project or uv_unwrap)`);
535
632
  return doc;
536
633
  }
634
+ /**
635
+ * Scene empties as meshless nodes. Parents resolve by name among the empties and the mesh nodes written so far; each
636
+ * node gets the local TRS that places it at its geometry-space transform (in export space: axis conversion, scale).
637
+ */
638
+ function writeEmpties(doc, scene, empties, o) {
639
+ const meshNodes = new Map();
640
+ for (const n of doc.getRoot().listNodes()) {
641
+ const l = meshNodes.get(n.getName());
642
+ if (l)
643
+ l.push(n);
644
+ else
645
+ meshNodes.set(n.getName(), [n]);
646
+ }
647
+ const byName = new Map();
648
+ for (const e of empties) {
649
+ if (!e.name)
650
+ throw new Error(`glTF: scene empty at point ${e.point} has no name`);
651
+ const l = byName.get(e.name);
652
+ if (l)
653
+ l.push(e);
654
+ else
655
+ byName.set(e.name, [e]);
656
+ }
657
+ const parentOf = new Map();
658
+ for (const e of empties) {
659
+ if (!e.parent) {
660
+ parentOf.set(e, null);
661
+ continue;
662
+ }
663
+ const es = byName.get(e.parent) ?? [], ms = meshNodes.get(e.parent) ?? [];
664
+ const where = `glTF: scene empty "${e.name}": parent "${e.parent}"`;
665
+ // without splitByName every mesh is merged into one node ("mesh"), so a named mesh parent no longer exists: the
666
+ // empty goes on the scene root, where its geometry-space transform places it the same (previews, viewers)
667
+ if (!es.length && !ms.length && o.splitByName === false) {
668
+ parentOf.set(e, null);
669
+ continue;
670
+ }
671
+ if (!es.length && !ms.length)
672
+ throw new Error(`${where} is neither an empty nor a mesh (meshes: ${[...meshNodes.keys()].slice(0, 12).join(', ') || 'none'}; empties: ${[...byName.keys()].slice(0, 12).join(', ')})`);
673
+ if (es.length + ms.length > 1)
674
+ throw new Error(`${where} is ambiguous: ${es.length} empt${es.length === 1 ? 'y' : 'ies'} and ${ms.length} mesh${ms.length === 1 ? '' : 'es'} have that name`);
675
+ if (ms.length && ms[0].getExtension('EXT_mesh_gpu_instancing'))
676
+ throw new Error(`${where} is a GPU-instanced mesh; parenting to an individual instance is not supported (parent to the scene or an empty instead)`);
677
+ parentOf.set(e, es.length ? { empty: es[0] } : { node: ms[0] });
678
+ }
679
+ for (const e of empties) {
680
+ const chain = [];
681
+ const seen = new Set();
682
+ for (let c = e; c;) {
683
+ if (seen.has(c))
684
+ throw new Error(`glTF: scene empties form a parent cycle: ${[...chain, c.name].join(' → ')}`);
685
+ seen.add(c);
686
+ chain.push(c.name);
687
+ const pr = parentOf.get(c);
688
+ c = pr && 'empty' in pr ? pr.empty : null;
689
+ }
690
+ }
691
+ // world matrix in export space: translation converted like positions, rotation conjugated by the axis change
692
+ const world = new Map();
693
+ for (const e of empties) {
694
+ const R = xfLinear(xform3(m4fromQuat(e.orient)), 0, o), t = xf(e.P[0], e.P[1], e.P[2], o);
695
+ const m = new Float64Array(16);
696
+ for (let c = 0; c < 3; c++)
697
+ for (let r = 0; r < 3; r++)
698
+ m[c * 4 + r] = R[c * 3 + r] * e.scale[c];
699
+ m[12] = t[0];
700
+ m[13] = t[1];
701
+ m[14] = t[2];
702
+ m[15] = 1;
703
+ world.set(e, m);
704
+ }
705
+ const made = new Map();
706
+ const make = (e) => {
707
+ const done = made.get(e);
708
+ if (done)
709
+ return done;
710
+ const pr = parentOf.get(e);
711
+ const parentNode = pr ? ('empty' in pr ? make(pr.empty) : pr.node) : null;
712
+ const pw = pr ? ('empty' in pr ? world.get(pr.empty) : Float64Array.from(pr.node.getWorldMatrix())) : null;
713
+ const local = pw ? m4mul(m4invert(pw), world.get(e)) : world.get(e);
714
+ const { q, s, shear } = decomposeXform(xform3(local));
715
+ if (shear)
716
+ o.warn?.(`glTF: scene empty "${e.name}": its transform relative to "${e.parent}" has shear (non-uniform parent scale with rotation); the nearest TRS was written`);
717
+ const node = doc.createNode(e.name).setTranslation([local[12], local[13], local[14]]).setRotation([q[0], q[1], q[2], q[3]]).setScale([s[0], s[1], s[2]]);
718
+ if (Object.keys(e.extras).length)
719
+ node.setExtras(e.extras);
720
+ if (parentNode)
721
+ parentNode.addChild(node);
722
+ else
723
+ scene.addChild(node);
724
+ made.set(e, node);
725
+ return node;
726
+ };
727
+ for (const e of empties)
728
+ make(e);
729
+ }
537
730
  /**
538
731
  * One job per packed source: its geometry (nested instances expanded) as a single mesh whose node gets
539
732
  * EXT_mesh_gpu_instancing with every instance's TRS in export space (axis conversion and scale applied).
@@ -736,8 +929,8 @@ function writeMesh(doc, buffer, scene, name, outs, info, quantize) {
736
929
  q[i] = Math.round(Math.max(-1, Math.min(1, (d[i] - center[i % 3]) / extent)) * 32767);
737
930
  a = acc(q, 3, true);
738
931
  }
739
- else if (ch.semantic === 'NORMAL' && quantize) {
740
- a = acc(Int8Array.from(d, (x) => Math.round(Math.max(-1, Math.min(1, x)) * 127)), 3, true);
932
+ else if ((ch.semantic === 'NORMAL' || ch.semantic === 'TANGENT') && quantize) {
933
+ a = acc(Int8Array.from(d, (x) => Math.round(Math.max(-1, Math.min(1, x)) * 127)), ch.size, true);
741
934
  }
742
935
  else if (ch.semantic.startsWith('TEXCOORD_') && quantize && d.every((x) => x >= 0 && x <= 1)) {
743
936
  a = acc(Uint16Array.from(d, (x) => Math.round(x * 65535)), 2, true);
@@ -823,6 +1016,8 @@ async function withTextures(g, o) {
823
1016
  /** GLB bytes. */
824
1017
  export async function exportGLB(g, o = {}) {
825
1018
  o = await withTextures(g, o);
1019
+ if (o.tangents !== 'none')
1020
+ await loadMikkTSpace();
826
1021
  const doc = gltfDocument(g, o);
827
1022
  const io = await exportIO(doc, o);
828
1023
  return io.writeBinary(doc);
@@ -830,6 +1025,8 @@ export async function exportGLB(g, o = {}) {
830
1025
  /** Self-contained .gltf JSON text (buffers embedded as data URIs). */
831
1026
  export async function exportGLTF(g, o = {}) {
832
1027
  o = await withTextures(g, o);
1028
+ if (o.tangents !== 'none')
1029
+ await loadMikkTSpace();
833
1030
  const doc = gltfDocument(g, o);
834
1031
  const io = await exportIO(doc, o);
835
1032
  const { json, resources } = await io.writeJSON(doc, { format: 'GLTF' });
@@ -916,6 +1113,7 @@ function materialEntry(m, base = '', index = () => 0) {
916
1113
  baseColor: [toDisplay(bc[0]), toDisplay(bc[1]), toDisplay(bc[2])], metallic: m.getMetallicFactor(), roughness: m.getRoughnessFactor(),
917
1114
  emissive: [toDisplay(em[0]) * strength, toDisplay(em[1]) * strength, toDisplay(em[2]) * strength], alpha: bc[3],
918
1115
  doubleSided: m.getDoubleSided(), unlit: !!m.getExtension('KHR_materials_unlit'),
1116
+ alphaMode: m.getAlphaMode(), alphaCutoff: m.getAlphaCutoff(),
919
1117
  textures: {
920
1118
  baseColor: texturePathOf(m.getBaseColorTexture(), base, index),
921
1119
  normal: texturePathOf(m.getNormalTexture(), base, index),
@@ -997,8 +1195,10 @@ function primitiveGeometry(prim, attrInfo, warn) {
997
1195
  continue;
998
1196
  if (sem === 'NORMAL')
999
1197
  setPt('N', a, 3, 'float');
1198
+ else if (sem === 'TANGENT' && es === 4)
1199
+ setPt(TANGENT_ATTRIB, a, 4, 'float');
1000
1200
  else if (sem === 'TEXCOORD_0' || sem === 'TEXCOORD_1')
1001
- setPt(sem === 'TEXCOORD_0' ? 'uv' : 'uv2', a, 3, 'float', (s, i, out) => { out[i * 3] = s[i * es]; out[i * 3 + 1] = 1 - s[i * es + 1]; out[i * 3 + 2] = 0; });
1201
+ setPt(sem === 'TEXCOORD_0' ? 'uv' : 'uv2', a, 3, 'float', (s, i, out) => { out[i * 3] = s[i * es]; out[i * 3 + 1] = gltfV(s[i * es + 1]); out[i * 3 + 2] = 0; });
1002
1202
  else if (sem === 'COLOR_0') {
1003
1203
  // COLOR_0 is linear; Cd holds display values
1004
1204
  setPt('Cd', a, 3, 'float', (s, i, out) => { out[i * 3] = toDisplay(s[i * es]); out[i * 3 + 1] = toDisplay(s[i * es + 1]); out[i * 3 + 2] = toDisplay(s[i * es + 2]); });
@@ -1010,7 +1210,7 @@ function primitiveGeometry(prim, attrInfo, warn) {
1010
1210
  const name = inf?.name ?? sem.slice(1).toLowerCase();
1011
1211
  setPt(name, a, es, inf?.type === 'int' ? 'int' : 'float');
1012
1212
  }
1013
- // TANGENT, JOINTS_n, WEIGHTS_n, TEXCOORD_2+, COLOR_1+ are not imported
1213
+ // JOINTS_n, WEIGHTS_n, TEXCOORD_2+, COLOR_1+ are not imported
1014
1214
  }
1015
1215
  // a constant Cd that the exporter folded into the material factor comes back as the point colour it was
1016
1216
  const folded = prim.getExtras()?.topotopo?.Cd;
@@ -1042,6 +1242,9 @@ function transformGeo(local, m) {
1042
1242
  d[i + 2] /= l;
1043
1243
  }
1044
1244
  }
1245
+ const T = g.points.get(TANGENT_ATTRIB);
1246
+ if (T && T.size === 4)
1247
+ transformTangents(T.data, g.numPoints, xform3(m));
1045
1248
  return g;
1046
1249
  }
1047
1250
  /** EXT_mesh_gpu_instancing: one matrix per instance (TRANSLATION · ROTATION · SCALE). */
@@ -1058,7 +1261,19 @@ function instanceMatrices(inst) {
1058
1261
  }
1059
1262
  return out;
1060
1263
  }
1061
- const RESERVED_EXTRAS = new Set('P N uv uv2 Cd Alpha material name path orient scale pscale'.split(' '));
1264
+ const RESERVED_EXTRAS = new Set(`P N uv uv2 Cd Alpha material name path orient scale pscale ${EMPTY_ATTRIB} ${PARENT_ATTRIB}`.split(' '));
1265
+ /**
1266
+ * The parent an imported empty refers to: the name (node name, else its mesh's) of the nearest ancestor that is imported
1267
+ * as an empty or a mesh; cameras, lights and GPU-instanced meshes are skipped (the world transform is kept either way).
1268
+ */
1269
+ function importedParent(node) {
1270
+ for (let p = node.getParentNode(); p; p = p.getParentNode()) {
1271
+ if (p.getCamera() || p.getExtension('KHR_lights_punctual') || p.getExtension('EXT_mesh_gpu_instancing'))
1272
+ continue;
1273
+ return p.getName() || p.getMesh()?.getName() || '';
1274
+ }
1275
+ return '';
1276
+ }
1062
1277
  function constantAttribute(table, name, type, size, value) {
1063
1278
  const a = table.add(name, type, size);
1064
1279
  for (let i = 0; i < table.count; i++)
@@ -1144,7 +1359,9 @@ export function documentToGeometry(doc, warn = () => { }, instancing = 'packed',
1144
1359
  if (!mesh) {
1145
1360
  const g = new Geometry({ positions: [world[12], world[13], world[14]] });
1146
1361
  const { q, s } = decomposeXform(xform3(world));
1362
+ constantAttribute(g.points, EMPTY_ATTRIB, 'int', 1, 1);
1147
1363
  constantAttribute(g.points, 'name', 'string', 1, node.getName());
1364
+ constantAttribute(g.points, PARENT_ATTRIB, 'string', 1, importedParent(node));
1148
1365
  constantAttribute(g.points, 'path', 'string', 1, path);
1149
1366
  constantAttribute(g.points, 'orient', 'float', 4, q);
1150
1367
  constantAttribute(g.points, 'scale', 'float', 3, s);
@@ -0,0 +1,31 @@
1
+ import type { ExportFormat } from './export.ts';
2
+ import type { ExportTarget, GraphSpec } from '../graph/types.ts';
3
+ /** Every export format with the label the viewer shows, in the order it offers them (a Record, so none is missing). */
4
+ export declare const FORMAT_LABELS: Record<ExportFormat, string>;
5
+ export declare const TARGET_FORMATS: ExportFormat[];
6
+ /** The extension a target's file gets: '' for unreal_landscape and textures, which write a folder. */
7
+ export declare const targetExtension: (format: ExportFormat) => string;
8
+ /** A format name in canonical form ("USD" → usda), or null. */
9
+ export declare function targetFormat(f: unknown): ExportFormat | null;
10
+ /** Why a target is invalid, or null when it is valid. */
11
+ export declare function targetError(t: unknown): string | null;
12
+ export interface ResolvedTarget {
13
+ format: ExportFormat;
14
+ /** posix path inside exports/: a file, or a folder for unreal_landscape and textures */
15
+ path: string;
16
+ /** the export tool's options (up_axis, scale, …) */
17
+ options: Record<string, unknown>;
18
+ }
19
+ /** A file name stem from an output id or graph name. */
20
+ export declare const fileStem: (s: string) => string;
21
+ /** A valid target with its path filled in: <stem><extension> unless it names one. */
22
+ export declare function resolveTarget(t: ExportTarget, stem: string): ResolvedTarget;
23
+ export interface PublishedOutput {
24
+ /** null for the graph's default output (graph.export), else the id in graph.outputs */
25
+ output: string | null;
26
+ node: string;
27
+ label: string;
28
+ target: ResolvedTarget | null;
29
+ }
30
+ /** A graph's default output (its files named after the graph) and its named outputs, each with its target if valid. */
31
+ export declare function publishedOutputs(graph: string, spec: GraphSpec, defaultNode: string): PublishedOutput[];
@@ -0,0 +1,75 @@
1
+ /** Every export format with the label the viewer shows, in the order it offers them (a Record, so none is missing). */
2
+ export const FORMAT_LABELS = {
3
+ glb: 'GLB (one file, textures inside)', gltf: 'glTF + texture files', usda: 'USD (.usda)', obj: 'OBJ', geo: 'Houdini .geo',
4
+ unreal_landscape: 'Unreal Landscape bundle (folder)', csv: 'CSV points (Unreal PCG)', pointsjson: 'Points JSON',
5
+ textures: 'PNG textures (folder)', png16: 'Heightmap, 16-bit PNG', r16: 'Heightmap, RAW .r16', mask_png: 'Masks, PNG',
6
+ ply: 'PLY', stl: 'STL', json: 'TopoTopo JSON',
7
+ };
8
+ export const TARGET_FORMATS = Object.keys(FORMAT_LABELS);
9
+ const EXTENSIONS = { unreal_landscape: '', textures: '', png16: '.png', mask_png: '.png', pointsjson: '.points.json' };
10
+ /** The extension a target's file gets: '' for unreal_landscape and textures, which write a folder. */
11
+ export const targetExtension = (format) => EXTENSIONS[format] ?? '.' + format;
12
+ /** A format name in canonical form ("USD" → usda), or null. */
13
+ export function targetFormat(f) {
14
+ const s = typeof f === 'string' ? f.trim().toLowerCase() : '';
15
+ const c = s === 'usd' ? 'usda' : s;
16
+ return Object.hasOwn(FORMAT_LABELS, c) ? c : null;
17
+ }
18
+ // the export tool's options (src/mcp/tools.ts), by value type
19
+ const BOOLEAN = ['split_by_name', 'materials', 'custom_attribs', 'quantize', 'pcg', 'pcg_struct', 'meshes'];
20
+ const CHOICES = { up_axis: ['y', 'z'], compress: ['none', 'meshopt', 'draco'], tangents: ['auto', 'preserve', 'none'], instancing: ['packed', 'expand'], instances: ['rows', 'expand'], precision: [32, 64] };
21
+ const NUMBER = ['scale', 'height_min', 'height_max', 'tile_size', 'heightfield'];
22
+ const NAMES = ['attributes', 'layers'];
23
+ const OPTIONS = [...BOOLEAN, ...Object.keys(CHOICES), ...NUMBER, ...NAMES, 'layer'];
24
+ /** A path segment Windows and POSIX both accept, and that cannot climb out of exports/. */
25
+ const segmentOk = (s) => !!s && s !== '.' && s !== '..' && !/[<>:"|?*\x00-\x1f]/.test(s) && !/[. ]$/.test(s) && !/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(s);
26
+ const pathOk = (p) => typeof p === 'string' && p.length <= 240 && !/^[A-Za-z]:|^[\\/]/.test(p) && p.replace(/\\/g, '/').split('/').every(segmentOk);
27
+ /** Why a target is invalid, or null when it is valid. */
28
+ export function targetError(t) {
29
+ const o = typeof t === 'string' ? { format: t } : t;
30
+ if (!o || typeof o !== 'object' || Array.isArray(o))
31
+ return 'export must be a format name ("glb") or {format, path?, ...options}';
32
+ if (!targetFormat(o.format))
33
+ return `export format "${o.format}" is not one of ${TARGET_FORMATS.join(', ')} (or usd)`;
34
+ if (o.path !== undefined && !pathOk(o.path))
35
+ return `export path "${o.path}" must stay inside exports/: relative, without "..", a drive or a leading slash`;
36
+ for (const [k, v] of Object.entries(o)) {
37
+ if (k === 'format' || k === 'path')
38
+ continue;
39
+ if (!OPTIONS.includes(k))
40
+ return `unknown export option "${k}" (options: ${OPTIONS.join(', ')})`;
41
+ if (BOOLEAN.includes(k) && typeof v !== 'boolean')
42
+ return `export option ${k} must be true or false`;
43
+ if (k in CHOICES && !CHOICES[k].includes(v))
44
+ return `export option ${k} must be one of ${CHOICES[k].join(', ')}`;
45
+ if (NUMBER.includes(k) && !(typeof v === 'number' && Number.isFinite(v)))
46
+ return `export option ${k} must be a number`;
47
+ if (k === 'scale' && !(v > 0))
48
+ return 'export option scale must be positive';
49
+ if (NAMES.includes(k) && !(Array.isArray(v) && v.every((s) => typeof s === 'string')))
50
+ return `export option ${k} must be a list of names`;
51
+ if (k === 'layer' && typeof v !== 'string')
52
+ return 'export option layer must be a name';
53
+ }
54
+ return null;
55
+ }
56
+ /** A file name stem from an output id or graph name. */
57
+ export const fileStem = (s) => s.replace(/[^A-Za-z0-9_.-]+/g, '_').replace(/^\.+|[. ]+$/g, '') || 'output';
58
+ /** A valid target with its path filled in: <stem><extension> unless it names one. */
59
+ export function resolveTarget(t, stem) {
60
+ const { format, path, ...options } = typeof t === 'string' ? { format: t } : t;
61
+ const f = targetFormat(format);
62
+ return { format: f, path: (typeof path === 'string' ? path : fileStem(stem) + targetExtension(f)).replace(/\\/g, '/'), options };
63
+ }
64
+ /** A graph's default output (its files named after the graph) and its named outputs, each with its target if valid. */
65
+ export function publishedOutputs(graph, spec, defaultNode) {
66
+ const valid = (t) => (t !== undefined && t !== null && !targetError(t) ? t : null);
67
+ const main = valid(spec.export);
68
+ return [
69
+ { output: null, node: defaultNode, label: 'Main output', target: main ? resolveTarget(main, graph) : null },
70
+ ...Object.entries(spec.outputs ?? {}).map(([id, o]) => {
71
+ const t = valid(o?.export);
72
+ return { output: id, node: o.node, label: o.label ?? id, target: t ? resolveTarget(t, id) : null };
73
+ }),
74
+ ];
75
+ }