topotopo 0.3.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 (119) hide show
  1. package/NOTICE +30 -0
  2. package/README.md +35 -14
  3. package/dist/cli.js +28 -10
  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/host/export-targets.js +1 -1
  54. package/dist/index.d.ts +3 -1
  55. package/dist/index.js +2 -1
  56. package/dist/inspect.d.ts +6 -1
  57. package/dist/inspect.js +13 -1
  58. package/dist/io/common.d.ts +8 -0
  59. package/dist/io/gltf.js +236 -19
  60. package/dist/io/targets.js +1 -1
  61. package/dist/mcp/docs.d.ts +1 -1
  62. package/dist/mcp/docs.js +58 -4
  63. package/dist/mcp/library.d.ts +12 -0
  64. package/dist/mcp/library.js +159 -0
  65. package/dist/mcp/server.js +29 -12
  66. package/dist/mcp/tools.js +16 -10
  67. package/dist/nodes/bake.js +56 -36
  68. package/dist/nodes/bevel.js +4 -3
  69. package/dist/nodes/code.js +1 -1
  70. package/dist/nodes/curves.js +7 -0
  71. package/dist/nodes/generate.js +1 -1
  72. package/dist/nodes/imageops.d.ts +1 -0
  73. package/dist/nodes/imageops.js +206 -0
  74. package/dist/nodes/index.d.ts +3 -0
  75. package/dist/nodes/index.js +3 -0
  76. package/dist/nodes/material.js +3 -0
  77. package/dist/nodes/measure.js +3 -2
  78. package/dist/nodes/rbd.js +1 -1
  79. package/dist/nodes/scene.d.ts +1 -0
  80. package/dist/nodes/scene.js +53 -0
  81. package/dist/nodes/solidify.d.ts +1 -0
  82. package/dist/nodes/solidify.js +52 -0
  83. package/dist/nodes/transform.js +5 -1
  84. package/dist/nodes/util.d.ts +1 -1
  85. package/dist/nodes/wasmcall.js +1 -1
  86. package/dist/render/options.js +1 -1
  87. package/dist/render/pbr.d.ts +28 -0
  88. package/dist/render/pbr.js +378 -0
  89. package/dist/render/preview.d.ts +58 -0
  90. package/dist/render/preview.js +24 -0
  91. package/dist/render/raster.d.ts +12 -2
  92. package/dist/render/raster.js +98 -11
  93. package/dist/render/texview.d.ts +1 -1
  94. package/dist/render/texview.js +7 -2
  95. package/dist/viewer/app/camera.js +1 -1
  96. package/dist/viewer/app/embed.js +80 -0
  97. package/dist/viewer/app/grid.js +1 -1
  98. package/dist/viewer/app/guides.js +1 -1
  99. package/dist/viewer/app/keymap.js +1 -1
  100. package/dist/viewer/app/layers.js +1 -1
  101. package/dist/viewer/app/main.js +1 -1
  102. package/dist/viewer/app/markers.js +1 -1
  103. package/dist/viewer/app/outliner.js +1 -1
  104. package/dist/viewer/app/props.js +1 -1
  105. package/dist/viewer/app/scene.js +6 -2
  106. package/dist/viewer/app/select.js +1 -1
  107. package/dist/viewer/app/selection.js +1 -1
  108. package/dist/viewer/app/status.js +1 -1
  109. package/dist/viewer/app/style.css +1 -1
  110. package/dist/viewer/app/units.js +1 -1
  111. package/dist/viewer/app/vars.js +1 -1
  112. package/dist/viewer/index.html +1 -1
  113. package/dist/viewer/server.d.ts +14 -2
  114. package/dist/viewer/server.js +30 -10
  115. package/dist/workspace.d.ts +13 -0
  116. package/dist/workspace.js +87 -1
  117. package/kernels/pkg/README.md +21 -28
  118. package/kernels/pkg-simd/README.md +21 -28
  119. package/package.json +9 -3
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);
@@ -17,7 +17,7 @@ export function targetFormat(f) {
17
17
  }
18
18
  // the export tool's options (src/mcp/tools.ts), by value type
