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/cli.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // node src/cli.ts <graph.json> [--node name | --output name] [--var name=value]… [--frame N | --frames A-B[:step]] [--fps 24]
4
4
  // [--render out.png] [--views quad|quad_uv|turntable|persp|front_left|front,top|persp,uv|persp,section] [--checker] [--color-by attr]
5
5
  // [--wireframe all|hard|boundary|groups] [--section y:0.5] [--clip x:0.5] [--glyphs N|up|orient|v] [--labels groups,pieces,points,prims,attrib:name]
6
- // [--shading flat|matcap|ao|pbr] [--exposure 0] [--legend] [--size 800|1600x600] [--render-scale 2] [--heightfield-res 256|full]
6
+ // [--shading flat|matcap|ao|pbr] [--exposure 0] [--cd auto|ignore|multiply] [--grey] [--legend] [--size 800|1600x600] [--render-scale 2] [--heightfield-res 256|full]
7
7
  // [--transparent] [--no-grid] [--underlay ref.png [--underlay-opacity 0.5] [--underlay-fit bounds|width|height|view]] [--sockets]
8
8
  // [--heightfield-layer mask|<layer>|none] [--export out.glb]
9
9
  // [--compress meshopt] [--quantize] [--tangents auto|preserve|none] [--pcg | --pcg-struct] [--attributes P,N,pscale] [--up-axis z] [--scale 100]
@@ -45,8 +45,9 @@
45
45
  // node src/cli.ts update owner/name [folder] [--to 1.4] [--render <folder>]
46
46
  // node src/cli.ts update owner/name [folder] --from 1.3 --to 1.4 --apply
47
47
  // A graph-file cook adds a package its graph names for the first time (and says so); --locked fails instead, for a
48
- // build machine. --follow owner/name on a cook or view uses a package's working folder instead of its copy, for
49
- // looking: exports use the published copy.
48
+ // build machine. --follow owner/name on a cook or view uses a package's working folder instead of its copy; a
49
+ // graph-file cook's exports use it too (their source record says so under "followed"), but with --locked, which
50
+ // exports published versions alone. The viewer's exports use the published copy.
50
51
  // A package's published outputs cooked into a Godot project, and the Godot plugin (src/host/godot.ts, src/host/cook.ts;
51
52
  // integrations/godot/PROTOCOL.md):
52
53
  // node src/cli.ts cook <.topo | package folder | folder>... --for godot [--into <folder>] [--flat] [--skip a,b] [--instancing packed|expand] [--adopt] [--force] [--no-cache] [--timeout <s>] [--report <file>] [--progress json] [--quiet]
