topotopo 0.5.1 → 0.5.3

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 (41) hide show
  1. package/dist/cli.js +42 -18
  2. package/dist/core/manifold.d.ts +11 -2
  3. package/dist/core/manifold.js +7 -4
  4. package/dist/core/materials.d.ts +3 -2
  5. package/dist/core/materials.js +3 -2
  6. package/dist/core/tangents.d.ts +11 -1
  7. package/dist/core/tangents.js +87 -14
  8. package/dist/core/texture.d.ts +1 -1
  9. package/dist/core/texture.js +12 -3
  10. package/dist/core/topology.d.ts +5 -1
  11. package/dist/core/topology.js +35 -4
  12. package/dist/graph/engine.d.ts +7 -0
  13. package/dist/graph/engine.js +54 -6
  14. package/dist/io/gltf.js +8 -7
  15. package/dist/io/source.d.ts +2 -0
  16. package/dist/io/source.js +10 -1
  17. package/dist/mcp/docs.js +35 -8
  18. package/dist/mcp/tools.js +35 -10
  19. package/dist/nodes/attributes.js +12 -3
  20. package/dist/nodes/bake.js +2 -2
  21. package/dist/nodes/curves.js +7 -7
  22. package/dist/nodes/material.js +3 -3
  23. package/dist/nodes/solid.js +42 -15
  24. package/dist/nodes/texture.js +16 -9
  25. package/dist/nodes/topology.js +3 -2
  26. package/dist/packages/registry.d.ts +21 -8
  27. package/dist/packages/registry.js +57 -24
  28. package/dist/render/options.js +9 -1
  29. package/dist/render/pbr.d.ts +22 -2
  30. package/dist/render/pbr.js +113 -38
  31. package/dist/render/preview.d.ts +2 -0
  32. package/dist/render/raster.d.ts +13 -1
  33. package/dist/render/raster.js +112 -19
  34. package/dist/session.d.ts +25 -6
  35. package/dist/session.js +98 -43
  36. package/dist/viewer/app/api.js +5 -2
  37. package/dist/viewer/app/cooking.js +9 -3
  38. package/dist/viewer/app/main.js +18 -4
  39. package/dist/viewer/server.js +20 -3
  40. package/integrations/godot/addons/topotopo/plugin.cfg +1 -1
  41. package/package.json +3 -3
package/dist/io/gltf.js CHANGED
@@ -55,7 +55,8 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
55
55
  // embedded (PNG / JPEG) as baseColorTexture, normalTexture and metallicRoughnessTexture (roughness = green channel);
56
56
  // a map replaces its factor (baseColorFactor white, roughnessFactor 1). Without readFile the maps are skipped.
57
57
  // "image:<name>" paths are image volumes of the geometry (texture nodes), encoded to PNG in memory; an "orm" map is
58
- // both the metallicRoughness and the occlusion texture (metallicFactor 1).
58
+ // both the metallicRoughness and the occlusion texture; the material's metallic / roughness are then the factors that multiply it
59
+ // (texture_to_material sets them to 1, or to the values it was given).
59
60
  // options.source (how the export was made, io/source.ts) → asset.extras.source.
60
61
  //
61
62
  // Import