19
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'], instancing: ['packed', 'expand'], instances: ['rows', 'expand'], precision: [32, 64] };
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
21
  const NUMBER = ['scale', 'height_min', 'height_max', 'tile_size', 'heightfield'];
22
22
  const NAMES = ['attributes', 'layers'];
23
23
  const OPTIONS = [...BOOLEAN, ...Object.keys(CHOICES), ...NUMBER, ...NAMES, 'layer'];
@@ -1,5 +1,5 @@
1
1
  import type { GraphSpec, NodeDef } from '../graph/types.ts';
2
- export declare const INSTRUCTIONS = "TopoTopo: a procedural geometry engine (Houdini-SOP style) you drive with JSON node graphs.\n\nWORKFLOW\n0. inputs {action:\"list\"} \u2192 the person's own files in the workspace inputs/ folder (guide curves, sites, zones, blockouts, PNG masks). Building a landscape or scene: look there first and build on them (help topic \"inputs\").\n1. catalog \u2192 see node types (100+, Houdini names work as aliases: copytopoints, attribwrangle, polyextrude, mountain\u2026).\n2. help {nodes:[...]} for exact params before using unfamiliar nodes; help {topic:\"wrangle\"|\"graph\"|\"recipes\"\u2026} for concepts.\n3. build {graph} the WHOLE network in one call (dry_run:true validates without cooking). Every response reports errors per node with did-you-mean hints.\n4. render to SEE it (quad view: persp/front/right/top; backfaces are tinted blue = flipped normals; views \"quad_uv\" + checker:true for UVs; overlays for specific questions: wireframe \"hard\"/\"boundary\", views \"section\", glyphs \"N\", label_groups, shading \"matcap\", see help topic \"render\"). inspect for numbers (bbox, attributes, watertightness).\n5. edit {ops} for incremental changes (set params, insert nodes, rewire) \u2014 only downstream nodes re-cook.\n6. export to glb/gltf (materials, textures, meshopt), geo (Houdini), csv (Unreal PCG points / instance rows), points.json, usda, obj/ply/stl/json for Unreal, Blender, Houdini; unreal_landscape = a whole terrain scene for Unreal.\n7. verify: assert nodes guard invariants in the graph (watertight, counts, bbox, expr); explain {graph} reads a result in words; diff {a, b} shows what an edit changed. See help topic \"verify\".\nOUTPUTS: publish intended deliverables in graph.outputs: {\"rotor\":{\"node\":\"rotor_final\",\"label\":\"Rotor\"}}. The default graph.output stays unchanged. The viewer lists every graph and named result, its generated textures and image layers; clicking a result isolates it. Rendered images and exports are saved and visible too. Use descriptive names; keep intermediate work in the node outliner. Rename/remove edits maintain published references.\nINSTANCING: copy_to_points {pack:true} / pack make packed instances (millions stay cheap; glb, usda and geo export them as instances, csv/points.json as one row per instance). See help topic \"instancing\".\nPCG: mask \u2192 scatter {density_mask} \u2192 orient \u2192 prune \u2192 copy_to_points {pack, variants, variant_weights}; points_along_curve, cluster, attribute_from_map. See help topic \"pcg\".\nCURVES: bezier / nurbs make spline prims (CVs + order, exact everywhere); convert_curve, resample, fillet_curve, offset_curve_3d, project_curve (roads on terrain), spline_fit, curve_attribs (curveu, frames, ramps). See help topic \"curves\".\nCLOTH: drape {steps} simulates a mesh as cloth over a collider (input 1) and the floor, from pins (pin_group / input 2) and in wind; inflate {pressure} puffs a closed mesh into a cushion or balloon. See help topic \"cloth\".\n\nCONVENTIONS: Y-up, metres, angles in degrees (wrangle trig uses radians). Houdini attribute names (P N Cd uv pscale orient up scale width name class piece). Polygons are closed prims, polylines are open prims.\nGRAPH: {\"nodes\": {\"name\": {\"type\": \"...\", \"in\": [\"upstream\", ...], \"params\": {...}}}, \"output\": \"name\", \"vars\": {\"k\": 1}}. Params accept \"=expr\" using vars (e.g. \"=height*0.5\"), time (frame, time) and other nodes (npoints('pts'), bbox('base').size.y, ch('box1/size')).\nHUMANS TUNE VARS: declare \"params\" for the 3\u20138 vars a person would tune ({\"k\": {type, desc, min, max, options, label, step}}); the live viewer (preview) shows them as sliders and menus. People change vars at any time, so read the graph (graphs {action:\"get\"}) before assuming a var's value. See help topic \"graph\".\nTIME: build/edit/render/inspect/export take \"frame\" (default 1). solver = per-frame feedback (growth, accumulation). See help topic \"time\".\nPARTICLES: particles(emitter points, collision mesh, field) = Houdini POPs in one node: emission, gravity/drag/wind, curl noise, fields, floor and mesh collisions, trails as polylines; steps with the frame. See help topic \"particles\".\nESCAPE HATCHES: wrangle (per-element JS with @P/@Cd syntax), script (whole-geometry JS with the engine library), sdf_expr (signed distance functions). If a node is missing, write it with these.\nTERRAIN: heightfield \u2192 heightfield_noise \u2192 heightfield_erode \u2192 masks / heightfield_path \u2192 heightfield_scatter + copy_to_points, heightfield_to_mesh; export png16 for an Unreal Landscape, or unreal_landscape for the landscape + layers + instances bundle. See help topic \"heightfield\".\nPHYSICS: rbd_settle drops pieces (packed instances) onto a terrain/container/ground until they rest, so scattered rocks and props sit in contact; rbd_stack drops them one at a time into piles. See help topic \"rbd\".";
2
+ export declare const INSTRUCTIONS = "TopoTopo: a procedural geometry engine (Houdini-SOP style) you drive with JSON node graphs.\n\nWORKFLOW\n0. inputs {action:\"list\"} \u2192 the person's own files in the workspace inputs/ folder (guide curves, sites, zones, blockouts, PNG masks). Building a landscape or scene: look there first and build on them (help topic \"inputs\").\n1. catalog \u2192 see node types (100+, Houdini names work as aliases: copytopoints, attribwrangle, polyextrude, mountain\u2026).\n2. help {nodes:[...]} for exact params before using unfamiliar nodes; help {topic:\"wrangle\"|\"graph\"|\"recipes\"\u2026} for concepts.\n3. build {graph} the WHOLE network in one call (dry_run:true validates without cooking). Every response reports errors per node with did-you-mean hints.\n4. render to SEE it (quad view: persp/front/right/top; backfaces are tinted blue = flipped normals; views \"quad_uv\" + checker:true for UVs; overlays for specific questions: wireframe \"hard\"/\"boundary\", views \"section\", glyphs \"N\", label_groups, shading \"matcap\", see help topic \"render\"). inspect for numbers (bbox, attributes, watertightness).\n5. edit {ops} for incremental changes (set params, insert nodes, rewire) \u2014 only downstream nodes re-cook.\n6. export to glb/gltf (materials, textures, meshopt), geo (Houdini), csv (Unreal PCG points / instance rows), points.json, usda, obj/ply/stl/json for Unreal, Blender, Houdini; unreal_landscape = a whole terrain scene for Unreal.\n7. verify: assert nodes guard invariants in the graph (watertight, counts, bbox, expr); explain {graph} reads a result in words; diff {a, b} shows what an edit changed. See help topic \"verify\".\nOUTPUTS: publish intended deliverables in graph.outputs: {\"rotor\":{\"node\":\"rotor_final\",\"label\":\"Rotor\"}}. The default graph.output stays unchanged. The viewer lists every graph and named result, its generated textures and image layers; clicking a result isolates it. Rendered images and exports are saved and visible too. Use descriptive names; keep intermediate work in the node outliner. Rename/remove edits maintain published references.\nINSTANCING: copy_to_points {pack:true} / pack make packed instances (millions stay cheap; glb, usda and geo export them as instances, csv/points.json as one row per instance). See help topic \"instancing\".\nPCG: mask \u2192 scatter {density_mask} \u2192 orient \u2192 prune \u2192 copy_to_points {pack, variants, variant_weights}; points_along_curve, cluster, attribute_from_map. See help topic \"pcg\".\nCURVES: bezier / nurbs make spline prims (CVs + order, exact everywhere); convert_curve, resample, fillet_curve, offset_curve_3d, project_curve (roads on terrain), spline_fit, curve_attribs (curveu, frames, ramps). See help topic \"curves\".\nCLOTH: drape {steps} simulates a mesh as cloth over a collider (input 1) and the floor, from pins (pin_group / input 2) and in wind; inflate {pressure} puffs a closed mesh into a cushion or balloon. See help topic \"cloth\".\n\nCONVENTIONS: Y-up, metres, angles in degrees (wrangle trig uses radians). Houdini attribute names (P N Cd uv pscale orient up scale width name class piece). Polygons are closed prims, polylines are open prims.\nGRAPH: {\"nodes\": {\"name\": {\"type\": \"...\", \"in\": [\"upstream\", ...], \"params\": {...}}}, \"output\": \"name\", \"vars\": {\"k\": 1}}. Params accept \"=expr\" using vars (e.g. \"=height*0.5\"), time (frame, time) and other nodes (npoints('pts'), bbox('base').size.y, ch('box1/size')).\nHUMANS TUNE VARS: declare \"params\" for the 3\u20138 vars a person would tune ({\"k\": {type, desc, min, max, options, label, step}}); the live viewer (preview) shows them as sliders and menus. People change vars at any time, so read the graph (graphs {action:\"get\"}) before assuming a var's value. See help topic \"graph\".\nTIME: build/edit/render/inspect/export take \"frame\" (default 1). solver = per-frame feedback (growth, accumulation). See help topic \"time\".\nPARTICLES: particles(emitter points, collision mesh, field) = Houdini POPs in one node: emission, gravity/drag/wind, curl noise, fields, floor and mesh collisions, trails as polylines; steps with the frame. See help topic \"particles\".\nESCAPE HATCHES: wrangle (per-element JS with @P/@Cd syntax), script (whole-geometry JS with the engine library), sdf_expr (signed distance functions). If a node is missing, write it with these.\nTERRAIN: heightfield \u2192 heightfield_noise \u2192 heightfield_erode \u2192 masks / heightfield_path \u2192 heightfield_scatter + copy_to_points, heightfield_to_mesh; export png16 for an Unreal Landscape, or unreal_landscape for the landscape + layers + instances bundle. See help topic \"heightfield\".\nPHYSICS: rbd_settle drops pieces (packed instances) onto a terrain/container/ground until they rest, so scattered rocks and props sit in contact; rbd_stack drops them one at a time into piles. See help topic \"rbd\".\nLIBRARIES: the person's projects live in libraries the TopoTopo Gallery website shows (their board links to them). library {action:\"list\"} finds one, {action:\"open\"} makes it the workspace of every tool, {action:\"create\"} starts one. See help topic \"library\".";
3
3
  /**
4
4
  * The complete example of help topic "inputs": guides.glb's path.* curves cut roads into a heightfield and its zone.*
5
5
  * areas mask a tree scatter; the vars a person tunes are exposed as params. test/mcp.ts cooks it on a real guides.glb.
package/dist/mcp/docs.js CHANGED
@@ -23,7 +23,8 @@ TIME: build/edit/render/inspect/export take "frame" (default 1). solver = per-fr
23
23
  PARTICLES: particles(emitter points, collision mesh, field) = Houdini POPs in one node: emission, gravity/drag/wind, curl noise, fields, floor and mesh collisions, trails as polylines; steps with the frame. See help topic "particles".
24
24
  ESCAPE HATCHES: wrangle (per-element JS with @P/@Cd syntax), script (whole-geometry JS with the engine library), sdf_expr (signed distance functions). If a node is missing, write it with these.
25
25
  TERRAIN: heightfield → heightfield_noise → heightfield_erode → masks / heightfield_path → heightfield_scatter + copy_to_points, heightfield_to_mesh; export png16 for an Unreal Landscape, or unreal_landscape for the landscape + layers + instances bundle. See help topic "heightfield".
26
- PHYSICS: rbd_settle drops pieces (packed instances) onto a terrain/container/ground until they rest, so scattered rocks and props sit in contact; rbd_stack drops them one at a time into piles. See help topic "rbd".`;
26
+ PHYSICS: rbd_settle drops pieces (packed instances) onto a terrain/container/ground until they rest, so scattered rocks and props sit in contact; rbd_stack drops them one at a time into piles. See help topic "rbd".
27
+ LIBRARIES: the person's projects live in libraries the TopoTopo Gallery website shows (their board links to them). library {action:"list"} finds one, {action:"open"} makes it the workspace of every tool, {action:"create"} starts one. See help topic "library".`;
27
28
  /**
28
29
  * The complete example of help topic "inputs": guides.glb's path.* curves cut roads into a heightfield and its zone.*
29
30
  * areas mask a tree scatter; the vars a person tunes are exposed as params. test/mcp.ts cooks it on a real guides.glb.
@@ -61,6 +62,28 @@ export function graphLines(g) {
61
62
  return `{${parts.join(',\n ')}}`;
62
63
  }
63
64
  export const TOPICS = {
65
+ library: `LIBRARIES AND THE GALLERY
66
+ A library is a folder the person listed (\`topotopo library add <name> <folder>\`, kept in ~/.topotopo/config.json). A
67
+ project is any folder in it holding project.json, and is a workspace of its own:
68
+ props/lantern/project.json {id, title, description, tags, graph:"main", bake:{graph?, node?, frame?}, links:[{label, url}]}
69
+ props/lantern/graphs/ assets/ inputs/ exports/ as in any workspace
70
+ props/lantern/attachments/ concept art, references, source files (shown on the project's gallery page)
71
+ props/lantern/.gallery/ thumb.png, preview.glb, bake.json: derived, never edit
72
+ The parent folders ("props") are the project's collection. The gallery (\`topotopo gallery\`, http://127.0.0.1:7340)
73
+ shows every library as a grid; each project has a page (/p/<library>/<id>), a thumbnail (…/thumb.png) and an
74
+ iframe embed (/embed/<library>/<id>) that the person's board pastes. It bakes the previews by itself after graphs,
75
+ assets or inputs change, from the graph named in "graph" (or "bake": another graph, a node, a frame).
76
+
77
+ WORKING IN A PROJECT
78
+ - library {action:"list", query?, tag?} → find it; library {action:"get", library, id, thumbnail:true} → what it holds.
79
+ - library {action:"open", library, id} → every tool (build, edit, render, export, inputs, assets, preview) now works
80
+ in that folder. Build the project's model into graph "main" (or the manifest's "graph").
81
+ - library {action:"create", library, path:"props/barrel", title, tags, links} → a new project, opened.
82
+ - library {action:"update", tags, links, description, bake:{frame: 48}} → edit project.json (bake.frame for
83
+ simulations that settle after frame 1; bake.node to show one part).
84
+ - library {action:"bake"} → render the previews now and see the thumbnail.
85
+ Put reference images the person gives you in attachments/, guide files in inputs/. Links in "links" point back to the
86
+ board or concept pages, so the gallery page and the board link both ways.`,
64
87
  graph: `GRAPH FORMAT
65
88
  {
66
89
  "nodes": {
@@ -445,6 +468,17 @@ MATERIALS: texture_to_material {material, base_color, normal, roughness, metalli
445
468
  with uv) + input 1 (merged images): writes "image:<name>" slots into the material table, assigns the material (all
446
469
  prims when new, else group) and carries the images. occlusion/metallic images are packed into "<material>_orm".
447
470
  The material node's *_map paths accept "image:<name>" as well.
471
+ CUTOUTS: tex_crop extracts a top-left pixel rectangle (all layers), optionally resizes. trace_image reads alpha
472
+ or a selected channel into closed XY curves, including holes; fill builds faces. Restore UVs after fill using
473
+ uv_project {method:"planar",axis:"z",scale:[width,width*imageHeight/imageWidth]} BEFORE deforming.
474
+ tex_pack items:[{name:"leaf",maps:{color:"leaf_color",normal:"leaf_normal"}}] creates aligned atlas images and
475
+ placement points: name, rect [x,y,w,h], uv_offset, uv_scale. In a vertex wrangle, read these from input 1:
476
+ atlasUV = localUV * uv_scale + uv_offset. Output points follow items order. No rotation or automatic downscale.
477
+ tex_dilate pads nearest valid pixels; alpha stays unchanged by default. For grey/data maps supply an explicit
478
+ validity mask (same size). Pack padding reserves empty gutters; dilate supplies the edge values.
479
+ material {alpha_mode:"mask",alpha_cutoff:0.5,double_sided:true} BEFORE texture_to_material enables cutouts.
480
+ Omitted/auto alpha mode retains legacy behaviour; explicit opaque/mask/blend overrides scalar/vertex auto mode.
481
+ Complete example: examples/image_cutouts.json; workflow and layout contract: docs/image-cutouts.md.
448
482
  SEE IT: render of a geometry holding only images shows the "texture" view; render {texture:"<image>"|"image/layer"|
449
483
  "<material>"} adds the view (a material shows its maps as a labelled strip); render {textures:true} samples base
450
484
  colour maps on the mesh (texture × Cd, like glTF). inspect lists every image with size and per-layer ranges.
@@ -681,6 +715,11 @@ SEE IT: render views "uv" (or "quad_uv" = persp + uv): the 0..1 square with a 0.
681
715
  by chart/island colour, island borders yellow, overlapping uv in RED (footer/notes give the overlap %).
682
716
  render checker:true shades 3D views with an 8×8 uv checker: squares should look square and equal-sized
683
717
  (stretch = rectangles, density = cell size, mirrored charts flip the red/green gradient).
718
+ MEASURE IT: inspect {detail:"uv", resolution:1024, json:true}: exact overlaps (triangle pairs, their prims and areas,
719
+ folds inside one chart included; shared edges are not overlaps), collapsed / non-finite / out-of-tile triangles, UDIM
720
+ tiles, charts, mirrored triangles, utilization (exact for a clean atlas in 0..1, else a labelled raster ESTIMATE) and
721
+ per-piece (prim "name") surface, uv area and texel density. An analysis that hits its bounds says INCOMPLETE.
722
+ CLI: --inspect uv --uv-resolution 1024 [--json].
684
723
  Export: uv → glTF TEXCOORD_0 (v flipped), OBJ vt, USD primvars:st.`,
685
724
  render: `RENDER (pick the overlay that answers your question; everything is off by default)
686
725
  render {node?, views, …} returns a PNG; build/edit take the same options as render:{…}. The footer names the active
@@ -709,11 +748,18 @@ QUESTION → OPTION
709
748
  What do the colours mean? color_by + legend:true (gradient bar with min/max, or categorical swatches)
710
749
  What shape is it? shading:"matcap" (clay, reads form) · "ao" (ambient occlusion: creases and
711
750
  cavities darken; ao_radius px) · "flat" (facets, ignores N)
751
+ How do the materials read? Roughness, metal, maps? shading:"pbr": the metallic-roughness material glTF export writes
752
+ (base colour map × vertex colour, tangent-space normal map in the exported MikkTSpace frame, orm or
753
+ roughness map, metallic, emissive, unlit) under a fixed camera-relative studio rig (key, fill, rim and a
754
+ sky/ground environment), GGX specular, ACES, exposure (stops, default 0). Deterministic: the same graph
755
+ gives the same PNG. Texture files are read from disk; transparency is not evaluated (shaded opaque,
756
+ with a note), nor are missing or non-PNG maps (named in the notes).
712
757
  Labels never overlap: ones without room are skipped (note says how many; raise size or lower max_labels).
713
758
  view_labels:false drops each view's name label and the persp axis gizmo (clean thumbnails, e.g. the shelf's).
714
759
  Examples: render {views:["persp","section"], section_axis:"z", wireframe:"hard", label_groups:true}
715
760
  render {views:"turntable", shading:"matcap"} · render {glyphs:"N", clip:{axis:"x", offset:0.5}}
716
761
  CLI: --wireframe all --section y:0.5 --clip x:0.5 --glyphs N --labels groups,pieces --shading matcap --legend --size 1600 --scale 2
762
+ --shading pbr --exposure 0.5
717
763
  --no-view-labels`,
718
764
  export: `EXPORT
719
765
  export {output:"crate"} / export {} (the default output) / export {all:true}: the graph's export targets (help topic
@@ -728,13 +774,21 @@ export {path:"exports/thing.glb"} — format from the extension:
728
774
  Options: up_axis "y" (default) | "z", scale (100 = m → cm), split_by_name (one mesh per prim "name", default true),
729
775
  custom_attribs, materials (default true), compress "none" | "meshopt" (EXT_meshopt_compression + KHR_mesh_quantization,
730
776
  ~3× smaller; for web engines such as three.js/Babylon.js) | "draco" (only with the optional draco3dgltf package),
731
- quantize (KHR_mesh_quantization alone), attributes ["P","pscale",…] (csv / points.json), pcg / pcg_struct (csv),
777
+ quantize (KHR_mesh_quantization alone), tangents "auto" | "preserve" | "none" (glTF TANGENT, below), attributes ["P","pscale",…] (csv / points.json), pcg / pcg_struct (csv),
732
778
  precision 64 | 32 (geo), instancing "packed" | "expand", instances "rows" | "expand" (csv / points.json of packed
733
779
  prims), meshes (instance rows: also write one GLB per source, default true). For Unreal and Blender keep the default
734
780
  uncompressed GLB.
735
781
  glTF layout: one node+mesh per "name", one primitive per material. Polygons → TRIANGLES, polylines → one LINE_STRIP each
736
- (LINES above 256 curves), loose points → POINTS with pscale as _PSCALE. N → NORMAL (else computed, 60° cusp),
737
- uv/uv2 → TEXCOORD_0/1 (V flipped), Cd (+Alpha) → COLOR_0. Custom attributes: every other numeric point/vertex attribute
782
+ (LINES above 256 curves), loose points → POINTS with pscale as _PSCALE. Scene empties (scene_null: isolated points with
783
+ scene_empty 1, name, parent, orient, scale) → meshless nodes (sockets) under their parent: the scene, another empty or
784
+ a uniquely named mesh, with the local TRS that keeps their geometry-space placement; set point attributes → node extras;
785
+ missing, ambiguous or cyclic parents and GPU-instanced parents are errors; import brings them back. N → NORMAL (else computed, 60° cusp),
786
+ uv/uv2 → TEXCOORD_0/1 (V flipped), Cd (+Alpha) → COLOR_0. TANGENT (tangents "auto", the default): MikkTSpace
787
+ tangents (xyz + handedness w) for every primitive whose material has a normal map, computed per corner before
788
+ vertices are welded (uv seams, hard normals and mirrored islands keep their own frames), the same frame bake_normal
789
+ bakes in; a valid point/vertex "tangent" float[4] (from an import) is written on other primitives. "preserve" writes
790
+ the supplied attribute wherever it exists (malformed = error), "none" never writes TANGENT. Collapsed uvs are
791
+ reported. Import reads TANGENT back as point "tangent" (transforms keep it: xyz rotated, w flipped by mirrors). Custom attributes: every other numeric point/vertex attribute
738
792
  of size 1-4 → _NAME (upper-cased, float or the smallest int type); mesh extras keep the original names and types.
739
793
  MATERIALS: the material node writes prim "material" + the detail table. Vertex colours win: prims whose Cd is not all
740
794
  white export baseColor white × COLOR_0 with the material's metallic/roughness/emissive; otherwise baseColor = the
@@ -0,0 +1,12 @@
1
+ import type { Workspace } from '../workspace.ts';
2
+ import type { ToolDef } from './tools.ts';
3
+ export interface LibraryToolHost {
4
+ /** the workspace the other tools use now */
5
+ workspace(): Workspace;
6
+ /** make a folder the workspace of every tool (and of the live viewer) */
7
+ open(dir: string): Promise<{
8
+ graphs: number;
9
+ assets: number;
10
+ }>;
11
+ }
12
+ export declare function libraryTool(host: LibraryToolHost): ToolDef;