@@ -92,7 +93,8 @@ const graphName = (file) => path.basename(file).replace(/\.json$/i, '').replace(
92
93
  const prog = import.meta.url.endsWith('.ts') ? 'node src/cli.ts' : 'topotopo';
93
94
  // the hints of every command name it so
94
95
  setProgram(prog);
95
- if (argv.includes('-v') || argv.includes('-V') || argv.includes('--version')) {
96
+ // the global version flag is the first argument (or the only one); later ones belong to the command (use <package> --version 1.0)
97
+ if (['-v', '-V', '--version'].includes(argv[0] ?? '')) {
96
98
  console.log(`topotopo ${TOPOTOPO_VERSION}`);
97
99
  process.exit(0);
98
100
  }
@@ -111,11 +113,13 @@ if (!argv.length || argv.includes('-h') || argv.includes('--help')) {
111
113
  ' [--export-all] (every output with an export target in the graph, into exports/ of its package folder)',
112
114
  ' relative paths in the graph (file nodes, maps) read from its package folder: the nearest folder with a .topo file at or',
113
115
  ' above the graph file, else the graph file\'s folder; --render/--export/--underlay paths are relative to the current folder',
114
- ' [--follow owner/name] (show that package\'s working folder, where the package finds it, instead of its copy, for this run: renders and inspect use it, exports the published copy; repeat it)',
115
- ' [--locked] (a build machine: a package the graph names that the package does not use, or a copy missing or edited by hand, fails the run instead of being added)',
116
+ ' [--follow owner/name] (use that package\'s working folder, where the package finds it, instead of its copy, for this run: renders, inspect and exports use it, unpublished (the export\'s source record lists it under "followed"); repeat it)',
117
+ ' [--locked] (a build machine: a package the graph names that the package does not use, or a copy missing or edited by hand, fails the run instead of being added; exports use the published copies, whatever --follow shows)',
116
118
  ' render overlays: [--wireframe all|hard|boundary|groups] [--hard-angle 30] [--section y:0.5] [--clip x:0.5[:abs]]',
117
119
  ' [--glyphs N|up|orient|v] [--glyph-attrib a] [--labels groups,pieces,points,prims,attrib:name] [--legend] [--points]',
118
120
  ' [--shading flat|matcap|ao|pbr] [--exposure 0] [--size 800|1600x600] [--render-scale 2]',
121
+ ' [--cd auto|ignore|multiply] (shading pbr: auto = a named material wins over Cd, Cd colours prims without one; multiply = Cd tints the material too)',
122
+ ' [--grey] (value check: pbr with every base colour a neutral 18% grey; roughness, metallic and normal maps still apply)',
119
123
  ' views: persp front back left right top bottom front_left front_right back_left back_right uv section texture persp@<az>',
120
124
  ' framing: every 3D view fits the bounds; [--zoom 1] is relative to that fit (above 1 only with --look-at or --ortho-scale)',
121
125
  ' [--azimuth 35] (degrees around +Y: 0 = camera on +Z at the front, 90 = on +X, the right side) [--elevation 25] (degrees above the horizon)',
@@ -333,18 +337,35 @@ async function cook() {
333
337
  console.log(n);
334
338
  for (const p of pk.check())
335
339
  console.error(`warning: ${p}`);
336
- for (const f of pk.following())
337
- console.log(`following ${f.package}: its working folder ${f.dir} instead of its copy, for renders and inspect (exports use the published copy)`);
338
- // the packages shown live (--follow, a workspace that follows its own) are for looking: an export cooks with their
339
- // published copies (a cook of its own when the graph names one) and says so
340
- const exportNote = pk.publishedNote(graph);
341
- const exportScope = exportNote ? pk.published() : null;
340
+ // --follow names the working folders exports use too (their source record lists them under "followed"); --locked
341
+ // exports published versions alone. Other packages shown live (a workspace that follows its own) are for looking:
342
+ // an export cooks with their published copies (a cook of its own when the graph names one) and says so
343
+ const locked = argv.includes('--locked'), exportFollow = locked ? [] : followArgs;
344
+ for (const f of pk.following()) {
345
+ console.log(`following ${f.package}: its working folder ${f.dir} instead of its copy, ${exportFollow.includes(f.package) ? 'for renders, inspect and exports (unpublished: the export\'s source record says so)' : 'for renders and inspect (exports use the published copy)'}`);
346
+ }
347
+ const exportNote = pk.publishedNote(graph, exportFollow);
348
+ const exportScope = exportNote ? pk.published(exportFollow) : null;
349
+ /** What to do about followed packages an export would cook from published copies: publish them, or follow them. */
350
+ const publishOrFollow = (pkgs) => pkgs.map((u) => (locked
351
+ ? `publish ${u.package} (${prog} publish ${u.dir} --note "...") and use it: --locked exports published versions alone`
352
+ : `publish ${u.package} (${prog} publish ${u.dir} --note "...") or pass --follow ${u.package} to export from its working folder`)).join('; ');
353
+ /** Why an export cannot cook with the published copies: followed packages it names that have none in use. */
354
+ const exportBlocked = () => {
355
+ const missing = pk.unpublished(graph, exportFollow);
356
+ return missing.length ? `${missing.map((u) => u.package).join(', ')} ${missing.length === 1 ? 'has' : 'have'} no published version in use (this run shows ${missing.length === 1 ? 'its working folder' : 'their working folders'}, for looking): ${publishOrFollow(missing)}` : null;
357
+ };
342
358
  const forExport = async (r, node = r.target) => {
343
359
  if (!exportScope)
344
360
  return r;
361
+ const blocked = exportBlocked();
362
+ if (blocked)
363
+ fail(`export: ${blocked}; nothing was written`);
345
364
  const e = await engine.cook(graph, { target: node, frame: r.frame, fps: r.fps, scope: exportScope });
346
- if (!e.ok || !e.geo)
347
- fail(`export: with the published copies, ${node} does not cook (${e.errors.map((x) => `${x.node}: ${x.message}`).join('; ') || 'no geometry'}); nothing was written`);
365
+ if (!e.ok || !e.geo) {
366
+ const shown = pk.following().filter((f) => !exportFollow.includes(f.package)).map((f) => ({ package: f.package, dir: f.dir }));
367
+ fail(`export: with the published copies, ${node} does not cook (${e.errors.map((x) => `${x.node}: ${x.message}`).join('; ') || 'no geometry'})${shown.length ? `: ${publishOrFollow(shown)}` : ''}; nothing was written`);
368
+ }
348
369
  return e;
349
370
  };
350
371
  const fps = opt('--fps') !== undefined ? Number(opt('--fps')) : undefined;
@@ -392,20 +413,20 @@ async function cook() {
392
413
  }
393
414
  /** Every render flag (renderFlags reads them, plus --views, --color-by, --checker). */
394
415
  const RENDER_FLAGS = ['--wireframe', '--hard-angle', '--section', '--clip', '--glyphs', '--glyph-attrib', '--glyph-scale', '--max-glyphs', '--labels', '--max-labels',
395
- '--shading', '--ao-radius', '--size', '--render-scale', '--azimuth', '--elevation', '--zoom', '--look-at', '--bounds', '--ortho-scale', '--texture', '--max-triangles', '--exposure',
416
+ '--shading', '--ao-radius', '--size', '--render-scale', '--azimuth', '--elevation', '--zoom', '--look-at', '--bounds', '--ortho-scale', '--texture', '--max-triangles', '--exposure', '--cd',
396
417
  '--heightfield-res', '--heightfield-layer', '--underlay', '--underlay-opacity', '--underlay-fit', '--legend', '--points', '--annotate', '--textures', '--transparent',
397
- '--sockets', '--no-view-labels', '--no-footer', '--no-grid', '--views', '--color-by', '--checker'];
418
+ '--sockets', '--grey', '--no-view-labels', '--no-footer', '--no-grid', '--views', '--color-by', '--checker'];
398
419
  /** Render overlay flags → render tool arguments → RenderOptions (src/render/options.ts). */
399
420
  function renderFlags(get, has) {
400
421
  const a = {};
401
422
  for (const [f, k] of [['--wireframe', 'wireframe'], ['--hard-angle', 'hard_angle'], ['--section', 'section'], ['--clip', 'clip'], ['--glyphs', 'glyphs'],
402
423
  ['--glyph-attrib', 'glyph_attrib'], ['--glyph-scale', 'glyph_scale'], ['--max-glyphs', 'max_glyphs'], ['--labels', 'labels'], ['--max-labels', 'max_labels'],
403
424
  ['--shading', 'shading'], ['--ao-radius', 'ao_radius'], ['--size', 'size'], ['--render-scale', 'scale'], ['--azimuth', 'azimuth'], ['--elevation', 'elevation'],
404
- ['--zoom', 'zoom'], ['--look-at', 'look_at'], ['--bounds', 'bounds'], ['--ortho-scale', 'ortho_scale'], ['--texture', 'texture'], ['--max-triangles', 'max_triangles'], ['--exposure', 'exposure'],
425
+ ['--zoom', 'zoom'], ['--look-at', 'look_at'], ['--bounds', 'bounds'], ['--ortho-scale', 'ortho_scale'], ['--texture', 'texture'], ['--max-triangles', 'max_triangles'], ['--exposure', 'exposure'], ['--cd', 'cd'],
405
426
  ['--heightfield-res', 'heightfield_res'], ['--heightfield-layer', 'heightfield_layer'], ['--underlay-opacity', 'underlay_opacity'], ['--underlay-fit', 'underlay_fit']])
406
427
  if (get(f) !== undefined)
407
428
  a[k] = get(f);
408
- for (const [f, k] of [['--legend', 'legend'], ['--points', 'points'], ['--annotate', 'annotate'], ['--textures', 'textures'], ['--transparent', 'transparent'], ['--sockets', 'sockets']])
429
+ for (const [f, k] of [['--legend', 'legend'], ['--points', 'points'], ['--annotate', 'annotate'], ['--textures', 'textures'], ['--transparent', 'transparent'], ['--sockets', 'sockets'], ['--grey', 'grey']])
409
430
  if (has(f))
410
431
  a[k] = true;
411
432
  if (has('--no-view-labels'))
@@ -542,6 +563,9 @@ async function cook() {
542
563
  const refused = published.find((p) => p.target?.refused);
543
564
  if (refused)
544
565
  fail(`--export-all: "${refused.label}": ${prefixGone(refused.target.refused)}; nothing was written`);
566
+ const blocked = exportScope ? exportBlocked() : null;
567
+ if (blocked)
568
+ fail(`--export-all: ${blocked}; nothing was written`);
545
569
  for (const p of published) {
546
570
  if (!p.target)
547
571
  continue;
@@ -16,8 +16,17 @@ export declare function manifoldId(m: any): number;
16
16
  export declare class NotManifoldError extends Error {
17
17
  hint?: string;
18
18
  }
19
- /** Convert closed polygon geometry to a Manifold. Throws a descriptive error when not solid. */
20
- export declare function toManifold(g: Geometry, L?: PropLayout): any;
19
+ /**
20
+ * Convert closed polygon geometry to a Manifold. Throws a descriptive error when not solid. `part` builds it from some of
21
+ * the triangles only (`tri`, a subset of g's triangulation) under a shared original ID, for a solid split into parts.
22
+ */
23
+ export declare function toManifold(g: Geometry, L?: PropLayout, part?: {
24
+ tri: {
25
+ tris: ArrayLike<number>;
26
+ triPrim: ArrayLike<number>;
27
+ };
28
+ id: number;
29
+ }): any;
21
30
  export interface FromManifoldResult {
22
31
  geo: Geometry;
23
32
  primSource: Int32Array;
@@ -46,10 +46,13 @@ export function manifoldId(m) {
46
46
  export class NotManifoldError extends Error {
47
47
  hint;
48
48
  }
49
- /** Convert closed polygon geometry to a Manifold. Throws a descriptive error when not solid. */
50
- export function toManifold(g, L = propLayout([g])) {
49
+ /**
50
+ * Convert closed polygon geometry to a Manifold. Throws a descriptive error when not solid. `part` builds it from some of
51
+ * the triangles only (`tri`, a subset of g's triangulation) under a shared original ID, for a solid split into parts.
52
+ */
53
+ export function toManifold(g, L = propLayout([g]), part) {
51
54
  const W = M();
52
- const { tris, triPrim } = triangulate(g);
55
+ const { tris, triPrim } = part?.tri ?? triangulate(g);
53
56
  if (tris.length === 0)
54
57
  return new W.Manifold(new W.Mesh({ numProp: 3, vertProperties: new Float32Array(0), triVerts: new Uint32Array(0) }));
55
58
  const P = g.P;
@@ -97,7 +100,7 @@ export function toManifold(g, L = propLayout([g])) {
97
100
  for (let i = 0; i < tris.length; i++)
98
101
  triVerts[i] = vertOf[tris[i]];
99
102
  // reserve an explicit original ID so results can be traced back to this input
100
- const id = W.Manifold.reserveIDs(1);
103
+ const id = part?.id ?? W.Manifold.reserveIDs(1);
101
104
  const mesh = new W.Mesh({
102
105
  numProp: L.numProp,
103
106
  vertProperties: Float32Array.from(props),
@@ -5,7 +5,7 @@ export interface Material {
5
5
  roughness: number;
6
6
  emissive: [number, number, number];
7
7
  alpha: number;
8
- /** Absent = legacy auto (blend only for scalar / vertex opacity). */
8
+ /** Absent = auto: blend only when the material's own alpha is below 1 (vertex alpha never changes it). */
9
9
  alphaMode?: 'OPAQUE' | 'MASK' | 'BLEND';
10
10
  alphaCutoff?: number;
11
11
  doubleSided: boolean;
@@ -30,7 +30,8 @@ export declare const MATERIALS_DETAIL = "materials";
30
30
  export declare const DEFAULT_MATERIAL: Readonly<Material>;
31
31
  /** Fill missing fields with defaults and coerce types (tolerant of hand-written tables). */
32
32
  export declare function normalizeMaterial(m: any): Material;
33
- export declare function materialAlphaMode(m: Material, vertexAlpha?: boolean): 'OPAQUE' | 'MASK' | 'BLEND';
33
+ /** The glTF alpha mode of a material: its own alpha_mode, else BLEND when its scalar alpha is below 1. Vertex alpha is data and never promotes it. */
34
+ export declare function materialAlphaMode(m: Material): 'OPAQUE' | 'MASK' | 'BLEND';
34
35
  /** Every texture path used by a table (deduplicated, table order). */
35
36
  export declare function texturePaths(t: MaterialTable): string[];
36
37
  /** The material table stored on the geometry (empty when there is none or it does not parse). */
@@ -35,8 +35,9 @@ function alphaFields(m) {
35
35
  return {};
36
36
  return { alphaMode: mode, ...(mode === 'MASK' ? { alphaCutoff: Math.max(0, Math.min(1, num(m?.alphaCutoff, 0.5))) } : {}) };
37
37
  }
38
- export function materialAlphaMode(m, vertexAlpha = false) {
39
- return m.alphaMode ?? (m.alpha < 1 || vertexAlpha ? 'BLEND' : 'OPAQUE');
38
+ /** The glTF alpha mode of a material: its own alpha_mode, else BLEND when its scalar alpha is below 1. Vertex alpha is data and never promotes it. */
39
+ export function materialAlphaMode(m) {
40
+ return m.alphaMode ?? (m.alpha < 1 ? 'BLEND' : 'OPAQUE');
40
41
  }
41
42
  /** { textures } with the non-empty string slots, or {} when there is none (keeps texture-free tables unchanged). */
42
43
  function textureField(t) {
@@ -1,6 +1,14 @@
1
1
  import type { Geometry } from './geometry.ts';
2
- /** Load (once) and initialise the MikkTSpace WebAssembly module. */
2
+ /** loadMikkTSpace() starts a fresh MikkTSpace instance when the heap of the current one is larger than this. */
3
+ export declare const MIKK_RESET_BYTES: number;
4
+ /**
5
+ * Load and initialise the MikkTSpace WebAssembly module; when the loaded instance's heap has grown past
6
+ * MIKK_RESET_BYTES (or it aborted), replace it with a fresh one. Callers await this before each synchronous run of
7
+ * tangent work (an export, a render, a bake). While a replacement loads, mikkTSpaceReady() is false.
8
+ */
3
9
  export declare function loadMikkTSpace(): Promise<void>;
10
+ /** Bytes of WebAssembly memory the loaded MikkTSpace instance holds (0 when none is loaded). */
11
+ export declare const mikkTSpaceHeapBytes: () => number;
4
12
  /** True once loadMikkTSpace() has finished. */
5
13
  export declare const mikkTSpaceReady: () => boolean;
6
14
  export interface TangentDiagnostics {
@@ -9,6 +17,8 @@ export interface TangentDiagnostics {
9
17
  uvNonFinite: number;
10
18
  /** triangles whose uvs are collinear or coincide (zero uv area) */
11
19
  uvDegenerate: number;
20
+ /** collapsed-uv triangles skipped because their world-space area is tiny next to the mean (not counted in uvDegenerate or fallbackCorners) */
21
+ uvThin: number;
12
22
  /** corners that received the fallback tangent */
13
23
  fallbackCorners: number;
14
24
  /** the first triangle with a non-finite or collapsed uv, or -1 (warnings say where it is) */
@@ -6,39 +6,106 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
6
6
  }
7
7
  return path;
8
8
  };
9
+ /** loadMikkTSpace() starts a fresh MikkTSpace instance when the heap of the current one is larger than this. */
10
+ export const MIKK_RESET_BYTES = 256 * 2 ** 20;
9
11
  let mod = null;
10
12
  let loading = null;
11
- /** Load (once) and initialise the MikkTSpace WebAssembly module. */
13
+ let spent = false; // the instance aborted (out of memory): replace it on the next load
14
+ /**
15
+ * Load and initialise the MikkTSpace WebAssembly module; when the loaded instance's heap has grown past
16
+ * MIKK_RESET_BYTES (or it aborted), replace it with a fresh one. Callers await this before each synchronous run of
17
+ * tangent work (an export, a render, a bake). While a replacement loads, mikkTSpaceReady() is false.
18
+ */
12
19
  export async function loadMikkTSpace() {
13
- if (mod)
20
+ if (mod && !spent && mikkTSpaceHeapBytes() <= MIKK_RESET_BYTES)
14
21
  return;
15
22
  if (!loading) {
23
+ const old = mod;
24
+ mod = null;
16
25
  loading = (async () => {
17
- const spec = 'three/examples/jsm/libs/mikktspace.module.js';
18
- const m = await import(__rewriteRelativeImportExtension(spec));
19
- await m.ready;
20
- return m;
26
+ try {
27
+ let m;
28
+ if (old) {
29
+ m = old;
30
+ m.dispose();
31
+ }
32
+ else {
33
+ const spec = 'three/examples/jsm/libs/mikktspace.module.js';
34
+ m = await import(__rewriteRelativeImportExtension(spec));
35
+ }
36
+ await m.ready;
37
+ spent = false;
38
+ mod = m;
39
+ }
40
+ finally {
41
+ loading = null;
42
+ }
21
43
  })();
22
- loading.catch(() => { loading = null; });
23
44
  }
24
- mod = await loading;
45
+ await loading;
46
+ }
47
+ /** Bytes of WebAssembly memory the loaded MikkTSpace instance holds (0 when none is loaded). */
48
+ export const mikkTSpaceHeapBytes = () => mod?.wasm?.memory.buffer.byteLength ?? 0;
49
+ /** One generateTangents call on the raw exports: 4 floats (xyz, w) per corner. */
50
+ function generate(w, P, N, T) {
51
+ const pass = (a) => {
52
+ const p = w.__wbindgen_malloc(a.length * 4) >>> 0;
53
+ new Float32Array(w.memory.buffer, p, a.length).set(a);
54
+ return p;
55
+ };
56
+ const ret = w.__wbindgen_add_to_stack_pointer(-16) >>> 0;
57
+ try {
58
+ try {
59
+ w.generateTangents(ret, pass(P), P.length, pass(N), N.length, pass(T), T.length);
60
+ }
61
+ catch (e) {
62
+ if (!(e instanceof globalThis.WebAssembly.RuntimeError))
63
+ throw e; // a trap: in practice memory.grow failed at 4 GiB
64
+ spent = true;
65
+ throw new Error(`MikkTSpace ran out of WebAssembly memory (${w.memory.buffer.byteLength / 2 ** 20 | 0} MiB) on ${P.length / 9} triangles`);
66
+ }
67
+ const [ptr, len] = new Uint32Array(w.memory.buffer, ret, 2);
68
+ const out = new Float32Array(w.memory.buffer, ptr, len).slice();
69
+ w.__wbindgen_free(ptr, len * 4);
70
+ return out;
71
+ }
72
+ finally {
73
+ w.__wbindgen_add_to_stack_pointer(16);
74
+ }
25
75
  }
26
76
  /** True once loadMikkTSpace() has finished. */
27
- export const mikkTSpaceReady = () => mod !== null;
77
+ export const mikkTSpaceReady = () => mod?.wasm != null;
28
78
  /** uv triangles whose doubled area is below this fraction of their squared edge lengths are collapsed. */
29
79
  const UV_DEGENERATE = 1e-9;
80
+ /**
81
+ * A triangle whose world area is below this fraction of the mean triangle area is thin (the sides and back of a card
82
+ * a millimetre thick): planar uvs collapse on it by construction, so it is not reported as a collapsed uv.
83
+ */
84
+ const THIN_AREA = 1e-2;
30
85
  /**
31
86
  * MikkTSpace tangents for a triangle soup: pos and nrm 9 floats per triangle, uv 6 (TopoTopo convention). Returns 12
32
87
  * floats per triangle: xyz unit tangent and w = ±1 (bitangent = w · cross(N, T)). Throws when the module is not
33
88
  * loaded.
34
89
  */
35
90
  export function mikkTangents(pos, nrm, uv) {
36
- if (!mod)
91
+ if (!mod?.wasm)
37
92
  throw new Error('MikkTSpace is not loaded: await loadMikkTSpace() first (exportGLB, renderPBR and bake_normal do)');
38
93
  const nt = Math.floor(pos.length / 9);
39
- const diag = { triangles: nt, uvNonFinite: 0, uvDegenerate: 0, fallbackCorners: 0, firstBad: -1 };
40
- const bad = new Uint8Array(nt);
94
+ const diag = { triangles: nt, uvNonFinite: 0, uvDegenerate: 0, uvThin: 0, fallbackCorners: 0, firstBad: -1 };
95
+ const bad = new Uint8Array(nt); // 1 = reported, 2 = thin (fallback tangent, not reported)
41
96
  const P = Float32Array.from(pos), N = Float32Array.from(nrm), T = Float32Array.from(uv);
97
+ // world-space area of each triangle, and their mean
98
+ const area = new Float64Array(nt);
99
+ let areaSum = 0;
100
+ for (let t = 0; t < nt; t++) {
101
+ const o = t * 9, ax = P[o + 3] - P[o], ay = P[o + 4] - P[o + 1], az = P[o + 5] - P[o + 2], bx = P[o + 6] - P[o], by = P[o + 7] - P[o + 1], bz = P[o + 8] - P[o + 2];
102
+ const a = 0.5 * Math.hypot(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx);
103
+ if (Number.isFinite(a)) {
104
+ area[t] = a;
105
+ areaSum += a;
106
+ }
107
+ }
108
+ const thinBelow = nt ? (areaSum / nt) * THIN_AREA : 0;
42
109
  for (let t = 0; t < nt; t++) {
43
110
  let finite = true;
44
111
  for (let k = 0; k < 6; k++)
@@ -56,6 +123,11 @@ export function mikkTangents(pos, nrm, uv) {
56
123
  const u0 = T[t * 6], v0 = T[t * 6 + 1], du1 = T[t * 6 + 2] - u0, dv1 = T[t * 6 + 3] - v0, du2 = T[t * 6 + 4] - u0, dv2 = T[t * 6 + 5] - v0;
57
124
  const e2 = du1 * du1 + dv1 * dv1 + du2 * du2 + dv2 * dv2 + (du2 - du1) ** 2 + (dv2 - dv1) ** 2;
58
125
  if (!(Math.abs(du1 * dv2 - du2 * dv1) > UV_DEGENERATE * e2)) {
126
+ if (area[t] < thinBelow) {
127
+ diag.uvThin++;
128
+ bad[t] = 2;
129
+ continue;
130
+ }
59
131
  diag.uvDegenerate++;
60
132
  bad[t] = 1;
61
133
  if (diag.firstBad < 0)
@@ -75,7 +147,7 @@ export function mikkTangents(pos, nrm, uv) {
75
147
  N[i + 2] = 1;
76
148
  }
77
149
  }
78
- const out = nt ? mod.generateTangents(P, N, T) : new Float32Array(0);
150
+ const out = nt ? generate(mod.wasm, P, N, T) : new Float32Array(0);
79
151
  for (let t = 0; t < nt; t++)
80
152
  for (let k = 0; k < 3; k++) {
81
153
  const c = t * 3 + k, o = c * 4, n = c * 3;
@@ -93,7 +165,8 @@ export function mikkTangents(pos, nrm, uv) {
93
165
  out[o + 2] = z / l;
94
166
  continue;
95
167
  }
96
- diag.fallbackCorners++;
168
+ if (bad[t] !== 2)
169
+ diag.fallbackCorners++;
97
170
  // the world axis least aligned with N, made perpendicular to it
98
171
  const ax = Math.abs(nx), ay = Math.abs(ny), az = Math.abs(nz);
99
172
  const a = ax <= ay && ax <= az ? [1, 0, 0] : ay <= az ? [0, 1, 0] : [0, 0, 1];
@@ -172,7 +172,7 @@ export declare function warpLayer(a: Float32Array, ch: number, w: number, h: num
172
172
  export declare function sampleBilinear(a: Float32Array, ch: number, w: number, h: number, fx: number, fy: number, out: Float32Array, wrap: boolean): void;
173
173
  /**
174
174
  * Transform a layer: the result at (u, v) samples the source at the inverse of (repeat `tile` times, scale, rotate
175
- * by `rotate` degrees about the centre, offset). wrap = repeat the source; otherwise outside the source is 0.
175
+ * by `rotate` degrees about the centre, offset; the tile cells start at the lower-left corner). wrap = repeat the source; otherwise outside the source is 0.
176
176
  */
177
177
  export declare function transformLayer(a: Float32Array, ch: number, w: number, h: number, offset: [number, number], rotate: number, scale: [number, number], tile: [number, number], wrap: boolean): Float32Array;
178
178
  /** Ramp lookup table: n entries over 0..1 of a ramp evaluator (numbers or [r, g, b]). */
@@ -104,6 +104,12 @@ export function genPattern(o, w, h) {
104
104
  v = (cx + cy) & 1 ? 1 : 0;
105
105
  break;
106
106
  case 'stripes': {
107
+ // vertical stripes by the u count; with a u count of 1 the v count makes horizontal stripes
108
+ if (nx === 1 && ny > 1) {
109
+ cid = cellRand(cy, 0, o.seed);
110
+ v = aa(Math.min(fy, 1 - fy) * chh) * vary(cy, 0);
111
+ break;
112
+ }
107
113
  const sx = u * nx, scx = Math.floor(sx), sf = sx - scx;
108
114
  cid = cellRand(wrapI(scx, nx), 0, o.seed);
109
115
  v = aa(Math.min(sf, 1 - sf) * cw) * vary(wrapI(scx, nx), 0);
@@ -780,12 +786,14 @@ export function sampleBilinear(a, ch, w, h, fx, fy, out, wrap) {
780
786
  }
781
787
  /**
782
788
  * Transform a layer: the result at (u, v) samples the source at the inverse of (repeat `tile` times, scale, rotate
783
- * by `rotate` degrees about the centre, offset). wrap = repeat the source; otherwise outside the source is 0.
789
+ * by `rotate` degrees about the centre, offset; the tile cells start at the lower-left corner). wrap = repeat the source; otherwise outside the source is 0.
784
790
  */
785
791
  export function transformLayer(a, ch, w, h, offset, rotate, scale, tile, wrap) {
786
792
  const out = new Float32Array(a.length);
787
793
  const th = (-rotate * Math.PI) / 180, c = Math.cos(th), s = Math.sin(th);
788
- const sx = (scale[0] || 1e-6) / Math.max(1e-6, tile[0] || 1), sy = (scale[1] || 1e-6) / Math.max(1e-6, tile[1] || 1);
794
+ const sx = scale[0] || 1e-6, sy = scale[1] || 1e-6;
795
+ const tx = Math.max(1e-6, tile[0] || 1), ty = Math.max(1e-6, tile[1] || 1);
796
+ const tiled = tx !== 1 || ty !== 1;
789
797
  const tmp = new Float32Array(ch);
790
798
  const aspect = h / w;
791
799
  for (let j = 0; j < h; j++)
@@ -797,7 +805,8 @@ export function transformLayer(a, ch, w, h, offset, rotate, scale, tile, wrap) {
797
805
  y = (ry / aspect) / sy + 0.5;
798
806
  if (!wrap && (x < 0 || x > 1 || y < 0 || y > 1))
799
807
  continue;
800
- sampleBilinear(a, ch, w, h, x * w, (1 - y) * h, tmp, wrap);
808
+ // tiling is about the lower-left corner of the transformed image: cell 0 starts at uv (0, 0)
809
+ sampleBilinear(a, ch, w, h, x * tx * w, (1 - y * ty) * h, tmp, wrap || tiled);
801
810
  out.set(tmp, (j * w + i) * ch);
802
811
  }
803
812
  return out;
@@ -81,11 +81,15 @@ export declare function orientOutward(g: Geometry): Geometry;
81
81
  * Turn inside-out pieces outward: a connected piece with negative signed volume flips, unless it lies inside another
82
82
  * piece's bounds (the inner wall of a hollow solid faces inward on purpose). A mirror without a winding flip, or a
83
83
  * hand-built cutter, gives such pieces; booleans would make inverted walls from them. Returns the first prim of each
84
- * flipped piece.
84
+ * flipped piece, and the solids the pieces make: each outward piece with the inward pieces (cavity walls) it holds,
85
+ * as a solid index per prim (-1 for empty prims), and whether the bounds of two solids overlap.
85
86
  */
86
87
  export declare function outwardPieces(g: Geometry): {
87
88
  geo: Geometry;
88
89
  flipped: number[];
90
+ solid: Int32Array;
91
+ solids: number;
92
+ overlap: boolean;
89
93
  };
90
94
  /** Quick topology health report used by inspect and by solid ops. */
91
95
  export declare function topologyReport(g: Geometry): {
@@ -691,12 +691,13 @@ export function orientOutward(g) {
691
691
  * Turn inside-out pieces outward: a connected piece with negative signed volume flips, unless it lies inside another
692
692
  * piece's bounds (the inner wall of a hollow solid faces inward on purpose). A mirror without a winding flip, or a
693
693
  * hand-built cutter, gives such pieces; booleans would make inverted walls from them. Returns the first prim of each
694
- * flipped piece.
694
+ * flipped piece, and the solids the pieces make: each outward piece with the inward pieces (cavity walls) it holds,
695
+ * as a solid index per prim (-1 for empty prims), and whether the bounds of two solids overlap.
695
696
  */
696
697
  export function outwardPieces(g) {
697
698
  const { primClass, count } = connectivity(g);
698
699
  if (!count)
699
- return { geo: g, flipped: [] };
700
+ return { geo: g, flipped: [], solid: new Int32Array(g.numPrims).fill(-1), solids: 0, overlap: false };
700
701
  const { tris, triPrim } = triangulate(g);
701
702
  const vol = new Float64Array(count), first = new Int32Array(count).fill(-1);
702
703
  const lo = new Float64Array(count * 3).fill(Infinity), hi = new Float64Array(count * 3).fill(-Infinity);
@@ -736,9 +737,39 @@ export function outwardPieces(g) {
736
737
  flip[c] = 1;
737
738
  flipped.push(first[c]);
738
739
  }
740
+ // a cavity wall joins the smallest outward piece around it
741
+ const size = (c) => (flip[c] ? -vol[c] : vol[c]);
742
+ const owner = new Int32Array(count), index = new Int32Array(count).fill(-1);
743
+ let solids = 0;
744
+ for (let c = 0; c < count; c++) {
745
+ owner[c] = c;
746
+ if (!(size(c) < 0))
747
+ continue;
748
+ let best = -1;
749
+ for (let o = 0; o < count; o++)
750
+ if (size(o) > -size(c) && inside(c, o) && (best < 0 || size(o) < size(best)))
751
+ best = o;
752
+ if (best >= 0)
753
+ owner[c] = best;
754
+ }
755
+ const roots = [];
756
+ for (let c = 0; c < count; c++)
757
+ if (owner[c] === c) {
758
+ index[c] = solids++;
759
+ roots.push(c);
760
+ }
761
+ const solid = Int32Array.from(primClass, (c) => (c >= 0 ? index[owner[c]] : -1));
762
+ // bounds that overlap or touch (touching pieces fuse in a union), swept along x
763
+ roots.sort((a, b) => lo[a * 3] - lo[b * 3]);
764
+ let overlap = false;
765
+ for (let i = 0; i < roots.length && !overlap; i++)
766
+ for (let j = i + 1; j < roots.length && lo[roots[j] * 3] <= hi[roots[i] * 3] && !overlap; j++) {
767
+ const a = roots[i], b = roots[j];
768
+ overlap = lo[a * 3 + 1] <= hi[b * 3 + 1] && lo[b * 3 + 1] <= hi[a * 3 + 1] && lo[a * 3 + 2] <= hi[b * 3 + 2] && lo[b * 3 + 2] <= hi[a * 3 + 2];
769
+ }
739
770
  if (!flipped.length)
740
- return { geo: g, flipped };
741
- return { geo: reversePrims(g, Uint8Array.from(primClass, (c) => (c >= 0 ? flip[c] : 0))), flipped };
771
+ return { geo: g, flipped, solid, solids, overlap };
772
+ return { geo: reversePrims(g, Uint8Array.from(primClass, (c) => (c >= 0 ? flip[c] : 0))), flipped, solid, solids, overlap };
742
773
  }
743
774
  /** Quick topology health report used by inspect and by solid ops. */
744
775
  export function topologyReport(g) {
@@ -111,8 +111,15 @@ export interface FrameRange {
111
111
  end: number;
112
112
  step?: number;
113
113
  }
114
+ /**
115
+ * Approximate memory of a geometry for the cache budget: topology, attributes, groups and volume buffers. With `seen`,
116
+ * a buffer already in the set is not counted again (shared between geometries); the buffers counted are added to it.
117
+ */
118
+ export declare function geoBytes(g: Geometry, seen?: Set<ArrayBuffer>): number;
114
119
  declare class GeoCache {
115
120
  private map;
121
+ /** volume buffer → entries holding it: a shared buffer is charged once */
122
+ private owners;
116
123
  private bytes;
117
124
  maxBytes: number;
118
125
  constructor(maxBytes?: number);
@@ -49,7 +49,19 @@ import { VAR_NAME_HINT, varNameError } from './vars.js';
49
49
  import { codeVarNames, pickVars } from '../core/usercode.js';
50
50
  export { STOPPED };
51
51
  // ---------------------------------------------------------------- cache
52
- function geoBytes(g) {
52
+ /** The large typed-array buffers the volumes of a geometry hold (image and heightfield layers, SDF grid samples), each once. */
53
+ function volumeBuffers(g) {
54
+ const out = new Set();
55
+ for (const v of g.volumes) {
56
+ if (v.kind === 'grid')
57
+ out.add(v.values.buffer);
58
+ else if (v.kind === 'image' || v.kind === 'heightfield')
59
+ for (const l of v.layers.values())
60
+ out.add(l.buffer);
61
+ }
62
+ return [...out];
63
+ }
64
+ function baseBytes(g) {
53
65
  let b = g.primStart.byteLength + g.vertexPoint.byteLength + g.primClosed.byteLength + 256;
54
66
  // packed: the per-prim arrays (sources are shared with the nodes that made them)
55
67
  if (g.primKind)
@@ -63,8 +75,26 @@ function geoBytes(g) {
63
75
  b += m.byteLength;
64
76
  return b;
65
77
  }
78
+ /**
79
+ * Approximate memory of a geometry for the cache budget: topology, attributes, groups and volume buffers. With `seen`,
80
+ * a buffer already in the set is not counted again (shared between geometries); the buffers counted are added to it.
81
+ */
82
+ export function geoBytes(g, seen) {
83
+ let b = baseBytes(g);
84
+ for (const buf of volumeBuffers(g)) {
85
+ if (seen) {
86
+ if (seen.has(buf))
87
+ continue;
88
+ seen.add(buf);
89
+ }
90
+ b += buf.byteLength;
91
+ }
92
+ return b;
93
+ }
66
94
  class GeoCache {
67
95
  map = new Map();
96
+ /** volume buffer → entries holding it: a shared buffer is charged once */
97
+ owners = new Map();
68
98
  bytes = 0;
69
99
  maxBytes;
70
100
  constructor(maxBytes = 1.5e9) { this.maxBytes = maxBytes; }
@@ -79,19 +109,37 @@ class GeoCache {
79
109
  set(k, geo) {
80
110
  if (this.map.has(k))
81
111
  return;
82
- const bytes = geoBytes(geo);
83
- if (bytes > this.maxBytes / 2)
112
+ const own = baseBytes(geo), bufs = volumeBuffers(geo);
113
+ let add = own;
114
+ for (const buf of bufs)
115
+ if (!this.owners.has(buf))
116
+ add += buf.byteLength;
117
+ if (add > this.maxBytes / 2)
84
118
  return;
85
- this.map.set(k, { geo, bytes });
86
- this.bytes += bytes;
119
+ for (const buf of bufs) {
120
+ if (!this.owners.has(buf))
121
+ this.bytes += buf.byteLength;
122
+ this.owners.set(buf, (this.owners.get(buf) ?? 0) + 1);
123
+ }
124
+ this.map.set(k, { geo, bytes: own });
125
+ this.bytes += own;
87
126
  for (const [key, e] of this.map) {
88
127
  if (this.bytes <= this.maxBytes)
89
128
  break;
90
129
  this.map.delete(key);
91
130
  this.bytes -= e.bytes;
131
+ for (const buf of volumeBuffers(e.geo)) {
132
+ const n = (this.owners.get(buf) ?? 1) - 1;
133
+ if (n > 0)
134
+ this.owners.set(buf, n);
135
+ else {
136
+ this.owners.delete(buf);
137
+ this.bytes -= buf.byteLength;
138
+ }
139
+ }
92
140
  }
93
141
  }
94
- clear() { this.map.clear(); this.bytes = 0; }
142
+ clear() { this.map.clear(); this.owners.clear(); this.bytes = 0; }
95
143
  get stats() { return { entries: this.map.size, mb: +(this.bytes / 1e6).toFixed(1) }; }
96
144
  }
97
145
  // ---------------------------------------------------------------- helpers