@@ -334,14 +335,14 @@ function getMaterial(st, name, vertexColors, blend, tint) {
334
335
  const roughTex = ormTex ?? tex('roughness');
335
336
  if (ormTex && mat.textures?.roughness)
336
337
  st.warn?.(`glTF: material "${name}" has an orm and a roughness map; the orm map's green channel is used`);
337
- // a map replaces its factor: white base colour under a base colour map, roughness 1 under a roughness map,
338
- // metallic 1 under an ORM map
338
+ // a map replaces its factor: white base colour under a base colour map, roughness 1 under a roughness map; an ORM
339
+ // map's factors are the material's own metallic / roughness (1 unless set)
339
340
  // a folded constant vertex colour multiplies a base colour map exactly as COLOR_0 would have
340
341
  const rgb = tint ?? (vertexColors || baseTex ? [1, 1, 1] : mat.baseColor);
341
342
  m = st.doc.createMaterial(isDefault ? 'default' : name)
342
343
  .setBaseColorFactor([toLinear(rgb[0]), toLinear(rgb[1]), toLinear(rgb[2]), mat.alpha]) // glTF factors are linear
343
- .setMetallicFactor(ormTex ? 1 : mat.metallic)
344
- .setRoughnessFactor(roughTex ? 1 : mat.roughness)
344
+ .setMetallicFactor(mat.metallic)
345
+ .setRoughnessFactor(roughTex && !ormTex ? 1 : mat.roughness)
345
346
  .setDoubleSided(mat.doubleSided);
346
347
  if (baseTex)
347
348
  m.setBaseColorTexture(baseTex);
@@ -359,7 +360,7 @@ function getMaterial(st, name, vertexColors, blend, tint) {
359
360
  }
360
361
  else
361
362
  m.setEmissiveFactor([toLinear(mat.emissive[0]), toLinear(mat.emissive[1]), toLinear(mat.emissive[2])]);
362
- m.setAlphaMode(materialAlphaMode(mat, blend));
363
+ m.setAlphaMode(materialAlphaMode(mat));
363
364
  if (mat.alphaMode === 'MASK')
364
365
  m.setAlphaCutoff(mat.alphaCutoff ?? 0.5);
365
366
  if (mat.unlit)
@@ -574,7 +575,7 @@ export function gltfDocument(g, o = {}) {
574
575
  if (diag.uvNonFinite || diag.uvDegenerate) {
575
576
  // where the first one is: its prim's part and position (core/report.ts)
576
577
  const first = diag.firstBad >= 0 ? `, first ${primWhere(geo, geo.vertexPrims()[tris[diag.firstBad * 3]])}` : '';
577
- o.warn?.(`glTF: ${where}: ${diag.uvDegenerate} of ${diag.triangles} triangles have collapsed uvs${diag.uvNonFinite ? ` and ${diag.uvNonFinite} non-finite uvs` : ''}${first}; their ${diag.fallbackCorners} corners get a fallback tangent (the normal map has no orientation there): unwrap them (uv_unwrap) or give them uv area`);
578
+ o.warn?.(`glTF: ${where}: ${diag.uvDegenerate} of ${diag.triangles} triangles have collapsed uvs${diag.uvNonFinite ? ` and ${diag.uvNonFinite} non-finite uvs` : ''}${first}; their ${diag.fallbackCorners} corners get a fallback tangent (the normal map has no orientation there): unwrap them (uv_unwrap) or give them uv area${diag.uvThin ? `; ${diag.uvThin} thin triangles skipped` : ''}`);
578
579
  }
579
580
  else if (diag.fallbackCorners)
580
581
  o.warn?.(`glTF: ${where}: MikkTSpace left ${diag.fallbackCorners} corners without a tangent; a fallback was written`);
@@ -10,6 +10,8 @@ export interface ExportSource {
10
10
  seeds: Record<string, unknown>;
11
11
  /** the package versions the graph uses (absent when it uses none) */
12
12
  packages?: Record<string, string>;
13
+ /** the packages exported from their working folders, no published version (absent when none) */
14
+ followed?: string[];
13
15
  export: {
14
16
  format: string;
15
17
  options: Record<string, unknown>;
package/dist/io/source.js CHANGED
@@ -10,7 +10,12 @@
10
10
  // seeds the seed params the graph sets, by node ("loop/pts" inside a nested graph), as written
11
11
  // packages only when the graph uses packages (src/graph/packages.ts packagesUsed): "owner/name@version" → the
12
12
  // version's hash for every package version it uses, directly or through other packages (an export
13
- // made while following a working folder cooks with the published copies, so it names those)
13
+ // made while following a working folder cooks with the published copies, so it names those), and
14
+ // "owner/name@working" → the hash of a working folder an export was told to follow (CLI --follow,
15
+ // MCP export follow)
16
+ // followed only when it used working folders ("owner/name@working" under packages): those packages, sorted.
17
+ // They are no published version: the export is made again only from those folders as they were
18
+ // (their hash says whether they still are), replay passes --follow for each
14
19
  // export {format, options}: the export options given (the export tool's names)
15
20
  // package only on a package's outputs cooked for an engine (topotopo cook --for godot, src/host/cook.ts): the
16
21
  // package's publish name, else its id; the cook replaces a file at an output path only when it names
@@ -63,6 +68,8 @@ export function graphSeeds(spec) {
63
68
  walk(spec, '', 0);
64
69
  return sorted(out);
65
70
  }
71
+ /** The packages a packagesUsed record names by working folder ("owner/name@working"), sorted. */
72
+ const followedIn = (packages) => Object.keys(packages ?? {}).filter((k) => k.endsWith('@working')).map((k) => k.slice(0, -'@working'.length)).sort();
66
73
  /** The source block of an export. */
67
74
  export function exportSource(i) {
68
75
  const spec = i.spec;
@@ -76,6 +83,7 @@ export function exportSource(i) {
76
83
  vars: sorted(spec.vars ?? {}),
77
84
  seeds: graphSeeds(spec),
78
85
  ...(i.packages && Object.keys(i.packages).length ? { packages: sorted(i.packages) } : {}),
86
+ ...(followedIn(i.packages).length ? { followed: followedIn(i.packages) } : {}),
79
87
  export: { format: i.format, options: sorted(i.options ?? {}) },
80
88
  ...(i.package ? { package: i.package } : {}),
81
89
  topotopo: i.version,
@@ -94,6 +102,7 @@ export function replayArgs(s, exportPath, flags) {
94
102
  return [
95
103
  ...(s.output ? ['--output', s.output] : ['--node', s.node]),
96
104
  '--frame', String(s.frame), '--fps', String(s.fps),
105
+ ...(s.followed ?? []).flatMap((p) => ['--follow', p]),
97
106
  ...Object.entries(s.vars).flatMap(([k, v]) => ['--var', `${k}=${JSON.stringify(v)}`]),
98
107
  '--format', s.export.format, ...flags(s.export.options), '--export', exportPath,
99
108
  ];
package/dist/mcp/docs.js CHANGED
@@ -136,8 +136,8 @@ says what the open package's workspace holds: its packages as the scan finds the
136
136
  all. A package that publishes versions keeps its own uses and copies (they are published with it). workspace init
137
137
  moves the copies of the packages inside that kept their own.
138
138
  - FOLLOWING: "follow": true shows the workspace's own packages live from their working folders, for looking (the
139
- viewer, renders, inspect); exports and publishing always use the published versions, and an export made while
140
- following says which it used.
139
+ viewer, renders, inspect); exports and publishing use the published versions (but an export told to follow one,
140
+ help topic "packages", FOLLOWING), and an export made while following says which it used.
141
141
  - THE ENGINE: "engine" names the engine project ({"type", "project"}, the path written from the workspace and leading
142
142
  upward when the workspace is inside it) or "none" (kept). workspace init finds it: the nearest at or above the
143
143
  folder, else one below. It says when Unreal will not see the workspace (outside the project's Content/ or a plugin's),
@@ -736,7 +736,7 @@ CUTOUTS: tex_crop extracts a top-left pixel rectangle (all layers), optionally r
736
736
  tex_dilate pads nearest valid pixels; alpha stays unchanged by default. For grey/data maps supply an explicit
737
737
  validity mask (same size). Pack padding reserves empty gutters; dilate supplies the edge values.
738
738
  material {alpha_mode:"mask",alpha_cutoff:0.5,double_sided:true} BEFORE texture_to_material enables cutouts.
739
- Omitted/auto alpha mode retains legacy behaviour; explicit opaque/mask/blend overrides scalar/vertex auto mode.
739
+ Omitted/auto alpha mode blends only for scalar alpha < 1; vertex Alpha (COLOR_0.A) is data and never changes it.
740
740
  Complete example: examples/image_cutouts.json; workflow and layout contract: docs/image-cutouts.md.
741
741
  SEE IT: render of a geometry holding only images shows the "texture" view; render {texture:"<image>"|"image/layer"|
742
742
  "<material>"} adds the view (a material shows its maps as a labelled strip); render {textures:true} samples base
@@ -925,6 +925,10 @@ Nodes:
925
925
  profile placed by sections [{offset, scale, rotate}, ...]; sections with the same point count join point to point
926
926
  (insets keep their corners), closed sections are turned to the first one's winding; closed results face outward.
927
927
  revolve {axis, origin, angle} lathe about any axis line; draw the profile in a plane that holds the axis.
928
+ angle [a0, a1] turns right-handed about the axis (plan angle of the result = -a); caps only for closed profiles and
929
+ then always outward; an open profile gives an open surface, flip reverses it. extrude plane: xz along +Y, xy along +Z,
930
+ yz along +X. sweep end caps are perpendicular to the path (a tilted last segment tilts the cap). grid_split splits
931
+ quads only: cut first (boolean leaves n-gons), then split.
928
932
  shape2d capsule | slot a stadium (rect with half-circle ends) in size; extrude for a slot cutter.
929
933
  project_curve (curves, surface | heightfield) {mode direction|closest, direction, spacing, lift, misses} drapes a
930
934
  curve onto terrain; spacing resamples first so it follows the bumps; writes point hit and N (smooth normals).
@@ -1119,6 +1123,13 @@ on:false or the end of the session; nothing about it is saved. Every edit there
1119
1123
  (the viewer, renders, inspect): exports and publishing use the published copy, and an export made while following
1120
1124
  says which published version it used. A workspace with "follow": true (topotopo workspace init --follow) follows its
1121
1125
  own packages this way, those whose working folder is inside it. Other packages' versions keep the copies they hold.
1126
+ EXPORTING FROM A WORKING FOLDER: an export told to follow a package uses its working folder too: the CLI's --follow
1127
+ studio/trees on a graph-file cook (its --export and --export-all), MCP export {follow:["studio/trees"]} for a package
1128
+ this session follows. It is for a package with no published version yet (an unpublished sibling in the workspace) or
1129
+ for edits not published yet. Such an export is no published version: its source record lists the package under "followed" (and
1130
+ the folder's hash under packages, "studio/trees@working"), and the export says so. An export not told to follow a
1131
+ followed package with no published version in use is refused, saying to publish it or to pass --follow / follow.
1132
+ --locked (a build machine) exports published versions alone: a followed package it does not use fails the run.
1122
1133
 
1123
1134
  OUT OF DATE AND UPDATE: what a package uses changes only by an update, after a before/after.
1124
1135
  - workspace {action:"outdated"} (CLI: topotopo outdated) lists the packages in use that have newer versions:
@@ -1209,6 +1220,8 @@ Which node:
1209
1220
  tiling textures, boxes. box: each polygon along the axis its normal is closest to (X faces u = z, v = y;
1210
1221
  Y faces u = x, v = z; Z faces u = x, v = y); both sides of an axis share it, so faces looking along +X,
1211
1222
  +Y and -Z are MIRRORED (text reads backwards; inspect uv counts them) and -X, -Y, +Z read right.
1223
+ cylindrical scale[0] = tile count around the axis; its top and bottom annuli collapse, so give them a prim
1224
+ group and project them again with method box / planar and group.
1212
1225
  uv_unwrap automatic (xatlas): cuts charts by angle/cost, flattens and packs into 0..1. Default for props and
1213
1226
  hard-surface. Keeps polygons; writes prim chart. Each connected piece is charted on its own; polygons
1214
1227
  xatlas cuts across charts become triangles (exact uv); faces with no area collapse onto a neighbour's
@@ -1307,12 +1320,22 @@ QUESTION → OPTION
1307
1320
  What shape is it? shading:"matcap" (clay, reads form) · "ao" (ambient occlusion: creases and
1308
1321
  cavities darken; ao_radius px) · "flat" (facets, ignores N)
1309
1322
  How do the materials read? Roughness, metal, maps? shading:"pbr": the metallic-roughness material glTF export writes
1310
- (base colour map × vertex colour, tangent-space normal map in the exported MikkTSpace frame, orm or
1323
+ (base colour factor or map, tangent-space normal map in the exported MikkTSpace frame, orm or
1311
1324
  roughness map, metallic, emissive, unlit) under a fixed camera-relative studio rig (key, fill, rim and a
1312
1325
  sky/ground environment), GGX specular, ACES, exposure (stops, default 0). Deterministic: the same graph
1313
- gives the same PNG. Texture files are read from disk; transparency is not evaluated (shaded opaque,
1314
- with a note), nor are missing or non-PNG maps (named in the notes). color_by and highlight tint
1326
+ gives the same PNG. Texture files are read from disk; missing or non-PNG maps are not evaluated
1327
+ (named in the notes). Transparency follows the exported alpha mode: alpha_mode "mask" cuts out
1328
+ pixels below alpha_cutoff (alpha × base colour map alpha), "blend" (or alpha below 1 under "auto")
1329
+ is composited over what is behind, prim by prim from back to front; the inspection shadings
1330
+ (default, flat, matcap, ao) keep drawing blend materials as surfaces. color_by and highlight tint
1315
1331
  the shaded material (the attribute colour lit by the material's brightness); checker is not shown.
1332
+ Vertex colour, as in glTF export: a named material wins (its base colour factor or map; the prims'
1333
+ Cd is not shown, a note says so), Cd colours prims without a material. cd:"multiply" also tints a
1334
+ named material with Cd (vertex paint), cd:"ignore" never shows Cd; cd:"auto" is the default.
1335
+ Are the values right (light and dark, without colour)? grey:true: shading "pbr" with every base colour a neutral
1336
+ 18% grey lit by the studio rig at its luminance (base colour maps and Cd give no colour); roughness,
1337
+ metallic, normal and orm maps, alpha
1338
+ and emissive still apply.
1316
1339
  POLYGON EDGES: wireframe "auto" (the default) draws polygon edges on meshes under 6,000 polygons, never under shading
1317
1340
  "pbr" or textures:true (they would read as marks in the material); the footer says EDGES AUTO when it draws them.
1318
1341
  wireframe:false hides them, true draws them always.
@@ -1361,6 +1384,10 @@ SOURCE: every export (export tool, export targets and the viewer's Export and Do
1361
1384
  --export-all) records how it was made, so it can be made again: a "source" block {graph, graph_sha256 (SHA-256 of the graph JSON as
1362
1385
  cooked: vars after overrides, keys sorted, no whitespace), output (a named output, else null), node, frame, fps, vars
1363
1386
  (all of them, after overrides), seeds (the seed params the graph sets, by node: "loop/pts" inside a body, as written),
1387
+ packages (only when the graph uses packages: "owner/name@version" → the version's hash, every version it uses, and
1388
+ "owner/name@working" → the hash of a working folder the export followed), followed (only when it followed one: those
1389
+ packages, no published version; the export is made again only from those folders as they were, and replay passes
1390
+ --follow for each; help topic "packages", EXPORTING FROM A WORKING FOLDER),
1364
1391
  export: {format, options: every option the format reads, the given ones and the defaults of the rest}, topotopo (the
1365
1392
  version)}. png16 / r16 carry it in their .json sidecar, csv / points.json
1366
1393
  instance rows in <name>.meshes.json, unreal_landscape in landscape.json; every other export writes <file>.source.json
@@ -1368,7 +1395,7 @@ SOURCE: every export (export tool, export targets and the viewer's Export and Do
1368
1395
  it), and glb / gltf also carry it in asset.extras.source. Nothing in it depends on the time or the machine: the same
1369
1396
  graph, values and options give the same bytes, and a later version changing a default does not change what the
1370
1397
  record replays. Replay on the command line: topotopo <graph>.json --output <output> (or --node <node>) --frame <frame>
1371
- --fps <fps>, one --var <name>=<value as JSON> per var, --format <format>, every option as its flag (up_axis "z" →
1398
+ --fps <fps>, one --follow <package> per followed package, one --var <name>=<value as JSON> per var, --format <format>, every option as its flag (up_axis "z" →
1372
1399
  --up-axis z, custom_attribs false → --no-custom-attribs, layers ["a","b"] → --layers a,b) and --export <path>. e.g.
1373
1400
  topotopo graphs/crate.json --node h --frame 1 --fps 24 --format glb --compress none --custom-attribs
1374
1401
  --instancing packed --materials --no-quantize --scale 100 --split-by-name --tangents auto --up-axis z --export crate.glb
@@ -1394,7 +1421,7 @@ MATERIALS: the material node writes prim "material" + the detail table. A named
1394
1421
  material as it is and their Cd / Alpha are dropped (Cd left from colouring parts does not become COLOR_0 or a second,
1395
1422
  white or tinted copy of the material). Prims without a material, and every prim with vertex_colors:true, keep their
1396
1423
  Cd: not all white → baseColor white × COLOR_0 with the material's metallic/roughness/emissive (one constant Cd is
1397
- folded into the factor). alpha < 1 → alphaMode BLEND; unlit → KHR_materials_unlit; emissive above 1 → KHR_materials_emissive_strength.
1424
+ folded into the factor). a material's own alpha < 1 (or alpha_mode blend) → alphaMode BLEND; vertex Alpha is data: it stays COLOR_0.A and never changes the mode; unlit → KHR_materials_unlit; emissive above 1 → KHR_materials_emissive_strength.
1398
1425
  TEXTURES: material {base_color_map, normal_map, roughness_map} (PNG/JPEG paths relative to the package folder; the mesh
1399
1426
  needs uv). glb/gltf embed the images (baseColorTexture, normalTexture, metallicRoughnessTexture = roughness in green; a
1400
1427
  map replaces its factor). usda: UsdUVTexture shaders reading primvars:st, asset paths relative to the .usda. geo/json
package/dist/mcp/tools.js CHANGED
@@ -19,6 +19,7 @@ import { packageAt, packagesUsed } from '../graph/packages.js';
19
19
  import { ArtifactStore } from '../host/artifacts.js';
20
20
  import { prepareTarget, serializeExport, writeExportFiles, writeTargets } from '../host/export-targets.js';
21
21
  import { TOPOTOPO_VERSION } from '../host/version.js';
22
+ import { program } from '../package.js';
22
23
  import { evalGroup } from '../core/groups.js';
23
24
  import { Geometry } from '../core/geometry.js';
24
25
  import { verifyTools } from './verify.js';
@@ -153,6 +154,8 @@ const RENDER_PROPS = {
153
154
  legend: { type: 'boolean', description: 'legend for color_by (gradient bar with min/max, or categorical swatches) and highlight' },
154
155
  shading: { type: 'string', enum: ['default', 'flat', 'matcap', 'ao', 'pbr'], description: 'flat: facets (ignores N); matcap: clay that reads form; ao: screen-space ambient occlusion darkens creases and cavities; pbr: the exported metallic-roughness material (base colour, normal, orm/roughness maps, emissive, unlit) under a fixed studio light rig, deterministic' },
155
156
  exposure: { type: 'number', description: 'shading "pbr": exposure in stops (default 0)' },
157
+ grey: { type: 'boolean', description: 'value check: shading "pbr" (implied) with every base colour a neutral 18% grey under the studio rig at its luminance (no hue anywhere); base colour maps and Cd give no colour, roughness/metallic/normal/orm maps, alpha and emissive still apply' },
158
+ cd: { type: 'string', enum: ['auto', 'ignore', 'multiply'], description: 'shading "pbr": vertex colour Cd. auto (default, as glTF export): a named material\'s base colour (factor or map) wins and Cd colours only prims without a material; ignore: Cd never shown; multiply: Cd also tints a named material\'s base colour (vertex paint)' },
156
159
  ao_radius: { type: 'number', description: 'shading "ao": sample radius in pixels (default 10)' },
157
160
  look_at: { type: 'array', items: { type: 'number' }, description: 'look-at point [x, y, z] in world metres (x right, y up, z towards the front; default the bbox centre): the view centres on it and still fits the bounds; with zoom > 1 it zooms into that point' },
158
161
  bounds: { type: 'array', items: { type: 'array', items: { type: 'number' } }, description: 'world-space [[x0, y0, z0], [x1, y1, z1]] (min then max, metres, Y up): every 3D view frames these bounds instead of the box of the geometry, so renders of different geometries share one camera (timelapse frames, turntable azimuths)' },
@@ -211,22 +214,43 @@ export function makeTools(ws, opts = {}) {
211
214
  ws.bump(name);
212
215
  return reportResult(name, r, a, extraNotes);
213
216
  };
217
+ /**
218
+ * export {follow}: the packages whose working folders the export uses (each followed this session), checked; an
219
+ * export that would cook a followed package with no published version in use from published copies is refused.
220
+ */
221
+ const exportFollow = (a, spec) => {
222
+ const follow = a.follow === undefined ? [] : (Array.isArray(a.follow) ? a.follow : [a.follow]).map(String);
223
+ const followed = new Set((ws.packages?.following?.() ?? []).map((f) => f.package));
224
+ for (const p of follow) {
225
+ if (!followed.has(p))
226
+ throw new Error(`follow: this session does not follow ${p}: workspace {action:"follow", package:"${p}", on:true} follows its working folder (renders show it too), then export {follow:["${p}"]} exports from it`);
227
+ }
228
+ const missing = ws.packages?.unpublished?.(spec, follow) ?? [];
229
+ if (missing.length) {
230
+ throw new Error(`export: ${missing.map((u) => u.package).join(', ')} ${missing.length === 1 ? 'has' : 'have'} no published version in use (this session shows ${missing.length === 1 ? 'its working folder' : 'their working folders'}, for looking): `
231
+ + `${missing.map((u) => `publish ${u.package} (${program()} publish ${u.dir} --note "...") or pass follow:["${u.package}"] to export from its working folder`).join('; ')}; nothing was written`);
232
+ }
233
+ return follow;
234
+ };
214
235
  const resolveNodeGeo = async (a, forExport = false) => {
215
236
  const name = a.graph ?? a.name ?? 'main'; // `name` is what build/edit call it; accept both
216
237
  const g = ws.getGraph(name);
217
238
  const target = a.node || undefined;
218
- // an export uses the published copies of the packages the session shows live (following is for looking)
219
- const scope = forExport && ws.packages?.publishedNote?.(g) ? ws.packages.published?.() : null;
239
+ // an export uses the published copies of the packages the session shows live (following is for looking), but
240
+ // the working folders of those export {follow} names
241
+ const follow = forExport ? exportFollow(a, g) : [];
242
+ const scope = forExport && ws.packages?.publishedNote?.(g, follow) ? ws.packages.published?.(follow) : null;
220
243
  const r = await engine.cook(g, { target, frame: a.frame, ...(scope ? { scope } : {}) });
221
244
  if (!r.ok || !r.geo)
222
245
  throw new Error(reportText(name, r));
223
- return { r, name, geo: r.geo, scope };
246
+ return { r, name, geo: r.geo, scope, follow };
224
247
  };
225
- /** What an export of a graph made while following says (the published versions it used), on a line of its own. */
226
- const publishedLine = (spec) => { const n = ws.packages?.publishedNote?.(spec); return n ? `\n${n}` : ''; };
248
+ /** What an export of a graph made while following says (the working folders and published versions it used), on a line of its own. */
249
+ const publishedLine = (spec, follow) => { const n = ws.packages?.publishedNote?.(spec, follow); return n ? `\n${n}` : ''; };
227
250
  /** export without a path: the graph's targets (the default output's, a named one's, or all), inside exports/ */
228
251
  const exportTargets = async (a) => {
229
252
  const name = a.graph ?? a.name ?? 'main', spec = ws.getGraph(name);
253
+ const follow = exportFollow(a, spec);
230
254
  const published = publishedOutputs(name, spec, engine.findOutput(spec).name);
231
255
  const hint = (o) => `edit {ops:[{op:"export"${o === undefined ? '' : `, output:"${o}"`}, export:"glb"}]}`;
232
256
  let chosen = published;
@@ -243,15 +267,15 @@ export function makeTools(ws, opts = {}) {
243
267
  return text(`no output of "${name}" has an export target: set one with ${hint(undefined)}, or pass path`, true);
244
268
  const prepared = [];
245
269
  for (const p of targets) {
246
- const r = await ws.cook(name, p.node, a.frame, { kind: 'export' });
270
+ const r = await ws.cook(name, p.node, a.frame, { kind: 'export', follow });
247
271
  if (!r.ok || !r.geo)
248
272
  return text(reportText(name, r), true);
249
- prepared.push(await prepareTarget(r.geo, name, p, ws.exportDir, engine.host, { frame: r.frame, fps: r.fps, packages: packagesUsed(engine, spec, ws.packages?.published?.() ?? engine.root) }));
273
+ prepared.push(await prepareTarget(r.geo, name, p, ws.exportDir, engine.host, { frame: r.frame, fps: r.fps, packages: packagesUsed(engine, spec, ws.packages?.published?.(follow) ?? engine.root) }));
250
274
  }
251
275
  writeTargets(prepared, ws.exportDir);
252
276
  const skipped = chosen.filter((p) => !p.target).map((p) => p.label);
253
277
  return text(prepared.map((p) => exportReport(p.files, p.root, p.target.format, `${p.label}: ${p.summary}`, p.warnings, p.sourceFile, p.sourceManifest)).join('\n')
254
- + (skipped.length ? `\nno export target (skipped): ${skipped.join(', ')}` : '') + publishedLine(spec));
278
+ + (skipped.length ? `\nno export target (skipped): ${skipped.join(', ')}` : '') + publishedLine(spec, follow));
255
279
  };
256
280
  const tools = [
257
281
  {
@@ -474,13 +498,14 @@ export function makeTools(ws, opts = {}) {
474
498
  instancing: { type: 'string', enum: ['packed', 'expand'], description: 'packed prims: glb/gltf (EXT_mesh_gpu_instancing), usda (PointInstancer) and geo (PackedGeometry) keep instances by default; expand writes real copies' },
475
499
  instances: { type: 'string', enum: ['rows', 'expand'], description: 'csv / points.json of packed prims: rows (default) = one row per instance (full transform, Mesh column, anchor attributes) + <name>.meshes.json + <name>_meshes/<Mesh>.glb; expand = the points of the expanded geometry' },
476
500
  meshes: { type: 'boolean', description: 'instance rows: also write one GLB per packed source (default true)' },
501
+ follow: { type: 'array', items: { type: 'string' }, description: 'packages ("owner/name") this session follows (workspace {action:"follow"}) whose working folders the export uses instead of their published copies: for a package with no published version yet, or edits not yet published. The source record lists them under "followed". Without it an export uses the published copies' },
477
502
  ...FRAME_PROP,
478
503
  },
479
504
  },
480
505
  run: async (a) => {
481
506
  if (a.path === undefined)
482
507
  return exportTargets(a);
483
- const { geo, name, r, scope } = await resolveNodeGeo(a, true);
508
+ const { geo, name, r, scope, follow } = await resolveNodeGeo(a, true);
484
509
  const p = path.resolve(ws.dir, a.path);
485
510
  const fmt0 = String(a.format ?? exportFormatFromPath(p)).toLowerCase();
486
511
  const ext = ({ png: 'png16', raw: 'r16' }[fmt0] ?? fmt0);
@@ -491,7 +516,7 @@ export function makeTools(ws, opts = {}) {
491
516
  format: ext, options: exportToolOptions(a), packages: packagesUsed(engine, ws.getGraph(name), scope ?? engine.root), version: TOPOTOPO_VERSION,
492
517
  });
493
518
  const report = await writeExport(geo, ext, p, a, engine.host, (files) => new ArtifactStore(ws.exportDir).record(files, { graph: name, node: r.target, format: ext }), source);
494
- return text(`${report}\n(from ${name}/${r.target}${atFrame(r)}: ${geo.numPoints} points, ${geo.numPrims} prims)${publishedLine(ws.getGraph(name))}`);
519
+ return text(`${report}\n(from ${name}/${r.target}${atFrame(r)}: ${geo.numPoints} points, ${geo.numPrims} prims)${publishedLine(ws.getGraph(name), follow)}`);
495
520
  },
496
521
  },
497
522
  {
@@ -1391,13 +1391,18 @@ defineNode({
1391
1391
  'its normal is closest to. Both sides of an axis share one projection, so the faces looking along +X, +Y and -Z get MIRRORED uv (a ' +
1392
1392
  'texture reads backwards there, and their uv winding is opposite to the polygon\'s: inspect uv counts them as mirrored), while -X, -Y and ' +
1393
1393
  '+Z read the right way round. cylindrical: u = angle around axis (one turn per scale[0]), v = height along axis / scale[1]; spherical: u ' +
1394
- '= angle, v = polar angle (0..1 times scale[1]); both measured from center, with a seam where the angle wraps.',
1394
+ '= angle, v = polar angle (0..1 times scale[1]); both measured from center, with a seam where the angle wraps. For cylindrical and ' +
1395
+ 'spherical scale[0] is the TILE COUNT around the axis (a number of repeats, not a length: 1 = the texture wraps the surface once, 4 = four ' +
1396
+ 'repeats); scale[1] is metres per v tile for cylindrical. A cylindrical projection collapses the flat top and bottom faces of a tube or ' +
1397
+ 'ring (all their points share one height, so the uv degenerates to a line): put those faces in a prim group and run a second uv_project ' +
1398
+ 'with method box or planar and that group; group limits a projection to its prims and leaves the uv of the others untouched.',
1395
1399
  aliases: ['uvproject', 'texture', 'uv_texture'],
1396
1400
  inputs: [{ name: 'geo', desc: 'geometry' }],
1397
1401
  params: {
1402
+ group: P.group('prim', 'prims to project ("" = all); the other prims keep their uv'),
1398
1403
  method: { type: 'enum', options: ['box', 'planar', 'cylindrical', 'spherical'], default: 'box', desc: 'projection type' },
1399
1404
  axis: { type: 'enum', options: ['y', 'x', 'z'], default: 'y', desc: 'projection axis (planar normal / cylinder axis)' },
1400
- scale: { type: 'vec2', default: [1, 1], desc: 'world units per UV tile (box/planar); tiles around (cyl/sph)' },
1405
+ scale: { type: 'vec2', default: [1, 1], desc: 'box/planar: world units per UV tile; cylindrical/spherical: scale[0] is the number of tiles around the axis (a count, not a length), scale[1] is metres per tile along the axis (cylindrical) or the number of tiles pole to pole (spherical)' },
1401
1406
  offset: { type: 'vec2', default: [0, 0], desc: 'uv offset' },
1402
1407
  center: { type: 'vec3', default: [0, 0, 0], desc: 'projection center (cyl/sph)' },
1403
1408
  },
@@ -1405,12 +1410,16 @@ defineNode({
1405
1410
  example: { type: 'uv_project', params: { method: 'cylindrical', axis: 'y' } },
1406
1411
  cook: ({ input, p }) => {
1407
1412
  const g = input(0).clone();
1408
- g.points.delete('uv');
1413
+ const sel = mask(g, 'prim', p.group);
1414
+ if (!sel)
1415
+ g.points.delete('uv');
1409
1416
  const uv = g.vertices.add('uv', 'float', 3).data;
1410
1417
  const pn = primNormals(g), vprim = g.vertexPrims();
1411
1418
  const Pd = g.P;
1412
1419
  const ax = 'xyz'.indexOf(p.axis);
1413
1420
  for (let v = 0; v < g.numVertices; v++) {
1421
+ if (sel && !sel[vprim[v]])
1422
+ continue;
1414
1423
  const pt = g.vertexPoint[v];
1415
1424
  const x = Pd[pt * 3], y = Pd[pt * 3 + 1], z = Pd[pt * 3 + 2];
1416
1425
  let u = 0, w = 0;
@@ -1,6 +1,6 @@
1
1
  import { Image, MAIN_LAYER } from '../core/image.js';
2
2
  import { averagedVertexNormals, bakeSamples, curvatureEdges, dilate, edgeGrid, idColor, interpolate, interpolateCorners, normalize3, resolve, uvIslands, vertexPositions, vertexValues, } from '../core/bake.js';
3
- import { cornerTangents, loadMikkTSpace, mikkTSpaceReady, shadingFrame } from '../core/tangents.js';
3
+ import { MIKK_RESET_BYTES, cornerTangents, loadMikkTSpace, mikkTSpaceHeapBytes, mikkTSpaceReady, shadingFrame } from '../core/tangents.js';
4
4
  import { RayScene, bboxDiagonal } from '../core/analysis.js';
5
5
  import { pointNormals, resolveVertexNormals, triangulate } from '../core/topology.js';
6
6
  import { defineNode } from '../graph/registry.js';
@@ -568,7 +568,7 @@ defineBake({
568
568
  return finish(b, out, 4, [0.5, 0.5, 1, 1]);
569
569
  });
570
570
  };
571
- return mikkTSpaceReady() ? bakeWith() : loadMikkTSpace().then(bakeWith);
571
+ return mikkTSpaceReady() && mikkTSpaceHeapBytes() <= MIKK_RESET_BYTES ? bakeWith() : loadMikkTSpace().then(bakeWith);
572
572
  },
573
573
  });
574
574
  defineBake({
@@ -642,7 +642,7 @@ defineNode({
642
642
  type: 'sweep',
643
643
  category: 'curve',
644
644
  summary: 'Sweep a cross-section along curves using rotation-minimising frames (tubes, ribbons, rails, mouldings).',
645
- description: 'The profile is drawn in the XY plane around the origin, looking along the curve: at every curve point it is placed with its +Z along the curve (the direction of travel), its +Y on the up direction (the "up" param, or the point attribute up) kept perpendicular to the curve, and its +X = Y × Z, to the left of the direction of travel when up points up. The frame then turns as little as possible from point to point (rotation-minimising), so a flat ribbon does not twist on its own; twist adds a turn. The sides are wound so a closed profile drawn counter-clockwise (seen from +Z) faces outward; caps on open curves face away from the curve. uv: u runs around the profile, v along the curve; caps take the profile\'s flat layout.',
645
+ description: 'The profile is drawn in the XY plane around the origin, looking along the curve: at every curve point it is placed with its +Z along the curve (the direction of travel), its +Y on the up direction (the "up" param, or the point attribute up) kept perpendicular to the curve, and its +X = Y × Z, to the left of the direction of travel when up points up. The frame then turns as little as possible from point to point (rotation-minimising), so a flat ribbon does not twist on its own; twist adds a turn. The sides are wound so a closed profile drawn counter-clockwise (seen from +Z) faces outward; caps on open curves face away from the curve. The end caps lie in the profile plane, perpendicular to the curve at its last point: where the last segment is tilted, the cap is tilted with it and its rim pokes above or below a horizontal plane the tube was meant to end on (a ground or snap plane). End the path with a short horizontal run, or cut the result with clip. uv: u runs around the profile, v along the curve; caps take the profile\'s flat layout.',
646
646
  inputs: [
647
647
  { name: 'backbone', desc: 'curves to sweep along (Bezier/NURBS curves are sampled adaptively)' },
648
648
  { name: 'profile', desc: 'cross-section curve drawn in the XY plane (optional; one per backbone or a single shared one)', optional: true },
@@ -729,16 +729,16 @@ defineNode({
729
729
  type: 'revolve',
730
730
  category: 'curve',
731
731
  summary: 'Lathe: revolve profile curves around an axis (Y through the origin by default). Profiles touching the axis close up.',
732
- description: 'Each profile point turns around the axis line (through origin, along axis) at its own distance from it, so the profile can be drawn in any plane that holds the axis: the XY plane (x = radius) for the default Y axis, the XY plane (y = radius) for axis [1, 0, 0]. angle is measured from where the profile is drawn, turning counter-clockwise when the axis points at the viewer. Closed results face outward.',
732
+ description: 'Each profile point turns around the axis line (through origin, along axis) at its own distance from it, so the profile can be drawn in any plane that holds the axis: the XY plane (x = radius) for the default Y axis, the XY plane (y = radius) for axis [1, 0, 0]. angle is measured from where the profile is drawn, turning counter-clockwise when the axis points at the viewer. angle is measured from where the profile is drawn, so the plan angle of the result (atan2(z, x) seen from +Y) is minus the angle: a 0..90 revolve about Y ends at -90 in plan, towards -Z. Closed results face outward. Caps (caps on, partial angle) are only made for closed profiles, and then the result is a closed solid that is always oriented outward (flip has no effect on it). An open profile gives an open surface whose facing follows the profile direction and the sign of the angle span: if it faces the wrong way, set flip.',
733
733
  aliases: ['lathe'],
734
734
  inputs: [{ name: 'profile', desc: 'curves in a plane holding the axis (default: the XY plane, x = distance from the Y axis)' }],
735
735
  params: {
736
736
  axis: { type: 'vec3', default: [0, 1, 0], desc: 'direction of the axis to turn around', aliases: ['direction', 'dir'] },
737
737
  origin: { type: 'vec3', default: [0, 0, 0], desc: 'a point on the axis', aliases: ['center', 'pivot'] },
738
738
  segments: { type: 'int', default: 32, min: 3, max: 4096, desc: 'segments around', aliases: ['divisions', 'cols'] },
739
- angle: { type: 'vec2', default: [0, 360], desc: 'start/end angle in degrees' },
740
- caps: { type: 'bool', default: false, desc: 'cap partial revolves (closed profiles)' },
741
- flip: { type: 'bool', default: false, desc: 'reverse face orientation' },
739
+ angle: { type: 'vec2', default: [0, 360], desc: 'start/end angle in degrees, counter-clockwise seen from the axis tip (right-handed): 0..90 about Y runs from +X towards -Z' },
740
+ caps: { type: 'bool', default: false, desc: 'cap partial revolves of closed profiles (open profiles have no cap; the result is oriented outward)' },
741
+ flip: { type: 'bool', default: false, desc: 'reverse face orientation (open profiles; a closed solid is always re-oriented outward)' },
742
742
  },
743
743
  outputs: 'vertex uv',
744
744
  example: {
@@ -852,12 +852,12 @@ defineNode({
852
852
  aliases: ['linear_extrude', 'extrude2d'],
853
853
  inputs: [{ name: 'shapes', desc: 'closed polygons lying in a plane (e.g. shape2d, circle, text)' }],
854
854
  params: {
855
- height: { type: 'float', default: 1, desc: 'extrusion distance along the plane normal', aliases: ['depth', 'distance', 'h'] },
855
+ height: { type: 'float', default: 1, desc: 'extrusion distance along the plane normal: plane xz extrudes along +Y, xy along +Z, yz along +X', aliases: ['depth', 'distance', 'h'] },
856
856
  divisions: { type: 'int', default: 1, min: 1, max: 10000, desc: 'segments along the extrusion' },
857
857
  twist: { type: 'float', default: 0, desc: 'twist in degrees (about each shape centroid)' },
858
858
  scale_top: { type: 'vec2', default: [1, 1], desc: 'scale of the top cap (taper); [0,0] = pyramid' },
859
859
  center: { type: 'bool', default: false, desc: 'extrude symmetrically about the shape plane' },
860
- plane: { type: 'enum', options: ['auto', 'xz', 'xy', 'yz'], default: 'auto', desc: 'shape plane (auto = flattest axis)' },
860
+ plane: { type: 'enum', options: ['auto', 'xz', 'xy', 'yz'], default: 'auto', desc: 'plane the shapes lie in, which sets the extrusion direction: xz extrudes along +Y, xy along +Z, yz along +X (auto = the flattest axis)' },
861
861
  caps: { type: 'bool', default: true, desc: 'add top/bottom caps' },
862
862
  },
863
863
  outputs: 'prim groups top, bottom, side',
@@ -31,11 +31,11 @@ defineNode({
31
31
  from: { type: 'string', default: '', desc: 'input 1: which of its materials ("" = its only one)', aliases: ['source_material', 'use'] },
32
32
  group: P.group('prim', 'prims to assign ("" = all). e.g. "top", "@P.y>0", "0-9"'),
33
33
  base_color: { type: 'color', default: [0.8, 0.8, 0.8], desc: 'base colour [r,g,b] 0..1, "#rrggbb" or a name', aliases: ['basecolor', 'color', 'cd', 'albedo', 'diffuse'] },
34
- metallic: { type: 'float', default: 0, min: 0, max: 1, desc: 'metalness 0..1', aliases: ['metal', 'metalness'] },
35
- roughness: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'roughness 0..1', aliases: ['rough'] },
34
+ metallic: { type: 'float', default: 0, min: 0, max: 1, desc: 'metalness 0..1 (the glTF metallicFactor; texture_to_material with an orm map sets its own factors and ignores this)', aliases: ['metal', 'metalness'] },
35
+ roughness: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'roughness 0..1 (the glTF roughnessFactor, 1 under a roughness map; texture_to_material with an orm map sets its own factors and ignores this)', aliases: ['rough'] },
36
36
  emissive: { type: 'color', default: [0, 0, 0], desc: 'emitted colour; components above 1 export with KHR_materials_emissive_strength', aliases: ['emission', 'emit'] },
37
37
  alpha: { type: 'float', default: 1, min: 0, max: 1, desc: 'opacity; below 1 exports with alphaMode BLEND', aliases: ['opacity', 'opac'] },
38
- alpha_mode: { type: 'enum', options: ['auto', 'opaque', 'mask', 'blend'], default: 'auto', desc: 'auto preserves legacy scalar/vertex opacity; mask cuts out pixels below alpha_cutoff; explicit modes override auto' },
38
+ alpha_mode: { type: 'enum', options: ['auto', 'opaque', 'mask', 'blend'], default: 'auto', desc: 'auto blends only when alpha is below 1 (vertex alpha never changes the mode); mask cuts out pixels below alpha_cutoff; explicit modes override auto' },
39
39
  alpha_cutoff: { type: 'float', default: 0.5, min: 0, max: 1, desc: 'mask: discard where material alpha × texture alpha × vertex Alpha is below this value' },
40
40
  double_sided: { type: 'bool', default: false, desc: 'render both faces', aliases: ['doublesided', 'two_sided'] },
41
41
  unlit: { type: 'bool', default: false, desc: 'unlit shading (KHR_materials_unlit)', aliases: ['emissive_only', 'flat'] },
@@ -25,19 +25,46 @@ function withManifolds(fn) {
25
25
  catch { /* already freed */ }
26
26
  }
27
27
  }
28
+ /**
29
+ * One manifold for a solid made of pieces that may overlap. The kernel takes a multi-piece mesh as it is, so where its
30
+ * pieces overlap the region counts twice and a cut leaves it standing; the pieces are built apart and unioned instead,
31
+ * each with the cavity walls it holds (`solid`/`solids` from outwardPieces). One piece, or pieces whose bounds stay
32
+ * apart, go through as they are.
33
+ */
34
+ function solidManifold(g, L, o, track) {
35
+ const { solid, solids } = o;
36
+ if (solids < 2 || !o.overlap) {
37
+ const m = track(toManifold(g, L));
38
+ return { m, id: manifoldId(m) };
39
+ }
40
+ const { tris, triPrim } = triangulate(g);
41
+ const parts = Array.from({ length: solids }, () => ({ tris: [], triPrim: [] }));
42
+ for (let t = 0; t < triPrim.length; t++) {
43
+ const s = solid[triPrim[t]];
44
+ if (s < 0)
45
+ continue;
46
+ parts[s].tris.push(tris[t * 3], tris[t * 3 + 1], tris[t * 3 + 2]);
47
+ parts[s].triPrim.push(triPrim[t]);
48
+ }
49
+ const W = M(), id = W.Manifold.reserveIDs(1);
50
+ return { m: track(W.Manifold.union(parts.map((tri) => track(toManifold(g, L, { tri, id }))))), id };
51
+ }
28
52
  defineNode({
29
53
  type: 'boolean',
30
54
  category: 'solid',
31
- summary: 'Robust mesh boolean (union / subtract / intersect) of closed solids. Without B, unions A’s overlapping pieces.',
32
- description: 'The result is a closed solid made of polygons: each input face that survives the cut comes out as one polygon (a face the cut leaves with a hole as a few polygons sharing flat edges), so a bevel or inset after the boolean sees the real edges, and edges shorter than "tolerance" are collapsed so no slivers are left. Inside-out input pieces (a mirror without a winding flip) are turned outward first, with a warning.',
55
+ summary: 'Robust mesh boolean (union / subtract / intersect) of closed solids. Each input’s overlapping pieces are unioned first; without B, the result is that union of A.',
56
+ description: 'Either input may be a merge of pieces that overlap: each input is first made one solid, the union of its pieces (the inner wall of a hollow piece stays with it, so the hollow is kept), and the operation runs on those two solids, so subtracting a merge of cutters removes everything any of them covers. The result is a closed solid made of polygons: each input face that survives the cut comes out as one polygon (a face the cut leaves with a hole as a few polygons sharing flat edges), so a bevel or inset after the boolean sees the real edges, and edges shorter than "tolerance" are collapsed so no slivers are left. Inside-out input pieces (a mirror without a winding flip) are turned outward first, with a warning.',
33
57
  aliases: ['csg', 'bool', 'difference', 'union', 'intersect'],
34
- inputs: [{ name: 'a', desc: 'solid A' }, { name: 'b', desc: 'solid B (optional)', optional: true }],
58
+ inputs: [
59
+ { name: 'a', desc: 'solid A: closed pieces, which may overlap (unioned first)' },
60
+ { name: 'b', desc: 'solid B (optional): closed pieces, which may overlap (unioned first, so a merge of cutters cuts as one); its faces become the cut faces when subtracting', optional: true },
61
+ ],
35
62
  params: {
36
63
  operation: { type: 'enum', options: ['union', 'subtract', 'intersect'], default: 'subtract', desc: 'A ∪ B, A − B, or A ∩ B', aliases: ['op', 'mode'] },
37
64
  output: { type: 'enum', options: ['polygons', 'triangles'], default: 'polygons', desc: 'polygons = each surviving input face as one polygon (or a few around a hole); triangles = the kernel triangles as they come' },
38
65
  tolerance: { type: 'float', default: 0.00001, min: 0, desc: 'after the cut, collapse edges shorter than this and flatten slivers thinner than it, keeping the solid closed (0 = rounding only)', aliases: ['simplify', 'sliver'] },
39
66
  },
40
- outputs: 'prim groups from_a, from_b (cut faces come from B when subtracting); float point/vertex attributes interpolated',
67
+ outputs: 'prim groups from_a, from_b (cut faces come from B when subtracting); each face keeps the prim attributes of the input face it comes from (a cut face B’s material); float point/vertex attributes interpolated',
41
68
  example: {
42
69
  nodes: {
43
70
  box: { type: 'box' },
@@ -51,19 +78,19 @@ defineNode({
51
78
  const r = outwardPieces(g);
52
79
  if (r.flipped.length)
53
80
  warn(`${label}: ${r.flipped.length} piece(s) were inside out (faces pointing inward, e.g. mirrored without a winding flip) and were turned outward first; first ${primWhere(g, r.flipped[0])}`);
54
- return r.geo;
81
+ return r;
55
82
  };
56
- const A = outward(input(0), 'A'), B = hasInput(1) ? outward(input(1), 'B') : null;
83
+ const oA = outward(input(0), 'A'), oB = hasInput(1) ? outward(input(1), 'B') : null;
84
+ const A = oA.geo, B = oB?.geo ?? null;
57
85
  const L = propLayout(B ? [A, B] : [A]);
58
- const mA = track(toManifold(A, L));
59
- let r;
60
- const sources = [{ geo: A, id: manifoldId(mA) }];
61
- if (!B)
62
- r = track(M().Manifold.union(mA.decompose().map(track)));
63
- else {
64
- const mB = track(toManifold(B, L));
65
- sources.push({ geo: B, id: manifoldId(mB) });
66
- r = track(p.operation === 'union' ? mA.add(mB) : p.operation === 'intersect' ? mA.intersect(mB) : mA.subtract(mB));
86
+ // overlapping pieces of either input are unioned first
87
+ const sA = solidManifold(A, L, oA, track);
88
+ let r = sA.m;
89
+ const sources = [{ geo: A, id: sA.id }];
90
+ if (oB && B) {
91
+ const sB = solidManifold(B, L, oB, track);
92
+ sources.push({ geo: B, id: sB.id });
93
+ r = track(p.operation === 'union' ? sA.m.add(sB.m) : p.operation === 'intersect' ? sA.m.intersect(sB.m) : sA.m.subtract(sB.m));
67
94
  }
68
95
  if (p.tolerance > 0)
69
96
  r = track(r.simplify(p.tolerance));