Public: anyone can read this; the crew can change it.
A .obj mesh opens in the 3D viewer with its vertex and face counts #14095
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14062-a-obj-mesh-opens-in-the-3d-viewer-with-i → main 5 commits fork 4 threads · 4 unresolved
docs/features/mesh-files.md +6 −3
| @@ -1,23 +1,26 @@ | ||
| 1 | 1 | # Open an .obj or .ply file |
| 2 | 2 | |
| 3 | 3 | A `.obj` or `.ply` file in the code browser opens in the 3D viewer, the same one an `.stl` uses. Beside the view the |
| 4 | facts list **Vertices**, **Faces**, **Triangles** and the **Box** (its size in the file's own units, shown as mm). | |
| 4 | facts list **Vertices**, **Faces**, (for an `.obj`) **Groups**, **Triangles** and the **Box** (its size in the file's own units, shown as mm). | |
| 5 | 5 | The first paint carries them: the server reads the file (up to 2 MB) and renders the rows, so they show with |
| 6 | 6 | JavaScript off. For a larger file the viewer fills them in once it has fetched and read it. |
| 7 | 7 | |
| 8 | 8 | - **Vertices** are the points the file lists; **Faces** are the polygons, before they are cut into triangles. |
| 9 | - **Groups** are the distinct named objects and groups (`o`, `g` lines) in an OBJ; a repeated or empty name counts once or not at all. | |
| 9 | 10 | - **Dropped faces**: a face that names a vertex the file does not have is left out and counted, as |
| 10 | 11 | `6 (1 face dropped)`. |
| 11 | 12 | - **Over the cap**: a part of more than 5,000,000 triangles is counted but not drawn. The facts stay, and the view |
| 12 | 13 | says "This part has more triangles than can be drawn here; download it to open it elsewhere." with a Download button. |
| 13 | 14 | - **Not readable**: a truncated file, a big-endian PLY, or a header that claims more than the bytes hold is refused |
| 14 | 15 | with a plain note and Download; nothing is partly drawn. Reading never spends time on a claimed count, only on bytes. |
| 16 | - **OBJ falls back to source**: an OBJ over 20 MB, or one that is not readable (a vertex that is not three numbers, bytes that are not text), is shown as source with one sentence, | |
| 17 | and the viewer says the same sentence for a large file it fetched itself (`OBJ_TOO_BIG`, `OBJ_BROKEN` in `src/web/render/obj.ts`). | |
| 15 | 18 | - PLY: ASCII and binary little-endian; only `vertex` (x, y, z) and `face` (`vertex_indices`) are read. |
| 16 | 19 | |
| 17 | 20 | The terminal (both doors): the workspace screen's file view shows the same file as |
| 18 | `3D model · OBJ` over `12 triangles · 1 × 1 × 1 mm · 8 vertices · 6 faces`, and `not a readable PLY file` for one it cannot read. | |
| 21 | `3D model · OBJ` over `12 triangles · 1 × 1 × 1 mm · 8 vertices · 6 faces · 2 groups` (groups only when an OBJ names some), and `not a readable PLY file` for one it cannot read. | |
| 19 | 22 | The facts come from the same parsers as the page (`src/web/render/model-facts.ts`). |
| 20 | 23 | |
| 21 | 24 | Try it: commit `part.obj` or `part.ply` to a repository and open it under Code. |
| 22 | 25 | |
| 23 | Pinned by `test/render-obj-ply.test.ts`. | |
| 26 | Pinned by `test/render-obj-ply.test.ts` and `test/render-obj.test.ts`. |
src/web/render/mesh.ts +12 −4
| @@ -16,6 +16,8 @@ export interface Mesh { | ||
| 16 | 16 | readonly vertices?: number; |
| 17 | 17 | /** Faces kept, before they were cut into triangles. */ |
| 18 | 18 | readonly faces?: number; |
| 19 | /** Named objects and groups (`o`, `g`) in an OBJ; unset for other formats. */ | |
| 20 | readonly groups?: number; | |
| 19 | 21 | /** Faces dropped because they name a vertex that is not there. */ |
| 20 | 22 | readonly dropped?: number; |
| 21 | 23 | /** More triangles than `TRIANGLE_LIMIT`: counted, but `positions` is empty. */ |
| @@ -133,14 +135,19 @@ export function soupBuilder(vertices: number[], limit = TRIANGLE_LIMIT): { | ||
| 133 | 135 | /** |
| 134 | 136 | * Wavefront OBJ: `v` lines and `f` lines; a face of more than three corners |
| 135 | 137 | * is a fan. Indices are 1-based, and a negative one counts back from the last |
| 136 | * vertex read. Normals, texture coordinates, groups and materials are skipped. | |
| 138 | * vertex read. Named objects and groups (`o`, `g`) are counted; normals, | |
| 139 | * texture coordinates and materials are skipped. | |
| 137 | 140 | */ |
| 138 | 141 | export function parseObj(text: string, limit = TRIANGLE_LIMIT): Mesh { |
| 139 | 142 | const vertices: number[] = []; |
| 140 | 143 | const soup = soupBuilder(vertices, limit); |
| 144 | const groups = new Set<string>(); | |
| 141 | 145 | for (const line of text.split("\n")) { |
| 142 | 146 | const parts = line.trim().split(/\s+/); |
| 143 | if (parts[0] === "v") { | |
| 147 | if (parts[0] === "o" || parts[0] === "g") { | |
| 148 | const name = parts.slice(1).join(" "); | |
| 149 | if (name !== "") groups.add(`${parts[0]} ${name}`); | |
| 150 | } else if (parts[0] === "v") { | |
| 144 | 151 | const [x, y, z] = [Number(parts[1]), Number(parts[2]), Number(parts[3])]; |
| 145 | 152 | if (![x, y, z].every(Number.isFinite)) throw new MeshError("a vertex that is not three numbers"); |
| 146 | 153 | vertices.push(x, y, z); |
| @@ -155,7 +162,7 @@ export function parseObj(text: string, limit = TRIANGLE_LIMIT): Mesh { | ||
| 155 | 162 | ); |
| 156 | 163 | } |
| 157 | 164 | } |
| 158 | return soup.done(); | |
| 165 | return { ...soup.done(), groups: groups.size }; | |
| 159 | 166 | } |
| 160 | 167 | |
| 161 | 168 | /** The axis-aligned box around every corner; all zeros for an empty mesh. */ |
| @@ -189,11 +196,12 @@ function count(v: number, one: string, many: string): string { | ||
| 189 | 196 | * The words for an indexed mesh's rows, shared by the page's first paint, the viewer and the |
| 190 | 197 | * terminal. |
| 191 | 198 | */ |
| 192 | export function indexedRows(mesh: Mesh): { vertices: string; faces: string; triangles: string; box: string } { | |
| 199 | export function indexedRows(mesh: Mesh): { vertices: string; faces: string; groups?: string; triangles: string; box: string } { | |
| 193 | 200 | const dropped = mesh.dropped ? ` (${count(mesh.dropped, "face", "faces")} dropped)` : ""; |
| 194 | 201 | return { |
| 195 | 202 | vertices: (mesh.vertices ?? 0).toLocaleString("en"), |
| 196 | 203 | faces: `${(mesh.faces ?? 0).toLocaleString("en")}${dropped}`, |
| 204 | ...(mesh.groups === undefined ? {} : { groups: mesh.groups.toLocaleString("en") }), | |
| 197 | 205 | triangles: mesh.triangles.toLocaleString("en"), |
| 198 | 206 | box: sizeText((mesh.box ?? bounds(mesh.positions)).size), |
| 199 | 207 | }; |
src/web/render/model-facts.ts +2 −1
| @@ -77,7 +77,8 @@ function read(ext: string, bytes: Uint8Array): Facts { | ||
| 77 | 77 | export function indexedWords(mesh: Mesh): string { |
| 78 | 78 | const n = (v: number, one: string, many: string): string => `${v.toLocaleString("en")} ${v === 1 ? one : many}`; |
| 79 | 79 | const dropped = mesh.dropped ? ` (${n(mesh.dropped, "face", "faces")} dropped)` : ""; |
| 80 | return `${n(mesh.vertices ?? 0, "vertex", "vertices")} · ${n(mesh.faces ?? 0, "face", "faces")}${dropped}`; | |
| 80 | const groups = !mesh.groups ? "" : ` · ${n(mesh.groups, "group", "groups")}`; | |
| 81 | return `${n(mesh.vertices ?? 0, "vertex", "vertices")} · ${n(mesh.faces ?? 0, "face", "faces")}${dropped}${groups}`; | |
| 81 | 82 | } |
| 82 | 83 | |
| 83 | 84 | /** |
src/web/render/model3d-client.ts +8 −3
| @@ -36,7 +36,8 @@ import { OrbitControls } from "three/addons/controls/OrbitControls.js"; | ||
| 36 | 36 | import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; |
| 37 | 37 | import { REFUSED_URI, withinModelDir } from "./gltf-uri.ts"; |
| 38 | 38 | import { parse3mf } from "./threemf.ts"; |
| 39 | import { bounds, indexedRows, OVER_CAP_NOTE, parseObj, parseStl, sizeText, type Bounds, type Mesh as Parsed } from "./mesh.ts"; | |
| 39 | import { ObjFallback, objFromText } from "./obj.ts"; | |
| 40 | import { bounds, indexedRows, OVER_CAP_NOTE, parseStl, sizeText, type Bounds, type Mesh as Parsed } from "./mesh.ts"; | |
| 40 | 41 | import { parsePly } from "./ply.ts"; |
| 41 | 42 | |
| 42 | 43 | /** |
| @@ -102,7 +103,7 @@ async function load(src: string, format: string): Promise<Loaded> { | ||
| 102 | 103 | if (format === "stl" || format === "obj" || format === "ply" || format === "3mf") { |
| 103 | 104 | const parsed: Parsed = |
| 104 | 105 | format === "obj" |
| 105 | ? parseObj(await response.text()) | |
| 106 | ? objFromText(await response.text()) | |
| 106 | 107 | : format === "3mf" |
| 107 | 108 | ? await parse3mf(new Uint8Array(await response.arrayBuffer())) |
| 108 | 109 | : format === "ply" |
| @@ -196,6 +197,7 @@ function mount(figure: Element): void { | ||
| 196 | 197 | if (rows !== undefined) { |
| 197 | 198 | fact("[data-vertices]", rows.vertices); |
| 198 | 199 | fact("[data-faces]", rows.faces); |
outdated
The viewer only gains the Groups fact. A big OBJ the page did not read is parsed here, and a malformed or over-cap one needs the same one-sentence source fallback (OBJ_BROKEN / OBJ_TOO_BIG) the page gives small files, or box 3 is only half met. Add a test for it. |
||
| 200 | if (rows.groups !== undefined) fact("[data-groups]", rows.groups); | |
| 199 | 201 | } |
| 200 | 202 | if (overCap) { |
| 201 | 203 | // Counted, not drawn: the facts stay, the note and Download with them. |
| @@ -291,7 +293,10 @@ function mount(figure: Element): void { | ||
| 291 | 293 | (error: unknown) => { |
| 292 | 294 | renderer.dispose(); |
| 293 | 295 | if (note !== null) note.hidden = false; |
| 294 | stats.textContent = `Could not draw this file: ${error instanceof Error ? error.message : String(error)}`; | |
| 296 | stats.textContent = | |
| 297 | error instanceof ObjFallback | |
| 298 | ? error.message | |
| 299 | : `Could not draw this file: ${error instanceof Error ? error.message : String(error)}`; | |
| 295 | 300 | }, |
| 296 | 301 | ); |
| 297 | 302 | } |
src/web/render/model3d.ts +5 −1
| @@ -23,6 +23,7 @@ import type { BuiltAsset } from "../asset.ts"; | ||
| 23 | 23 | import { html, type Html } from "../html.ts"; |
| 24 | 24 | import { btn, empty, fileSize } from "../ui.ts"; |
| 25 | 25 | import { indexedRows } from "./mesh.ts"; |
| 26 | import { readObj } from "./obj.ts"; | |
| 26 | 27 | import { indexedMesh } from "./model-facts.ts"; |
| 27 | 28 | import { readStl, STL_LIMIT, STL_TOO_BIG } from "./stl.ts"; |
| 28 | 29 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| @@ -44,7 +45,9 @@ export function model3d(input: RenderInput): Rendered { | ||
| 44 | 45 | btn(label, { type: "button", size: "sm", variant: "outline", extra: "js-only", pressed: false, value }); |
| 45 | 46 | // An OBJ or PLY the page read has its counts in the first paint; the viewer |
| 46 | 47 | // fills the same rows for a file it fetched itself. |
| 47 | const mesh = indexedMesh(input.path, input.body, input.size); | |
| 48 | const obj = readObj(input.path, input.body, input.size); | |
readObj parses the whole body, then indexedMesh on the next line parses it again. Parse once and share the mesh. |
||
| 49 | if (obj !== null && "fallback" in obj) return { lines: 0, content: html``, fallback: obj.fallback }; | |
| 50 | const mesh = obj !== null ? (obj.mesh ?? null) : indexedMesh(input.path, input.body, input.size); | |
| 48 | 51 | const rows = mesh === null ? undefined : indexedRows(mesh); |
| 49 | 52 | const row = (key: string, label: string, value: string | undefined): Html => |
| 50 | 53 | value === undefined |
| @@ -77,6 +80,7 @@ export function model3d(input: RenderInput): Rendered { | ||
| 77 | 80 | <div><dt>File</dt><dd>${fileSize(input.size)}</dd></div> |
| 78 | 81 | ${row("vertices", "Vertices", rows?.vertices)} |
| 79 | 82 | ${row("faces", "Faces", rows?.faces)} |
| 83 | ${formatOf(input.path) === "obj" ? row("groups", "Groups", rows?.groups) : html``} | |
| 80 | 84 | ${row("triangles", "Triangles", rows?.triangles ?? stlFacts?.triangles.toLocaleString("en"))} |
| 81 | 85 | ${row("box", "Box", rows?.box ?? stlFacts?.size)} |
| 82 | 86 | </dl> |
src/web/render/obj.ts added +46
| @@ -0,0 +1,46 @@ | ||
| 1 | /** | |
| 2 | * An OBJ the viewer will open, or the one sentence for why it shows as source. | |
| 3 | * The counts come from `mesh.ts`'s `parseObj`, the parser the browser runs | |
| 4 | * too; this module only decides, at the page, whether the file is drawn. | |
| 5 | */ | |
| 6 | ||
| 7 | import { parseObj, type Mesh } from "./mesh.ts"; | |
| 8 | ||
| 9 | /** An OBJ over this is not drawn: the page offers the source and Download. */ | |
| 10 | export const OBJ_LIMIT = 20_000_000; | |
| 11 | ||
| 12 | /** The page reads a body this small itself; a bigger one is the viewer's to fetch. */ | |
| 13 | const PAGE_READ_CAP = 2_000_000; | |
| 14 | ||
| 15 | export const OBJ_TOO_BIG = "This OBJ is over 20 MB, so it is shown as source; Download opens it elsewhere."; | |
| 16 | export const OBJ_BROKEN = "This file is not a readable OBJ mesh, so it is shown as source."; | |
| 17 | ||
| 18 | const isObj = (path: string): boolean => path.toLowerCase().endsWith(".obj"); | |
| 19 | ||
| 20 | /** An OBJ that is not drawn, with the one sentence that says why. */ | |
| 21 | export class ObjFallback extends Error {} | |
| 22 | ||
| 23 | /** The mesh of an OBJ's text; an ObjFallback with its sentence when it is too big or not an OBJ. */ | |
| 24 | export function objFromText(text: string): Mesh { | |
| 25 | if (text.length > OBJ_LIMIT) throw new ObjFallback(OBJ_TOO_BIG); | |
| 26 | try { | |
| 27 | return parseObj(text); | |
| 28 | } catch { | |
| 29 | throw new ObjFallback(OBJ_BROKEN); | |
| 30 | } | |
| 31 | } | |
| 32 | ||
| 33 | /** | |
| 34 | * Null for a file that is not an OBJ. Over the cap or unreadable: the reason it shows as source. | |
| 35 | * Otherwise its mesh, or none when the page did not read the body (the viewer parses it). | |
| 36 | */ | |
| 37 | export function readObj(path: string, body: Uint8Array, size: number): { fallback: string } | { mesh?: Mesh } | null { | |
| 38 | if (!isObj(path)) return null; | |
| 39 | if (size > OBJ_LIMIT) return { fallback: OBJ_TOO_BIG }; | |
| 40 | if (body.length === 0 || size > PAGE_READ_CAP) return {}; | |
| 41 | try { | |
| 42 | return { mesh: objFromText(new TextDecoder("utf-8", { fatal: true }).decode(body)) }; | |
| 43 | } catch { | |
| 44 | return { fallback: OBJ_BROKEN }; | |
| 45 | } | |
| 46 | } |
test/render-obj.test.ts added +87
| @@ -0,0 +1,87 @@ | ||
| 1 | /** An OBJ opens in the 3D frame with its counts, or falls back to source with one sentence. */ | |
| 2 | ||
| 3 | import { describe, expect, test } from "bun:test"; | |
| 4 | import { indexedRows, parseObj } from "../src/web/render/mesh.ts"; | |
| 5 | import { model3d } from "../src/web/render/model3d.ts"; | |
| 6 | import { indexedWords, modelFacts } from "../src/web/render/model-facts.ts"; | |
| 7 | import { OBJ_BROKEN, OBJ_LIMIT, OBJ_TOO_BIG, ObjFallback, objFromText, readObj } from "../src/web/render/obj.ts"; | |
| 8 | ||
| 9 | const enc = (s: string): Uint8Array => new TextEncoder().encode(s); | |
| 10 | const CUBE = | |
| 11 | "o cube\ng top\n" + | |
| 12 | "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv 0 0 1\nv 1 0 1\nv 1 1 1\nv 0 1 1\n" + | |
| 13 | "f 1 4 3 2\nf 5 6 7 8\nf 1 2 6 5\nf 3 4 8 7\nf 2 3 7 6\nf 4 1 5 8\n"; | |
| 14 | ||
| 15 | const input = (path: string, body: Uint8Array, size = body.length) => ({ | |
| 16 | path, | |
| 17 | size, | |
| 18 | body, | |
| 19 | media: `/a/b/media/main/${path}`, | |
| 20 | download: `/a/b/media/main/${path}?download=1`, | |
| 21 | }); | |
| 22 | ||
| 23 | describe("a cube", () => { | |
| 24 | test("counts vertices, faces and groups", () => { | |
| 25 | const mesh = parseObj(CUBE); | |
| 26 | expect([mesh.vertices, mesh.faces, mesh.groups]).toEqual([8, 6, 2]); | |
| 27 | expect(indexedRows(mesh).groups).toBe("2"); | |
| 28 | }); | |
| 29 | ||
| 30 | test("the frame shows the three counts in the first paint, above the viewer", () => { | |
| 31 | const out = model3d(input("cube.obj", enc(CUBE))); | |
| 32 | expect(out.fallback).toBeUndefined(); | |
| 33 | const text = out.content.text; | |
| 34 | expect(text).toContain("<div data-vertices><dt>Vertices</dt><dd>8</dd>"); | |
| 35 | expect(text).toContain("<div data-faces><dt>Faces</dt><dd>6</dd>"); | |
| 36 | expect(text).toContain("<div data-groups><dt>Groups</dt><dd>2</dd>"); | |
| 37 | expect(text.indexOf("data-groups")).toBeLessThan(text.indexOf("data-stage")); | |
| 38 | expect(text).toContain('data-format="obj"'); | |
| 39 | }); | |
| 40 | ||
| 41 | test("a file the page did not read still gets a frame with a Groups slot for the viewer", () => { | |
| 42 | const out = model3d(input("big.obj", new Uint8Array(0), 10_000_000)); | |
| 43 | expect(out.fallback).toBeUndefined(); | |
| 44 | expect(out.content.text).toContain("data-groups hidden"); | |
| 45 | }); | |
| 46 | ||
| 47 | test("a PLY has no Groups row", () => { | |
| 48 | expect(model3d(input("a.ply", new Uint8Array(0), 10)).content.text).not.toContain("data-groups"); | |
| 49 | }); | |
| 50 | }); | |
| 51 | ||
| 52 | describe("a file that cannot be drawn shows as source with one sentence", () => { | |
| 53 | test("over the size cap", () => { | |
| 54 | expect(model3d(input("huge.obj", new Uint8Array(0), OBJ_LIMIT + 1)).fallback).toBe(OBJ_TOO_BIG); | |
| 55 | }); | |
| 56 | ||
| 57 | test("hostile: a vertex that is not numbers", () => { | |
| 58 | expect(model3d(input("bad.obj", enc("v 0 0 0\nv nan x 1\nf 1 1 1\n"))).fallback).toBe(OBJ_BROKEN); | |
| 59 | }); | |
| 60 | ||
| 61 | test("hostile: bytes that are not text", () => { | |
| 62 | expect(readObj("bin.obj", new Uint8Array([0xff, 0xfe, 0x00, 0x80]), 4)).toEqual({ fallback: OBJ_BROKEN }); | |
| 63 | }); | |
| 64 | ||
| 65 | test("hostile: faces naming missing vertices are dropped, not fatal", () => { | |
| 66 | const out = model3d(input("x.obj", enc("v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\nf 1 2 9999999999\nf -5 1 2\n"))); | |
| 67 | expect(out.fallback).toBeUndefined(); | |
| 68 | expect(out.content.text).toContain("(2 faces dropped)"); | |
| 69 | }); | |
| 70 | ||
| 71 | test("the viewer's reader gives the same sentences for a large file the page did not read", () => { | |
outdated
Vacuous: group names are never printed, so this passes without any escaping. Test something the change can break. |
||
| 72 | expect(() => objFromText("v 0 0 0\nv x y z\n")).toThrow(OBJ_BROKEN); | |
| 73 | expect(() => objFromText("v 0 0 0\n".repeat(OBJ_LIMIT / 8 + 1))).toThrow(OBJ_TOO_BIG); | |
| 74 | expect(objFromText(CUBE).groups).toBe(2); | |
| 75 | expect(() => objFromText("v a b c")).toThrow(ObjFallback); | |
| 76 | }); | |
| 77 | ||
| 78 | test("a group is counted once however often it recurs, and a nameless one not at all", () => { | |
| 79 | expect(parseObj("g a\ng a\ng\no a\nv 0 0 0\n").groups).toBe(2); | |
| 80 | }); | |
| 81 | }); | |
| 82 | ||
| 83 | test("the terminal's words carry the groups, when there are any", () => { | |
| 84 | expect(indexedWords(parseObj(CUBE))).toBe("8 vertices · 6 faces · 2 groups"); | |
| 85 | expect(modelFacts("c.obj", enc(CUBE), 100).facts).toContain("· 2 groups"); | |
| 86 | expect(indexedWords(parseObj("v 0 0 0\n"))).toBe("1 vertex · 0 faces"); | |
| 87 | }); |
Ungrammatical and over-wrapped comment: 'Normals, texture coordinates, materials are skipped'. Reword it.