Public: anyone can read this; the crew can change it.

An .stl page shows its volume and surface area, computed on the server #15863

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/15838-an-stl-page-shows-its-volume-and-surface → main 0 commits fork 4 threads · 4 unresolved

  • Merged. torque/15838-an-stl-page-shows-its-volume-and-surface was merged into main as f20cc60.

Review

Sign in to review this change.
9 files changed +247 −10
docs/features/file-stl.md +7
@@ -18,6 +18,13 @@ The first paint carries the triangle count and box, read by the server, so they
1818 A drag is an orbit, never a pick. The markers take the page's `--accent`. In the terminal, `m` on a model
1919 asks for two points (`x y z x y z`) and answers with the same words. The arithmetic and the pick rules are
2020 `measure.ts`, checked by hand in `test/model-measure.test.ts`.
21 - **Volume** and **Area** are rows beside the Box, in the same unit word cubed and squared (`8000 units³`, `2400 units²`), read on the server
22 so they show with JavaScript off. The terminal's file view carries them on its line: `12 triangles · 20 × 20 × 20 units · Volume 8000 units³ · Area 2400 units²`.
23 Volume is the divergence theorem, `V = (1/6) Σ v0 · (v1 × v2)` over the triangles; area is `A = (1/2) Σ |(v1 − v0) × (v2 − v0)|`
24 (`mesh_measure_solid.ts`, checked by hand on a cube and a tetrahedron in `test/mesh-solid.test.ts`).
25 A volume needs a closed mesh (every edge shared by two triangles) wound one way round (each edge walked once each way):
26 an open mesh reads `open mesh` and one with mixed winding reads `mixed winding, no volume`, never a number; its area still shows.
27 A mesh wound wholly inward reads as its magnitude. The unit is whatever the file's coordinates are in; an STL names none.
2128 - The **Box** row is the part's width × depth × height in that unit, shown for each format the viewer draws (STL, 3MF, OBJ, PLY, DAE, glTF).
2229 - Editing a mesh is not built yet. The editor's refusal on a model or a STEP file says what opens it instead
2330 (`opens_with.ts`); STEP still shows its part card, not geometry (that needs a CAD kernel in WebAssembly, a later pull).
src/web/render/mesh_measure_solid.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * The volume and surface area of a triangle mesh, computed from its parsed triangles. Pure:
3 * `positions` in (x, y, z per corner, three corners a triangle), plain numbers out, in the
4 * file's own unit cubed and squared (an STL names none).
5 *
6 * Volume is the divergence theorem over the surface: V = (1/6) Σ v0 · (v1 × v2), one signed
7 * tetrahedron to the origin per triangle; its sign is negative when the triangles wind inward.
8 * Area is A = (1/2) Σ |(v1 − v0) × (v2 − v0)|. A volume only means something when the mesh is
9 * closed: every undirected edge is shared by exactly two triangles (else it is open), and wound
10 * consistently: each edge is walked once in each direction (else the signed sum mixes insides and
11 * outsides and means nothing).
12 */
13
14 export interface SolidMeasure {
15 /** Signed volume, unit³. Only meaningful when `closed` and `consistent`. */
16 readonly volume: number;
17 /** Surface area, unit². */
18 readonly area: number;
19 /** Every edge is shared by exactly two triangles. */
20 readonly closed: boolean;
21 /** Every edge is walked once in each direction, so all triangles wind the same way round. */
22 readonly consistent: boolean;
23 }
24
25 /**
26 * Vertex ids by exact coordinates, in an open-addressing table keyed on the float bits:
27 * no string per corner, so a 20 MB mesh is measured without a million-entry string Map.
28 */
29 function vertexIds(positions: Float32Array, corners: number): Int32Array {
30 const bits = new Uint32Array(positions.buffer, positions.byteOffset, corners * 3);
31 let size = 16;
32 while (size < corners * 2) size *= 2;
33 const table = new Int32Array(size).fill(-1);
34 const ids = new Int32Array(corners);
outdated

Allocating an array through .map and a tuple cast for every triangle is slow on a 20 MB mesh and hard to read. Read the nine values directly from positions[o + i].

35 let next = 0;
36 for (let c = 0; c < corners; c++) {
37 const x = bits[c * 3]!, y = bits[c * 3 + 1]!, z = bits[c * 3 + 2]!;
38 let h = (Math.imul(x, 0x9e3779b1) ^ Math.imul(y, 0x85ebca6b) ^ Math.imul(z, 0xc2b2ae35)) >>> 0;
39 h = (h ^ (h >>> 15)) & (size - 1);
40 for (;;) {
41 const at = table[h]!;
42 if (at < 0) {
43 // First sight of this corner: its own index is the representative.
44 table[h] = c;
45 ids[c] = next++;
46 break;
47 }
48 if (bits[at * 3] === x && bits[at * 3 + 1] === y && bits[at * 3 + 2] === z) {
49 ids[c] = ids[at]!;
50 break;
51 }
52 h = (h + 1) & (size - 1);
53 }
54 }
55 return ids;
56 }
57
outdated

