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
@@ -19,6 +19,7 @@ import { LabelPlacer, ambientOcclusion, dotOv, drawLabel, drawLegend, lineOv } f
19
19
  import { withHeightfieldPreview } from '../core/heightfield.js';
20
20
  import { withSdfGridPreview } from '../core/sdfgrid.js';
21
21
  import { drawTextureView, textureSampler } from './texview.js';
22
+ import { pbrScene, preparePBR } from './pbr.js';
22
23
  /** View presets accepted by parseViews (MCP render "views", CLI --views). */
23
24
  export const VIEW_PRESETS = {
24
25
  quad: ['persp', 'front', 'right', 'top'],
@@ -48,7 +49,7 @@ export function parseViews(spec) {
48
49
  const AXES = ['x', 'y', 'z'];
49
50
  const WIRE_MODES = ['none', 'all', 'hard', 'boundary', 'groups'];
50
51
  const GLYPH_MODES = ['none', 'N', 'up', 'orient', 'v', 'custom'];
51
- const SHADING_MODES = ['default', 'flat', 'matcap', 'ao'];
52
+ const SHADING_MODES = ['default', 'flat', 'matcap', 'ao', 'pbr'];
52
53
  const CUT_C = [0.93, 0.4, 0.3], CUT_FLIP_C = [0.25, 0.38, 0.9];
53
54
  const ORTHO = {
54
55
  front: { f: [0, 0, -1], r: [1, 0, 0], u: [0, 1, 0], label: 'FRONT X> Y^' },
@@ -101,7 +102,16 @@ function makeCam(name, bmin, bmax, W, H, o, kind = name, azDeg, secAxis = 1) {
101
102
  const s = (o.orthoScale && o.orthoScale > 0 ? W / o.orthoScale : Math.min((W / 2) * 0.86 / Math.max(halfW, 1e-6), (H / 2) * 0.82 / Math.max(halfH, 1e-6))) * zoom;
102
103
  return { name, persp: false, eye: c, f: v.f, r: v.r, u: v.u, c, focal: 0, scale: s };
103
104
  }
104
- /** Render the geometry; returns RGBA pixels. */
105
+ /**
106
+ * Render with the asynchronous preparation shading 'pbr' needs (MikkTSpace, texture files through readFile, usually
107
+ * Host.readFile); every other mode renders exactly as renderGeometry does.
108
+ */
109
+ export async function renderGeometryAsync(g, o = {}, readFile) {
110
+ if (o.shading === 'pbr' && !o.pbrTextures)
111
+ o = { ...o, pbrTextures: await preparePBR(g, readFile) };
112
+ return renderGeometry(g, o);
113
+ }
114
+ /** Render the geometry; returns RGBA pixels. Shading 'pbr' needs renderGeometryAsync first (or MikkTSpace loaded). */
105
115
  export function renderGeometry(g, o = {}) {
106
116
  // packed instances are drawn expanded (within a triangle budget), spline curves as polylines, see core/packed.ts
107
117
  if (g.hasPacked() || g.hasSplines()) {
@@ -331,18 +341,24 @@ export function renderGeometry(g, o = {}) {
331
341
  out[i + 2] = 0.13;
332
342
  }
333
343
  // --- uv data (uv view, checker shading)
334
- const uvd = views.includes('uv') || o.checker || o.textures ? readUV(g) : null;
344
+ const materialNames = primMaterials(g), materialTable = readMaterials(g);
345
+ const hasMasks = Object.values(materialTable).some((m) => m.alphaMode === 'MASK');
346
+ const uvd = views.includes('uv') || o.checker || o.textures || hasMasks ? readUV(g) : null;
335
347
  const checkerOn = !!(o.checker && uvd);
336
348
  if (o.checker && !uvd)
337
349
  notes.push('checker: no uv attribute (run uv_project, uv_unwrap or uv_flatten first)');
338
350
  // base colour maps (image textures) on the mesh: texture × Cd (as glTF multiplies COLOR_0), off under checker / colour-by
339
- const texS = o.textures && uvd && !checkerOn && !o.colorBy && !o.highlight ? textureSampler(g, notes) : null;
351
+ const showTextureColor = !!(o.textures && !checkerOn && !o.colorBy && !o.highlight);
352
+ const texS = uvd && (showTextureColor || hasMasks) ? textureSampler(g, notes) : null;
340
353
  if (o.textures && !uvd && nTri)
341
354
  notes.push('textures: no uv attribute, maps not shown');
342
355
  else if (o.textures && uvd && !texS && !checkerOn)
343
356
  notes.push('textures: no material with an image base colour (texture_to_material)');
344
357
  const texCd = !!(texS && g.findAttrib('Cd', ['vertex', 'point', 'prim', 'detail']));
345
- const texRGB = [0, 0, 0];
358
+ const texRGB = [0, 0, 0, 1];
359
+ const alphaAttr = resolveAttr('Alpha');
360
+ const alphaOf = (v) => alphaAttr && alphaAttr.attr.type !== 'string' && !alphaAttr.attr.isArray
361
+ ? alphaAttr.attr.data[elemIndex(alphaAttr.cls, v) * alphaAttr.attr.size] : 1;
346
362
  // ---------------------------------------------------------------- opt-in overlays, shared by all views
347
363
  const ovDesc = []; // footer line 2: what is switched on
348
364
  if (pscale)
@@ -376,7 +392,17 @@ export function renderGeometry(g, o = {}) {
376
392
  // shading
377
393
  const flatN = shadingMode === 'flat' && nTri ? primNormals(g) : null;
378
394
  const matcap = shadingMode === 'matcap';
379
- if (shadingMode)
395
+ let pbrS = null;
396
+ if (shadingMode === 'pbr' && nTri) {
397
+ const ev = o.exposure ?? 0;
398
+ if (!Number.isFinite(ev))
399
+ throw new Error(`render: exposure expects a number of stops, got ${o.exposure}`);
400
+ pbrS = pbrScene(g, tris, triPrim, o.pbrTextures, ev, notes);
401
+ if (o.colorBy || o.highlight || o.checker)
402
+ notes.push('pbr: color_by, highlight and checker are not shown under shading "pbr"');
403
+ ovDesc.push(`SHADING PBR STUDIO EV ${fmtNum(ev)} (${pbrS.summary.toUpperCase()})`);
404
+ }
405
+ else if (shadingMode)
380
406
  ovDesc.push(`SHADING ${shadingMode.toUpperCase()}`);
381
407
  // section / clip planes
382
408
  const planeAt = (k, off, abs) => (abs ? off ?? 0 : bmin[k] + (bmax[k] - bmin[k]) * (off ?? 0.5));
@@ -783,6 +809,8 @@ export function renderGeometry(g, o = {}) {
783
809
  }
784
810
  }
785
811
  const cam = makeCam(vname, bmin, bmax, W, H, o, kind, azDeg, secK);
812
+ if (pbrS)
813
+ pbrS.camera(cam.r, cam.u, cam.f);
786
814
  // project points
787
815
  const sx = new Float32Array(np), sy = new Float32Array(np), cz = new Float32Array(np), vz = new Float32Array(np);
788
816
  const project = (x, y, z, outp) => {
@@ -873,6 +901,7 @@ export function renderGeometry(g, o = {}) {
873
901
  const na = [0, 0, 0], nb = [0, 0, 0], nc = [0, 0, 0];
874
902
  const tn = [0, 0, 0];
875
903
  const chk = [0, 0, 0];
904
+ const pbrUV0 = [0, 0], pbrUV1 = [0, 0], pbrUV2 = [0, 0], pbrV = [0, 0, 0], pbrRGB = [0, 0, 0];
876
905
  const bf = vi === backView ? new Uint8Array(W * H) : null;
877
906
  for (let t = 0; t < nTri; t++) {
878
907
  const va = tris[t * 3], vb = tris[t * 3 + 1], vc = tris[t * 3 + 2];
@@ -903,7 +932,9 @@ export function renderGeometry(g, o = {}) {
903
932
  const fnw = cross3(e1, e2);
904
933
  const toCam = cam.persp ? [cam.eye[0] - Pd[a * 3], cam.eye[1] - Pd[a * 3 + 1], cam.eye[2] - Pd[a * 3 + 2]] : [-cam.f[0], -cam.f[1], -cam.f[2]];
905
934
  const back = dot3(fnw, toCam) < 0;
906
- const suspicious = back && conn !== null && closedPiece[conn.primClass[triPrim[t]]] === 1;
935
+ const material = materialNames ? materialTable[materialNames[triPrim[t]]] : undefined;
936
+ const alphaMask = material?.alphaMode === 'MASK';
937
+ const suspicious = back && !material?.doubleSided && conn !== null && closedPiece[conn.primClass[triPrim[t]]] === 1;
907
938
  if (flatN) {
908
939
  const p = triPrim[t] * 3;
909
940
  na[0] = nb[0] = nc[0] = flatN[p];
@@ -930,6 +961,8 @@ export function renderGeometry(g, o = {}) {
930
961
  }
931
962
  const za = cz[a], zb2 = cz[b], zc = cz[c];
932
963
  const inv = 1 / area;
964
+ // shading 'pbr': screen-space gradients of the affine weights (uv derivatives for the texture level of detail)
965
+ const g0x = (by - cy) * inv, g0y = (cx - bx) * inv, g1x = (cy - ay) * inv, g1y = (ax - cx) * inv;
933
966
  // base colour map: mip level from the triangle's texels per screen pixel (render/texview.ts)
934
967
  const texP = texS && texS.has(triPrim[t]) ? triPrim[t] : -1;
935
968
  let texLod = 0;
@@ -962,15 +995,69 @@ export function renderGeometry(g, o = {}) {
962
995
  if ((p0 * qa + p1 * qb + p2 * qc - cC) * cS > 0)
963
996
  continue;
964
997
  }
965
- zb[zi] = depth;
966
- if (bf)
967
- bf[zi] = suspicious ? 1 : 0;
998
+ const aw0 = w0, aw1 = w1;
968
999
  if (cam.persp) {
969
1000
  const s = w0 * za + w1 * zb2 + w2 * zc;
970
1001
  w0 = (w0 * za) / s;
971
1002
  w1 = (w1 * zb2) / s;
972
1003
  w2 = 1 - w0 - w1;
973
1004
  }
1005
+ if (alphaMask) {
1006
+ let alpha = material.alpha * (alphaOf(va) * w0 + alphaOf(vb) * w1 + alphaOf(vc) * w2);
1007
+ if (texP >= 0) {
1008
+ texS.sample(texP, uvd[va * 2] * w0 + uvd[vb * 2] * w1 + uvd[vc * 2] * w2, uvd[va * 2 + 1] * w0 + uvd[vb * 2 + 1] * w1 + uvd[vc * 2 + 1] * w2, texLod, texRGB);
1009
+ alpha *= texRGB[3];
1010
+ }
1011
+ if (alpha < (material.alphaCutoff ?? 0.5))
1012
+ continue;
1013
+ }
1014
+ zb[zi] = depth;
1015
+ if (bf)
1016
+ bf[zi] = suspicious ? 1 : 0;
1017
+ if (pbrS) {
1018
+ let dudx = 0, dvdx = 0, dudy = 0, dvdy = 0;
1019
+ if (pbrS.hasUV) {
1020
+ const at = (q0, q1, out) => {
1021
+ let p0 = q0, p1 = q1;
1022
+ if (cam.persp) {
1023
+ const s = q0 * za + q1 * zb2 + (1 - q0 - q1) * zc;
1024
+ p0 = (q0 * za) / s;
1025
+ p1 = (q1 * zb2) / s;
1026
+ }
1027
+ pbrS.uvAt(t, p0, p1, 1 - p0 - p1, out);
1028
+ };
1029
+ at(aw0, aw1, pbrUV0);
1030
+ at(aw0 + g0x, aw1 + g1x, pbrUV1);
1031
+ at(aw0 + g0y, aw1 + g1y, pbrUV2);
1032
+ dudx = pbrUV1[0] - pbrUV0[0];
1033
+ dvdx = pbrUV1[1] - pbrUV0[1];
1034
+ dudy = pbrUV2[0] - pbrUV0[0];
1035
+ dvdy = pbrUV2[1] - pbrUV0[1];
1036
+ }
1037
+ if (cam.persp) {
1038
+ const px3 = Pd[a * 3] * w0 + Pd[b * 3] * w1 + Pd[c * 3] * w2, py3 = Pd[a * 3 + 1] * w0 + Pd[b * 3 + 1] * w1 + Pd[c * 3 + 1] * w2, pz3 = Pd[a * 3 + 2] * w0 + Pd[b * 3 + 2] * w1 + Pd[c * 3 + 2] * w2;
1039
+ const vx = cam.eye[0] - px3, vy = cam.eye[1] - py3, vz2 = cam.eye[2] - pz3, vl = Math.hypot(vx, vy, vz2) || 1;
1040
+ pbrV[0] = vx / vl;
1041
+ pbrV[1] = vy / vl;
1042
+ pbrV[2] = vz2 / vl;
1043
+ }
1044
+ else {
1045
+ pbrV[0] = -cam.f[0];
1046
+ pbrV[1] = -cam.f[1];
1047
+ pbrV[2] = -cam.f[2];
1048
+ }
1049
+ pbrS.shade(t, w0, w1, w2, dudx, dvdx, dudy, dvdy, pbrV, back, pbrRGB);
1050
+ const ci = zi * 3;
1051
+ if (suspicious) {
1052
+ pbrRGB[0] = pbrRGB[0] * 0.35 + 0.12;
1053
+ pbrRGB[1] = pbrRGB[1] * 0.35 + 0.22;
1054
+ pbrRGB[2] = pbrRGB[2] * 0.35 + 0.6;
1055
+ }
1056
+ col[ci] = pbrRGB[0];
1057
+ col[ci + 1] = pbrRGB[1];
1058
+ col[ci + 2] = pbrRGB[2];
1059
+ continue;
1060
+ }
974
1061
  tn[0] = ca[0] * w0 + cb[0] * w1 + cc[0] * w2;
975
1062
  tn[1] = ca[1] * w0 + cb[1] * w1 + cc[1] * w2;
976
1063
  tn[2] = ca[2] * w0 + cb[2] * w1 + cc[2] * w2;
@@ -1011,7 +1098,7 @@ export function renderGeometry(g, o = {}) {
1011
1098
  fb = fb * 0.35 + 0.6;
1012
1099
  }
1013
1100
  }
1014
- else if (texP >= 0) {
1101
+ else if (texP >= 0 && showTextureColor) {
1015
1102
  texS.sample(texP, uvd[va * 2] * w0 + uvd[vb * 2] * w1 + uvd[vc * 2] * w2, uvd[va * 2 + 1] * w0 + uvd[vb * 2 + 1] * w1 + uvd[vc * 2 + 1] * w2, texLod, texRGB);
1016
1103
  if (texCd) {
1017
1104
  fr *= texRGB[0];
@@ -12,7 +12,7 @@ export declare function drawTextureView(g: Geometry, col: Float32Array, W: numbe
12
12
  * texture view does. Anything else (points, prims, other volumes) is returned as it is.
13
13
  */
14
14
  export declare function withImagePreview(g: Geometry, max?: number): Geometry;
15
- /** Base colour maps per prim for persp/ortho views: sample(prim, u, v, lod, out) fills out with RGB and returns true. */
15
+ /** Base colour maps per prim for persp/ortho views: sample fills out with RGBA (grey has alpha 1). */
16
16
  export interface TextureSampler {
17
17
  /** true when prim p shows a base colour map */
18
18
  has(p: number): boolean;
@@ -7,6 +7,7 @@ import { Geometry } from '../core/geometry.js';
7
7
  import { Image, channelsOf, imageRef, isImage, referenceableImages, resizeLayer } from '../core/image.js';
8
8
  import { MATERIAL_ATTRIB, normalizeMaterial, primMaterials, readMaterials, writeMaterials } from '../core/materials.js';
9
9
  import { drawText, textWidth } from './font.js';
10
+ import { imageRowOfV } from '../core/texcoord.js';
10
11
  const SLOT_LABEL = { baseColor: 'BASE COLOR', normal: 'NORMAL', roughness: 'ROUGHNESS', orm: 'ORM' };
11
12
  /**
12
13
  * What the texture view shows for a spec: "" = every image (at most 16); an image name = that image (all its layers
@@ -221,11 +222,15 @@ export function textureSampler(g, notes) {
221
222
  sample(p, u, v, lod, out) {
222
223
  const chain = perPrim[p];
223
224
  const m = chain[Math.max(0, Math.min(chain.length - 1, Math.round(lod)))];
224
- const x = u * m.w - 0.5, y = (1 - v) * m.h - 0.5;
225
+ const x = u * m.w - 0.5, y = imageRowOfV(v, m.h) - 0.5;
225
226
  const x0 = Math.floor(x), y0 = Math.floor(y), tx = x - x0, ty = y - y0;
226
227
  const i0 = wrap(x0, m.w), i1 = wrap(x0 + 1, m.w), j0 = wrap(y0, m.h), j1 = wrap(y0 + 1, m.h);
227
228
  const d = m.data, ch = m.ch;
228
- for (let c = 0; c < 3; c++) {
229
+ for (let c = 0; c < 4; c++) {
230
+ if (ch === 1 && c === 3) {
231
+ out[c] = 1;
232
+ continue;
233
+ }
229
234
  const cc = ch === 4 ? c : 0;
230
235
  const a = d[(j0 * m.w + i0) * ch + cc], b = d[(j0 * m.w + i1) * ch + cc], e = d[(j1 * m.w + i0) * ch + cc], f = d[(j1 * m.w + i1) * ch + cc];
231
236
  const t = a + (b - a) * tx, s = e + (f - e) * tx;
@@ -1,4 +1,4 @@
1
- // Cameras and views (docs/design/viewer.md section 3): our own controller, no OrbitControls. Tumble around a pivot,
1
+ // Cameras and views: our own controller, no OrbitControls. Tumble around a pivot,
2
2
  // track, dolly towards a point, no inertia: the camera moves only while the person drags, scrolls or frames. Seven
3
3
  // named cameras (persp and the axis views); one view, or four in a 2×2 quad, each showing one of them with its own
4
4
  // shading. Orthographic cameras cannot tumble. Near and far planes follow the scene size (the renderer keeps a
@@ -0,0 +1,80 @@
1
+ // The embed page (src/gallery/pages.ts embedPage): a baked preview.glb under an orbit camera, made to sit in an iframe
2
+ // on a board. Not the editor viewport: no panels, no diagnostic overlays, and three's
3
+ // OrbitControls (left drag orbits, right drag pans, wheel zooms, as model viewers do), slowly turning until touched.
4
+ // The thumbnail behind the canvas stays visible until the model is in, and when it cannot load.
5
+ import * as THREE from 'three';
6
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
7
+ import { parseGLB, createLights } from './scene.js';
8
+
9
+ const canvas = document.getElementById('gl');
10
+ const note = document.getElementById('note');
11
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
12
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
13
+ renderer.setClearColor(0x2b2d31, 1);
14
+ const scene = new THREE.Scene();
15
+ const camera = new THREE.PerspectiveCamera(35, 1, 0.01, 1000);
16
+ const controls = new OrbitControls(camera, canvas);
17
+ controls.enableDamping = true;
18
+ controls.autoRotate = true;
19
+ controls.autoRotateSpeed = 0.6;
20
+ controls.addEventListener('start', () => { controls.autoRotate = false; });
21
+ const lights = createLights(scene);
22
+
23
+ let dirty = true;
24
+ controls.addEventListener('change', () => { dirty = true; });
25
+ const resize = () => {
26
+ const w = canvas.clientWidth, h = canvas.clientHeight;
27
+ if (!w || !h) return;
28
+ renderer.setSize(w, h, false);
29
+ camera.aspect = w / h;
30
+ camera.updateProjectionMatrix();
31
+ dirty = true;
32
+ };
33
+ new ResizeObserver(resize).observe(canvas);
34
+
35
+ /** Frame the bounding sphere from the thumbnail's angle (35° around, 25° up). */
36
+ function frame(root) {
37
+ const box = new THREE.Box3().setFromObject(root);
38
+ if (box.isEmpty()) return;
39
+ const sphere = box.getBoundingSphere(new THREE.Sphere());
40
+ const r = Math.max(sphere.radius, 1e-3);
41
+ const dist = r / Math.sin(THREE.MathUtils.degToRad(camera.fov / 2)) * 1.05;
42
+ const az = THREE.MathUtils.degToRad(35), el = THREE.MathUtils.degToRad(25);
43
+ camera.position.copy(sphere.center).add(new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)).multiplyScalar(dist));
44
+ camera.near = dist / 1000;
45
+ camera.far = dist * 100;
46
+ camera.updateProjectionMatrix();
47
+ controls.target.copy(sphere.center);
48
+ controls.minDistance = r * 0.05;
49
+ controls.maxDistance = dist * 20;
50
+ controls.update();
51
+ }
52
+
53
+ async function load() {
54
+ try {
55
+ const res = await fetch(canvas.dataset.src);
56
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
57
+ const root = await parseGLB(await res.arrayBuffer());
58
+ root.traverse((o) => {
59
+ // a point's size in pixels, as in the editor, not in metres
60
+ if (o.isPoints) { o.material.size = 3; o.material.sizeAttenuation = false; }
61
+ if (o.isMesh) for (const m of [o.material].flat()) m.side = THREE.DoubleSide;
62
+ });
63
+ scene.add(root);
64
+ resize();
65
+ frame(root);
66
+ document.getElementById('poster').hidden = true;
67
+ } catch (e) {
68
+ canvas.hidden = true;
69
+ note.textContent = `3D preview unavailable (${e.message})`;
70
+ }
71
+ }
72
+
73
+ renderer.setAnimationLoop(() => {
74
+ const moving = controls.update() || controls.autoRotate;
75
+ if (!dirty && !moving) return;
76
+ lights.follow(camera, controls.target);
77
+ renderer.render(scene, camera);
78
+ dirty = false;
79
+ });
80
+ load();
@@ -1,4 +1,4 @@
1
- // The adaptive metre grid, the world axes, the axis gizmo and each view's readouts (docs/design/viewer.md section 4).
1
+ // The adaptive metre grid, the world axes, the axis gizmo and each view's readouts.
2
2
  // The grid lies on y = 0 under persp and the top / bottom views, and on each side view's own plane (front: XY,
3
3
  // right: ZY), as Maya and Houdini draw them; minor lines every `step`, major every 10 steps, the axes in the
4
4
  // standard colours. One plane is set up again before each view renders.
@@ -1,4 +1,4 @@
1
- // Guides (docs/design/viewer.md section 7): nulls, curves, areas and volumes, the markers agents read as
1
+ // Guides: nulls, curves, areas and volumes, the markers agents read as
2
2
  // inputs/markers.json (roles site, path, zone, volume). Drawn as the standard objects they are, in one desaturated
3
3
  // cyan, on top of the scene: a null is an axis cross (its radius circle only while hovered or selected), a curve a
4
4
  // polyline with CV squares and a direction tick, an area a closed curve with a light diagonal hatch, a volume a wire
@@ -1,4 +1,4 @@
1
- // The keymap of docs/design/viewer.md section 9: one table of actions, four presets (TopoTopo, the default;
1
+ // The keymap: one table of actions, four presets (TopoTopo, the default;
2
2
  // Maya, Houdini, Blender). Each row carries the text the overlay prints per preset and the built actions' bindings:
3
3
  // chord → action. Transform and snapping rows (phase 2) ship their text but no bindings, so a preset never changes
4
4
  // shape later. Plain data and functions: the overlay is the only DOM code, and it runs only when called.
@@ -1,4 +1,4 @@
1
- // Reference layers (docs/design/viewer.md section 7): the person's files in inputs/, one outliner row each, shown
1
+ // Reference layers: the person's files in inputs/, one outliner row each, shown
2
2
  // when their eye is on (remembered in this browser), drawn in a display mode of their own (as the view by default;
3
3
  // ghost is one of the modes). PNGs stand as unlit image planes at their pixel aspect, one metre tall, beside the
4
4
  // scene. Files dropped on the page are uploaded to inputs/ (POST /api/inputs).
@@ -1,4 +1,4 @@
1
- // The viewer page (docs/design/viewer.md): boot, layout, the render loop over the views, the keymap and the mouse,
1
+ // The viewer page: boot, layout, the render loop over the views, the keymap and the mouse,
2
2
  // the status bar and the server's event stream. The camera moves only when the person moves it or frames: loading,
3
3
  // cooking, saving and placing never frame (the one exception is the very first view, when nothing is remembered).
4
4
  import * as THREE from 'three';
@@ -4,7 +4,7 @@
4
4
  // input file (help topic "inputs": string attributes name and role, pscale = a null's radius).
5
5
  // Plain functions, no DOM and no three.js: tested in Node (test/viewer-logic.ts).
6
6
 
7
- /** The roles the LLM reads, and the editor's name for each (docs/design/viewer.md section 7). */
7
+ /** The roles the LLM reads, and the editor's name for each. */
8
8
  export const MARKER_KINDS = ['site', 'path', 'zone', 'volume'];
9
9
  export const EDITOR_NAMES = { site: 'null', path: 'curve', zone: 'area', volume: 'volume' };
10
10
  /** [fewest, most] points per kind: a null's point, a curve's CVs, an area's corners, a volume's two ground corners */
@@ -1,4 +1,4 @@
1
- // The left panel (docs/design/viewer.md section 2): three tabs. Scene is the outliner tree: the output (the node being
1
+ // The left panel: three tabs. Scene is the outliner tree: the output (the node being
2
2
  // shown), the graph's nodes (click one to show its result; the square is its display flag) and the guides. Outputs
3
3
  // is the published results (outputs.js). Inputs is the files in inputs/ (reference layers) with Add input.
4
4
  // Rows carry a visibility eye, a display mode and the name; selecting a row selects in the viewport and back.
@@ -1,4 +1,4 @@
1
- // The properties column (docs/design/viewer.md sections 2 and 8): what the selection is (a guide's name, kind,
1
+ // The properties column: what the selection is (a guide's name, kind,
2
2
  // translate / rotate / scale, radius or height and the attributes the LLM reads; a layer's file, counts, bbox and
3
3
  // display mode; the output's summary; a piece's size), and below it the Controls: the graph's exposed vars as
4
4
  // sliders, fields, checkboxes, menus and colour pickers. Drags post at most every 100 ms; each control resets to its
@@ -1,9 +1,10 @@
1
- // Geometry in the viewport (docs/design/viewer.md section 7): the cooked output and, through the same MeshObject,
1
+ // Geometry in the viewport: the cooked output and, through the same MeshObject,
2
2
  // the reference layers. Display modes (as the view's shading, shaded, wire, shaded + wire, points, bounding box,
3
3
  // ghost), backfaces tinted blue and the open / non-manifold / flipped edges drawn as the render tool draws them,
4
4
  // connected pieces for picking and box selection, and the orange selection wireframe.
5
5
  import * as THREE from 'three';
6
6
  import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
7
+ import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
7
8
  import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
8
9
  import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
9
10
  import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
@@ -40,6 +41,8 @@ export function nudge(material) {
40
41
 
41
42
  /** Backfaces tinted blue as the render tool tints them (src/render/raster.ts): colour × 0.35 + (0.12, 0.22, 0.6). */
42
43
  export function backTint(material) {
44
+ // Authored two-sided surfaces (cards, cloth, etc.) have intentional backfaces.
45
+ if (material.side === THREE.DoubleSide) return material;
43
46
  if (material.userData.backTint) return material;
44
47
  material.userData.backTint = true;
45
48
  material.side = THREE.DoubleSide;
@@ -502,7 +505,8 @@ export class MeshObject {
502
505
  }
503
506
 
504
507
  // --------------------------------------------------------------------------------------------- loading GLBs
505
- const loader = new GLTFLoader();
508
+ // meshopt for the gallery's baked preview.glb (the live routes send plain GLB)
509
+ const loader = new GLTFLoader().setMeshoptDecoder(MeshoptDecoder);
506
510
  /** Parse a GLB buffer into a three.js scene, or throw. */
507
511
  export const parseGLB = (buf) => new Promise((resolve, reject) => loader.parse(buf, '', (g) => resolve(g.scene), reject));
508
512
  /** A PNG arrives as flat quads with unlit materials named "image:<name>" (src/render/texview.ts): a picture. */
@@ -1,4 +1,4 @@
1
- // Picking and selecting in the viewport (docs/design/viewer.md section 5): click selects what is under the cursor
1
+ // Picking and selecting in the viewport: click selects what is under the cursor
2
2
  // (a guide, else the nearest piece of the output or of a reference layer), Shift adds, Ctrl removes, a drag pulls a
3
3
  // box that selects what lies wholly inside it, a click on nothing clears. Hover draws a dimmer highlight. All
4
4
  // positions are viewport pixels.
@@ -1,4 +1,4 @@
1
- // The selection the outliner and the viewport share (docs/design/viewer.md section 5): an ordered set of ids, the
1
+ // The selection the outliner and the viewport share: an ordered set of ids, the
2
2
  // last one the lead (the properties panel shows it). Ids name objects ("out", "layer:<path>", "guide:<id>") or a
3
3
  // connected piece of a mesh object ("out#12", "layer:<path>#3").
4
4
  // Plain functions, tested in Node (test/viewer-logic.ts).
@@ -1,4 +1,4 @@
1
- // The status bar's own lines (docs/design/viewer.md section 4): what the page says when nothing else is reported.
1
+ // The status bar's own lines: what the page says when nothing else is reported.
2
2
  // Plain functions, tested in Node (test/viewer-logic.ts).
3
3
 
4
4
  /** While the event stream is connected. */
@@ -1,4 +1,4 @@
1
- /* The viewer page (docs/design/viewer.md): a neutral editor UI around the viewport. Section 7 colours: viewport
1
+ /* The viewer page: a neutral editor UI around the viewport. Colours: viewport
2
2
  #2b2d31, selection orange #f0a030, guides one desaturated cyan. */
3
3
  :root {
4
4
  --bg: #1f2124; --panel: #26282c; --panel2: #2c2f33; --line: #3a3d42; --text: #d6d9dd; --dim: #8c939b; --faint: #5d636b;
@@ -1,7 +1,7 @@
1
1
  // Units on screen: the adaptive grid's step and how lengths and coordinates are printed (metres, Y up).
2
2
  // Plain functions, tested in Node (test/viewer-logic.ts).
3
3
 
4
- /** The grid steps the views choose from (docs/design/viewer.md section 4), in metres. */
4
+ /** The grid steps the views choose from, in metres. */
5
5
  export const GRID_STEPS = [0.01, 0.1, 1, 10, 100, 1000];
6
6
  /** Major lines every this many steps. */
7
7
  export const MAJOR_EVERY = 10;
@@ -1,4 +1,4 @@
1
- // The Controls section's rules (docs/design/viewer.md section 8): which widget a var gets, a slider's range and step,
1
+ // The Controls section's rules: which widget a var gets, a slider's range and step,
2
2
  // how values print. Plain functions, tested in Node (test/viewer-logic.ts); props.js builds the widgets.
3
3
 
4
4
  export const isNum = (v) => typeof v === 'number' && Number.isFinite(v);
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
6
  <title>TopoTopo Viewer</title>
7
7
  <link rel="icon" href="data:,">
8
- <!-- the viewer page (docs/design/viewer.md): ES modules from /app/, three.js from /vendor/three/, no build step -->
8
+ <!-- the viewer page: ES modules from /app/, three.js from /vendor/three/, no build step -->
9
9
  <link rel="stylesheet" href="/app/style.css">
10
10
  <link rel="stylesheet" href="/app/outputs.css">
11
11
  <script type="importmap">{ "imports": { "three": "/vendor/three/build/three.module.js", "three/addons/": "/vendor/three/examples/jsm/" } }</script>
@@ -1,5 +1,8 @@
1
1
  import type { Workspace } from '../workspace.ts';
2
2
  import type { Geometry } from '../core/geometry.ts';
3
+ export declare const appDir: string;
4
+ export declare const threeDir: string;
5
+ export declare const MIME: Record<string, string>;
3
6
  /** largest file POST /api/inputs accepts */
4
7
  export declare const MAX_UPLOAD: number;
5
8
  /**
@@ -45,7 +48,16 @@ export interface ViewerOptions {
45
48
  */
46
49
  persistGraph?: (graph: string) => void;
47
50
  }
48
- export declare function startViewer(ws: Workspace, port?: number, opts?: ViewerOptions): Promise<{
51
+ /** A running viewer: its URL, the open pages (SSE clients), a workspace swap, and close. */
52
+ export interface Viewer {
49
53
  url: string;
54
+ /** pages open now (event-stream connections) */
55
+ clients: () => number;
56
+ /**
57
+ * Show another workspace (the MCP library tool's open): the routes serve it from now on and every open page
58
+ * reconnects and reloads, so the URL stays the same.
59
+ */
60
+ setWorkspace: (ws: Workspace) => void;
50
61
  close: () => void;
51
- }>;
62
+ }
63
+ export declare function startViewer(ws: Workspace, port?: number, opts?: ViewerOptions): Promise<Viewer>;
@@ -1,5 +1,5 @@
1
1
  // Live preview web server: serves the viewer page (index.html, a shell loading the ES modules of app/ and three.js
2
- // from /vendor/three/; docs/design/viewer.md) that shows any graph/node of the workspace and refreshes over
2
+ // from /vendor/three/) that shows any graph/node of the workspace and refreshes over
3
3
  // Server-Sent Events whenever a graph is rebuilt/edited.
4
4
  // It is also the human's control surface: files dropped on the page are stored in the workspace's inputs/ (under
5
5
  // `topotopo view`, the inputs/ beside the graph file) and shown as reference layers, the graph's exposed vars are set
@@ -14,10 +14,10 @@ import { Transform } from 'node:stream';
14
14
  import { pipeline } from 'node:stream/promises';
15
15
  import { fileURLToPath } from 'node:url';
16
16
  import { GeoBuilder } from '../core/geometry.js';
17
- import { exportGeometry, exportGeometryAsync } from '../io/export.js';
17
+ import { exportGeometry } from '../io/export.js';
18
+ import { previewGLB } from '../render/preview.js';
18
19
  import { summarize } from '../inspect.js';
19
20
  import { withHeightfieldPreview } from '../core/heightfield.js';
20
- import { withImagePreview } from '../render/texview.js';
21
21
  import { wiringOf } from '../graph/engine.js';
22
22
  import { createOutputs } from './outputs.js';
23
23
  import { renderGeometry } from '../render/raster.js';
@@ -27,9 +27,9 @@ import { imageFromPNGFile } from '../io/textures.js';
27
27
  import { MARKER_KINDS as KINDS, MarkerError, parseMarkers as parseMarkerList } from './app/markers.js';
28
28
  // index.html and app/ sit next to this module (the build copies them to dist/viewer/)
29
29
  const here = path.dirname(fileURLToPath(import.meta.url));
30
- const appDir = path.join(here, 'app');
30
+ export const appDir = path.join(here, 'app');
31
31
  // three.js where Node resolves it: this checkout's node_modules, or the hoisted copy next to an installed package
32
- const threeDir = (() => {
32
+ export const threeDir = (() => {
33
33
  try {
34
34
  return path.resolve(path.dirname(fileURLToPath(import.meta.resolve('three'))), '..');
35
35
  }
@@ -37,7 +37,7 @@ const threeDir = (() => {
37
37
  return path.resolve(here, '..', '..', 'node_modules', 'three');
38
38
  }
39
39
  })();
40
- const MIME = { '.js': 'text/javascript', '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.json': 'application/json', '.glb': 'model/gltf-binary' };
40
+ export const MIME = { '.js': 'text/javascript', '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.json': 'application/json', '.glb': 'model/gltf-binary' };
41
41
  /** largest file POST /api/inputs accepts */
42
42
  export const MAX_UPLOAD = 512 * 1024 * 1024;
43
43
  /** uploads in progress are written next to their target as `.<name>.<n>.part`, then renamed */
@@ -47,7 +47,7 @@ class HttpError extends Error {
47
47
  constructor(status, msg) { super(msg); this.status = status; }
48
48
  }
49
49
  /** The shape every geometry route serves: the same GLB options as /api/geo; images alone show as textured quads. */
50
- const toGLB = (g) => exportGeometryAsync(withImagePreview(withHeightfieldPreview(g)), 'glb', { splitByName: false, lineMode: 'lines', custom: false });
50
+ const toGLB = (g) => previewGLB(g);
51
51
  const issueText = (e) => `[${e.node}] ${e.message}`;
52
52
  /**
53
53
  * A dropped file's name as stored in inputs/: a plain basename with its extension. Path separators and ".." are
@@ -151,12 +151,13 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
151
151
  c.write(msg);
152
152
  };
153
153
  ws.listeners.add(broadcast);
154
- const outputs = createOutputs(ws, () => broadcast({ outputs: true }), { persistGraph: opts.persistGraph });
154
+ const makeOutputs = () => createOutputs(ws, () => broadcast({ outputs: true }), { persistGraph: opts.persistGraph });
155
+ let outputs = makeOutputs();
155
156
  // ---------------------------------------------------------------- inputs/
156
157
  let inputsVersion = 0;
157
158
  const inputsChanged = () => broadcast({ inputs: ++inputsVersion });
158
159
  const listInputs = () => ws.listInputs().filter((f) => !PART_RE.test(f.path));
159
- const inputsWhere = opts.inputsWhere ?? (path.dirname(ws.inputDir) === ws.dir ? 'in the workspace' : `in ${path.dirname(ws.inputDir)}`);
160
+ const inputsWhere = () => opts.inputsWhere ?? (path.dirname(ws.inputDir) === ws.dir ? 'in the workspace' : `in ${path.dirname(ws.inputDir)}`);
160
161
  // Files copied into inputs/ by other means (file manager, an agent) show up too, once the folder exists. The viewer
161
162
  // does not make it just to watch it (`topotopo view`'s inputs/ beside the graph file appears with the first drop):
162
163
  // uploads and listings start the watch when the folder is there by then.
@@ -460,7 +461,7 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
460
461
  }
461
462
  // where dropped files go: the absolute folder, and in words for the page ("beside house.json")
462
463
  if (u.pathname === '/api/inputs_dir')
463
- return json(200, { dir: ws.inputDir, where: inputsWhere });
464
+ return json(200, { dir: ws.inputDir, where: inputsWhere() });
464
465
  if (u.pathname === '/api/markers') {
465
466
  if (req.method === 'POST')
466
467
  return json(200, saveMarkers(parseMarkers(await readJSON(req))));
@@ -557,6 +558,25 @@ export async function startViewer(ws, port = Number(process.env.TOPOTOPO_PORT ??
557
558
  keepAlive.unref();
558
559
  return {
559
560
  url: `http://127.0.0.1:${actual}/`,
561
+ clients: () => clients.size,
562
+ setWorkspace: (next) => {
563
+ if (next === ws || closed)
564
+ return;
565
+ ws.listeners.delete(broadcast);
566
+ outputs.close();
567
+ clearTimeout(watchTimer);
568
+ unwatch();
569
+ varQueues.clear();
570
+ inputThumbs.clear();
571
+ ws = next;
572
+ ws.listeners.add(broadcast);
573
+ outputs = makeOutputs();
574
+ watchInputs();
575
+ // the pages reconnect (EventSource retries) and reload graphs, layers and guides from the new workspace
576
+ for (const c of clients)
577
+ c.end();
578
+ clients.clear();
579
+ },
560
580
  close: () => {
561
581
  closed = true;
562
582
  outputs.close();
@@ -19,6 +19,7 @@ export interface EditOp {
19
19
  value?: boolean;
20
20
  note?: string;
21
21
  }
22
+ export declare const NAME_RE: RegExp;
22
23
  /** A file under <workspace>/inputs. */
23
24
  export interface InputFile {
24
25
  /** posix path relative to inputs/ (a file node reads it as "inputs/" + path) */
@@ -105,4 +106,16 @@ export declare class Workspace {
105
106
  report: CookReport;
106
107
  }>;
107
108
  cook(name: string, target?: string, frame?: number): Promise<CookReport>;
109
+ private watchers;
110
+ private watchTimers;
111
+ /**
112
+ * Follow what other processes write into graphs/ and assets/ (a second Workspace on the same folder: the gallery's
113
+ * editor next to an MCP server, or a person editing the JSON). A graph file whose content differs from the stored
114
+ * graph replaces it and notifies the listeners; a removed file removes the graph. Our own writes read back equal, so
115
+ * they change nothing. An asset whose content changed is registered again and every graph is notified (any may use
116
+ * it); a removed asset stays registered until the next load(). Two writers to one graph: the last write wins.
117
+ */
118
+ watch(): void;
119
+ /** Stop following the folders (watch()). */
120
+ unwatch(): void;
108
121
  }