Math.abs hides an inward-wound mesh, and the closed check ignores winding, so a mixed-winding mesh can report a meaningless volume as if it were true. Either detect inconsistent winding (each edge traversed once in each direction) and say so, or state the limit in the user-facing text.

58 export function measureSolid(positions: Float32Array): SolidMeasure {
59 const triangles = Math.floor(positions.length / 9);
60 const ids = vertexIds(positions, triangles * 3);
61 // Per undirected edge: how many triangles use it, and the net direction they walk it (+1
62 // low→high).
63 const uses = new Map<number, number>();
64 const net = new Map<number, number>();
65 let six = 0;
66 let twice = 0;
67 for (let t = 0; t < triangles; t++) {
68 const o = t * 9;
69 const ax = positions[o]!, ay = positions[o + 1]!, az = positions[o + 2]!;
70 const bx = positions[o + 3]!, by = positions[o + 4]!, bz = positions[o + 5]!;
71 const cx = positions[o + 6]!, cy = positions[o + 7]!, cz = positions[o + 8]!;
72 six += ax * (by * cz - bz * cy) + ay * (bz * cx - bx * cz) + az * (bx * cy - by * cx);
73 const ux = bx - ax, uy = by - ay, uz = bz - az;
74 const vx = cx - ax, vy = cy - ay, vz = cz - az;
75 twice += Math.hypot(uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx);
76 for (let e = 0; e < 3; e++) {
77 const p = ids[t * 3 + e]!;
78 const q = ids[t * 3 + ((e + 1) % 3)]!;
79 const key = Math.min(p, q) * 0x4000000 + Math.max(p, q);
80 uses.set(key, (uses.get(key) ?? 0) + 1);
81 net.set(key, (net.get(key) ?? 0) + (p < q ? 1 : -1));
82 }
83 }
84 let closed = triangles > 0;
85 for (const n of uses.values()) if (n !== 2) { closed = false; break; }
86 let consistent = closed;
87 if (closed) for (const n of net.values()) if (n !== 0) { consistent = false; break; }
88 return { volume: six / 6, area: twice / 2, closed, consistent };
89 }
90
91 const round = (v: number): string => String(Math.round(v * 100) / 100);
92
93 /**
94 * `8000 units³`; `open mesh` or `mixed winding` when there is no volume to state. A closed mesh
95 * wound all inward reads as its magnitude (the part is inside out, its size is the same).
96 */
97 export function volumeText(m: SolidMeasure, unit = "units"): string {
98 if (!m.closed) return "open mesh";
99 if (!m.consistent) return "mixed winding, no volume";
100 return `${round(Math.abs(m.volume))} ${unit}³`;
101 }
102
103 /** `2400 units²`. */
104 export function areaText(m: SolidMeasure, unit = "units"): string {
105 return `${round(m.area)} ${unit}²`;
106 }
src/web/render/model-facts.ts +13 −6
@@ -12,7 +12,8 @@
1212
1313 import { inflateRawSync } from "node:zlib";
1414 import { kindByName } from "./kinds.ts";
15 import { bounds, parseObj, parseStl, sizeText, type Mesh } from "./mesh.ts";
15 import { bounds, parseObj, sizeText, type Mesh } from "./mesh.ts";
16 import { readStl } from "./stl.ts";
1617 import { daeFromText } from "./collada.ts";
1718 import { parsePly } from "./ply.ts";
1819 import { INFLATE_LIMIT, locateModel, parseModelXml } from "./threemf.ts";
@@ -25,6 +26,10 @@ interface Facts {
2526 readonly size: readonly [number, number, number];
2627 /** For an indexed format: the words about its vertices and faces. */
2728 readonly indexed?: string;
29 /** For an STL: `Volume … · Area …`, in the file's own units. */
30 readonly solid?: string;
31 /** The unit word of `size` and of the solid; an STL names none, so it reads `units`. */
32 readonly unit?: string;
2833 }
2934
3035 const extension = (path: string): string => path.slice(path.lastIndexOf(".") + 1).toLowerCase();
@@ -35,7 +40,7 @@ export const isModelPath = (path: string): boolean => kindByName(path) === "mode
3540 /** What a model is: `3D model · STL`, then what its bytes say. */
3641 export interface ModelFacts {
3742 readonly title: string;
38 /** `12 triangles · 20 × 20 × 20 mm`, its size over the cap, or why not. */
43 /** `12 triangles · 20 × 20 × 20 mm` (`units` for an STL), its size over the cap, or why not. */
3944 readonly facts: string;
4045 }
4146
@@ -54,8 +59,8 @@ export function modelFacts(path: string, bytes: Uint8Array | null, size: number)
5459 return { title, facts: `not a readable ${format} file` };
5560 }
5661 const count = `${facts.triangles.toLocaleString("en")} triangle${facts.triangles === 1 ? "" : "s"}`;
57 const tail = facts.indexed === undefined ? "" : ` · ${facts.indexed}`;
58 return { title, facts: `${count} · ${sizeText(facts.size)}${tail}` };
62 const tail = facts.indexed !== undefined ? ` · ${facts.indexed}` : facts.solid !== undefined ? ` · ${facts.solid}` : "";
63 return { title, facts: `${count} · ${sizeText(facts.size, facts.unit)}${tail}` };
5964 }
6065
6166 function read(ext: string, bytes: Uint8Array): Facts {
@@ -67,8 +72,10 @@ function read(ext: string, bytes: Uint8Array): Facts {
6772 return { triangles: mesh.triangles, size: bounds(mesh.positions).size };
6873 }
6974 if (ext === "stl") {
70 const mesh = parseStl(bytes);
71 return { triangles: mesh.triangles, size: bounds(mesh.positions).size };
75 // One read, one measure: `readStl` parses, checks and measures.
76 const stl = readStl(bytes);
77 if ("error" in stl) throw new Error(stl.error);
78 return { triangles: stl.triangles, size: stl.box.size, unit: "units", solid: `Volume ${stl.volume} · Area ${stl.area}` };
outdated

The STL is measured here and again in readStl. Compute it once. The terminal's mm size next to units³ is also inconsistent: pick one unit word.

7279 }
7380 if (ext === "obj" || ext === "ply" || ext === "dae") return indexedFacts(indexedParse(ext, bytes));
7481 return gltfFacts(ext === "glb" ? glbJson(bytes) : new TextDecoder().decode(bytes));
src/web/render/model3d.ts +1
@@ -84,6 +84,7 @@ export function model3d(input: RenderInput): Rendered {
8484 ${formatOf(input.path) === "obj" ? row("groups", "Groups", rows?.groups) : html``}
8585 ${row("triangles", "Triangles", rows?.triangles ?? stlFacts?.triangles.toLocaleString("en"))}
8686 ${row("box", "Box", rows?.box ?? stlFacts?.size)}
87 ${stlFacts === undefined ? html`` : html`${row("volume", "Volume", stlFacts.volume)}${row("area", "Area", stlFacts.area)}`}
outdated

Principles 7 and 2: hand-rolled markup with data-* hooks instead of the row() helper used by the lines above. Use row("volume", "Volume", stlFacts?.volume) and row("area", "Area", stlFacts?.area). Also add a render test that asserts these rows.

8788 </dl>
8889 <span class="muted" data-stats aria-live="polite"></span>
8990 <span class="spacer"></span>
src/web/render/stl.ts +9 −1
@@ -6,6 +6,7 @@
66 * viewer shares.
77 */
88
9 import { areaText, measureSolid, volumeText, type SolidMeasure } from "./mesh_measure_solid.ts";
910 import { bounds, MeshError, parseStl, sizeText, type Bounds } from "./mesh.ts";
1011
1112 /** The largest STL read or drawn: 20 MB. */
@@ -18,6 +19,12 @@ export interface StlFacts {
1819 readonly box: Bounds;
1920 /** `20 × 20 × 20`: the file's own units, which an STL does not name. */
2021 readonly size: string;
22 /** `8000 units³`, or `open mesh`. */
23 readonly volume: string;
24 /** `2400 units²`. */
25 readonly area: string;
26 /** The same measure, for words that are not the page's. */
27 readonly solid: SolidMeasure;
2128 }
2229
2330 /** The facts of an STL, or the sentence that says why they cannot be had. */
@@ -41,7 +48,8 @@ export function readStl(bytes: Uint8Array): StlFacts | { readonly error: string
4148 if (mesh.triangles === 0) return { error: "This STL holds no triangles." };
4249 for (const v of mesh.positions) if (!Number.isFinite(v)) return { error: "This STL holds a coordinate that is not a number." };
4350 const box = bounds(mesh.positions);
44 return { triangles: mesh.triangles, box, size: sizeText(box.size, "units") };
51 const solid = measureSolid(mesh.positions);
52 return { triangles: mesh.triangles, box, size: sizeText(box.size, "units"), volume: volumeText(solid), area: areaText(solid), solid };
4553 } catch (error) {
4654 return { error: `This is not a readable STL file${error instanceof MeshError ? `: ${error.message}` : ""}.` };
4755 }
test/mesh-solid.test.ts added +89
@@ -0,0 +1,89 @@
1 import { describe, expect, test } from "bun:test";
2 import { join } from "node:path";
3 import { areaText, measureSolid, volumeText } from "../src/web/render/mesh_measure_solid.ts";
4 import { parseStl } from "../src/web/render/mesh.ts";
5 import { readStl } from "../src/web/render/stl.ts";
6 import { modelFacts } from "../src/web/render/model-facts.ts";
7
8 /** Corners of each face, wound outward. */
9 const soup = (faces: number[][][]): Float32Array => Float32Array.from(faces.flat(2));
10
11 // Unit cube, 12 outward triangles.
12 const cube = soup([
13 [[0,0,0],[0,1,0],[1,1,0]], [[0,0,0],[1,1,0],[1,0,0]],
14 [[0,0,1],[1,0,1],[1,1,1]], [[0,0,1],[1,1,1],[0,1,1]],
15 [[0,0,0],[1,0,0],[1,0,1]], [[0,0,0],[1,0,1],[0,0,1]],
16 [[0,1,0],[0,1,1],[1,1,1]], [[0,1,0],[1,1,1],[1,1,0]],
17 [[0,0,0],[0,0,1],[0,1,1]], [[0,0,0],[0,1,1],[0,1,0]],
18 [[1,0,0],[1,1,0],[1,1,1]], [[1,0,0],[1,1,1],[1,0,1]],
19 ]);
20
21 // Corner tetrahedron with legs 3: V = 3·3·3/6 = 4.5; A = 3 · (9/2) + (√3/4)(3√2)² = 13.5 + 9√3/2.
22 const O = [0,0,0], X = [3,0,0], Y = [0,3,0], Z = [0,0,3];
23 const tetra = soup([[O, Y, X], [O, X, Z], [O, Z, Y], [X, Y, Z]]);
24
25 describe("volume and surface area of a mesh", () => {
26 test("a unit cube is 1 and 6", () => {
27 const m = measureSolid(cube);
28 expect(m.closed).toBe(true);
29 expect(m.volume).toBeCloseTo(1, 12);
30 expect(m.area).toBeCloseTo(6, 12);
31 expect(volumeText(m)).toBe("1 units³");
32 expect(areaText(m)).toBe("6 units²");
33 });
34
35 test("a tetrahedron matches the hand calculation", () => {
36 const m = measureSolid(tetra);
37 expect(m.closed).toBe(true);
38 expect(m.volume).toBeCloseTo(4.5, 10);
39 expect(m.area).toBeCloseTo(13.5 + (9 * Math.sqrt(3)) / 2, 5);
40 });
41
42 test("inward winding gives a negative signed volume", () => {
43 const flipped = Float32Array.from(cube);
44 for (let t = 0; t < 12; t++) for (let i = 0; i < 3; i++) {
45 const a = t * 9 + 3 + i, b = t * 9 + 6 + i;
46 [flipped[a], flipped[b]] = [flipped[b]!, flipped[a]!];
47 }
48 expect(measureSolid(flipped).volume).toBeCloseTo(-1, 12);
49 });
50
51 test("a closed mesh with one face flipped has no volume to state", () => {
52 const mixed = Float32Array.from(cube);
53 for (let i = 0; i < 3; i++) [mixed[3 + i], mixed[6 + i]] = [mixed[6 + i]!, mixed[3 + i]!];
54 const m = measureSolid(mixed);
55 expect(m.closed).toBe(true);
56 expect(m.consistent).toBe(false);
57 expect(volumeText(m)).toBe("mixed winding, no volume");
58 expect(measureSolid(cube).consistent).toBe(true);
59 });
60
61 test("an inside-out cube reads as its size", () => {
62 const flipped = Float32Array.from(cube);
63 for (let t = 0; t < 12; t++) for (let i = 0; i < 3; i++) {
64 const a = t * 9 + 3 + i, b = t * 9 + 6 + i;
65 [flipped[a], flipped[b]] = [flipped[b]!, flipped[a]!];
66 }
67 expect(volumeText(measureSolid(flipped))).toBe("1 units³");
68 });
69
70 test("an open mesh says so", () => {
71 const m = measureSolid(cube.subarray(0, 11 * 9));
72 expect(m.closed).toBe(false);
73 expect(volumeText(m)).toBe("open mesh");
74 expect(areaText(m)).toBe("5.5 units²");
75 expect(measureSolid(new Float32Array(0)).closed).toBe(false);
76 });
77 });
78
79 describe("where it is shown", () => {
80 test("the page's STL facts and the terminal line carry both", async () => {
81 const bytes = await Bun.file(join(import.meta.dir, "fixtures", "model3d", "cube-binary.stl")).bytes();
82 const facts = readStl(bytes);
83 if ("error" in facts) throw new Error(facts.error);
84 expect(facts.volume).toBe("8000 units³");
85 expect(facts.area).toBe("2400 units²");
86 expect(modelFacts("cube.stl", bytes, bytes.length).facts).toContain("20 × 20 × 20 units · Volume 8000 units³ · Area 2400 units²");
87 expect(parseStl(bytes).triangles).toBe(12);
88 });
89 });
test/model3d.test.ts +2 −2
@@ -158,10 +158,10 @@ describe("what a glTF may make the browser fetch", () => {
158158 });
159159
160160 describe("a model in words, for the terminal", () => {
161 test("STL in either form and OBJ: the format, the triangles and the box in mm", async () => {
161 test("STL in either form and OBJ: the format, the triangles and the box (units for STL, mm for OBJ)", async () => {
162162 for (const name of ["cube-ascii.stl", "cube-binary.stl"]) {
163163 const bytes = await fixture(name);
164 expect(modelLine(modelFacts(name, bytes, bytes.length))).toBe("3D model · STL · 12 triangles · 20 × 20 × 20 mm");
164 expect(modelLine(modelFacts(name, bytes, bytes.length))).toBe("3D model · STL · 12 triangles · 20 × 20 × 20 units · Volume 8000 units³ · Area 2400 units²");
165165 }
166166 const obj = await fixture("cube.obj");
167167 expect(modelLine(modelFacts("cube.obj", obj, obj.length))).toBe("3D model · OBJ · 12 triangles · 20 × 20 × 20 mm · 8 vertices · 6 faces");
test/render-stl.test.ts +19
@@ -52,6 +52,25 @@ describe("the first paint", () => {
5252 expect(text).not.toContain("<b>");
5353 });
5454
55 test("Volume and Area are dl rows beside Box; an open mesh says so", async () => {
56 const body = await fixture("cube-binary.stl");
57 const text = model3d(input("a.stl", body.length, body)).content.text;
58 expect(text).toContain("<div data-volume><dt>Volume</dt><dd>8000 units³</dd></div>");
59 expect(text).toContain("<div data-area><dt>Area</dt><dd>2400 units²</dd></div>");
60 // Drop the last facet: 11 triangles, an open mesh with no volume, but still an area.
61 const open = body.slice(0, body.length - 50);
62 new DataView(open.buffer).setUint32(80, 11, true);
63 const openText = model3d(input("a.stl", open.length, open)).content.text;
64 expect(openText).toContain("<div data-volume><dt>Volume</dt><dd>open mesh</dd></div>");
65 expect(openText).toMatch(/<div data-area><dt>Area<\/dt><dd>[\d.]+ units²<\/dd><\/div>/);
66 });
67
68 test("a file that is not read shows no Volume or Area row", () => {
69 const text = model3d(input("a.stl", 10, new Uint8Array(10))).content.text;
70 expect(text).not.toContain("<dt>Volume</dt>");
71 expect(text).not.toContain("<dt>Area</dt>");
72 });
73
5574 test("a 3 MB file, past the old 2 MB cap, still has its facts in the first paint", () => {
5675 const n = 60_000;
5776 const body = new Uint8Array(84 + n * 50);
test/tui-model3d.test.ts +1 −1
@@ -67,7 +67,7 @@ test("a binary STL reads as a 3D model with its triangles, its box and where to
6767 await settleUntil(app, "12 triangles");
6868 const text = app.screen.toText();
6969 expect(text).toContain("3D model · STL");
70 expect(text).toContain("12 triangles · 20 × 20 × 20 mm");
70 expect(text).toContain("12 triangles · 20 × 20 × 20 units");
7171 expect(text).toContain("Download: https://forge.test/alice/tower/media/main/parts/cube.stl?download=1");
7272 expect(text).not.toContain("Binary file");
7373 } finally {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs