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

A point cloud in PCD form is previewed from its header and a sampled scatter #16040

Merged opened this

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

Merged

torque/forge:torque/16022-a-point-cloud-in-pcd-form-is-previewed-f → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/16022-a-point-cloud-in-pcd-form-is-previewed-f was merged into main as e342142.

Review

Sign in to review this change.
16 files changed +907 −2
docs/design/areas/pcd.md added +6
@@ -0,0 +1,6 @@
1 # Point clouds
2
3 The blob page's view of a `.pcd` file (`src/web/render/pcd.ts`, styles in `pcd-css.ts`). It uses the existing tokens (`--fg`), the `status-rows` classes for the header's facts and the `table` for its fields.
4
5 - `.pcd-scatter` — the three projections (x-y, x-z, y-z) in a grid that wraps: one column at 360px, three where the width allows. No script; each is server-drawn SVG.
6 - `.pcd-panel` — one projection as a `figure`: a square SVG that fills its cell at a fixed aspect ratio (its `viewBox` is set on the server, so nothing shifts) and a caption naming the axes and the sample's range on each.
docs/features/file-kinds.md +1
@@ -18,6 +18,7 @@ The forge draws a file on its page when its kind is below and it is within the s
1818 - **SQLite database**, drawn up to 5 MB: `.db`, `.sqlite`, `.sqlite3`
1919 - **Parquet**, drawn up to 5 MB: `.parquet`
2020 - **Packet capture**, drawn up to 5 MB: `.pcap`, `.pcapng`, `.cap`
21 - **Point cloud (PCD)**, drawn up to 5 MB: `.pcd`
2122 - **3D model**, drawn up to 100 MB: `.stl`, `.3mf`, `.ply`, `.glb`, `.gltf`, `.obj`, `.dae`
2223 - **Archive**, drawn up to 50 MB: `.zip`, `.tar`, `.tgz`, `.tar.gz`
2324 - **Spreadsheet**, drawn up to 10 MB: `.xlsx`
docs/features/pcd.md added +17
@@ -0,0 +1,17 @@
1 ---
2 topic: Files in the browser
3 row: Point clouds (.pcd) as their header and a sampled scatter
4 ---
5 # Point clouds (.pcd)
6
7 A PCD file (Point Cloud Library, ASCII or binary) opens as its header facts and a scatter of up to 5,000 sampled points.
8
9 - **Page:** the file page shows points, width × height, data format, version, viewpoint, bytes per point, the field table (name, type, size, count) and three server-drawn SVG projections (x-y, x-z, y-z). No script, no library. PCD states no unit, so the page says the axes are in the file's own units; the ranges under each panel are those of the sample.
10 - **Sampling:** every `ceil(points / 5000)`th point; a sampled point with a NaN or infinite coordinate is left out and counted.
11 - **Terminal:** opening a `.pcd` in the workspace (`src/tui/screens/workspace.ts`, `pcdFacts`) shows the same facts, sample ranges and field rows as a table; `s` flips to the source. Same gate as the page.
12 - **MCP:** `read_file` on a `.pcd` carries `about: { kind: "pcd", points, width, height, data, fields, sampled, bounds?, says }`; no new tool.
13 - **Gate:** the name and a `VERSION` line must both say PCD, and the file must be at most 5 MB; past that, or when it does not parse (no x, y, z, a short body, a lying count, `binary_compressed`), the page keeps the source view with one line saying why.
14 - **Hostile input:** header at most 16 KB and 64 fields; a binary body is checked as `points × stride ≤ bytes` before any read; an ASCII body is walked once, bounded by its bytes; every name is escaped.
15 - **Left out:** `binary_compressed` (LZF), colour, normals, rotating the cloud, exact bounds over all points.
16 - **Fixtures:** `test/fixtures/cloud.pcd` (ASCII) and `cloud-compressed.pcd` (`binary_compressed`, which keeps the source view).
17 - **Code:** `src/web/render/pcd.ts`, styles `pcd-css.ts`, kind `pcd` in `kinds.ts`; test `test/pcd-render.test.ts`.
scripts/kinds-guide.ts +1 −1
@@ -10,7 +10,7 @@ export const END = "<!-- file-kinds:end -->";
1010 /** The name a person says for each kind. A new kind without one fails the type check. */
1111 export const NAMES: Readonly<Record<FileKind, string>> = {
1212 image: "Image", svg: "SVG", pdf: "PDF", html: "HTML page", audio: "Audio", video: "Video", csv: "Table (CSV, TSV, JSON lines)",
13 sqlite: "SQLite database", parquet: "Parquet", pcap: "Packet capture", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document",
13 sqlite: "SQLite database", parquet: "Parquet", pcap: "Packet capture", pcd: "Point cloud (PCD)", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document",
1414 slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", xcf: "GIMP", cad: "CAD or 3D source (header facts)", cert: "PEM certificate", sbom: "Bill of materials (CycloneDX, SPDX)", wasm: "WebAssembly module", config: "Config", markdown: "Markdown",
1515 notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive",
1616 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project",
src/http/mcp/tools/read_file.ts +3 −1
@@ -4,13 +4,14 @@ import { isSafeRef, isSafeTreePath } from "../../../git/guard.ts";
44 import { blobForRender, listTree } from "../../../git/read.ts";
55 import { readStl, sayStl, stlSize, TOO_LARGE } from "../../../text/stl.ts";
66 import { checkConfig, configKind, type ConfigKind } from "../../../text/config_check.ts";
7 import { aboutPcd } from "../../../web/render/pcd.ts";
78 import { describeMedia } from "../../../text/mp4.ts";
89 import { readXcf } from "../../../web/render/xcf-read.ts";
910 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1011
1112 export const tool: Tool = {
1213 name: "read_file",
13 doc: "`{ repo, path, ref? }`: a file (utf-8, or base64 for binary) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}",
14 doc: "`{ repo, path, ref? }`: a file (utf-8, or base64 for binary) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}",
1415 description:
1516 "No shell? Read a file or list a directory at a ref (default branch); over 5 MB answers tooLarge.",
1617 inputSchema: {
@@ -72,6 +73,7 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re
7273 const { format, triangles } = stl.value;
7374 return { kind: "stl", format, triangles, size: stlSize(stl.value), says: sayStl(stl.value) };
7475 }
76 if (/\.pcd$/i.test(path)) return aboutPcd(body);
7577 if (/\.xcf$/i.test(path)) return aboutXcf(body);
7678 const media = describeMedia(path, body);
7779 if (media) return media;
src/tui/screens/workspace.ts +6
@@ -66,6 +66,7 @@ import { MAX_COLUMNS, parseCsv, type Table } from "../../text/csv.ts";
6666 import { isNumericColumn, sortRows } from "../../text/csv-sort.ts";
6767 import { parseGeoJson, propertyRows } from "../../web/render/geojson.ts";
6868 import { isKmlPath, kmlTable } from "./kml.ts";
69 import { pcdFacts } from "../../web/render/pcd.ts";
6970 import { gcodeFacts, parseGcode } from "../../web/render/gcode.ts";
7071 import { readStep, stepFacts } from "../../web/render/step.ts";
7172 import { parseOtio } from "../../web/render/otio.ts";
@@ -1181,6 +1182,11 @@ class Tab {
11811182 this.table = typeof made === "string" ? null : made;
11821183 this.fault = typeof made === "string" ? made : "";
11831184 if (this.table !== null) this.grid = layoutTable(this.table);
1185 } else if (fileKind(this.path, source.subarray(0, 4096)) === "pcd") {
1186 const cloud = pcdFacts(source);
1187 this.table = typeof cloud === "string" ? null : { header: ["Fact", "Value"], rows: cloud, more: 0, delimiter: ",", columns: 2 };
1188 this.fault = typeof cloud === "string" ? cloud : "";
1189 if (this.table !== null) this.grid = layoutTable(this.table);
11841190 } else if (isGcodePath(this.path)) {
11851191 this.table = gcodeTable(new TextDecoder().decode(source));
11861192 if (this.table !== null) this.grid = layoutTable(this.table);
src/web/render/kinds.ts +14
@@ -29,6 +29,7 @@ export type FileKind =
2929 | "sqlite"
3030 | "parquet"
3131 | "pcap"
32 | "pcd"
3233 | "model3d"
3334 | "archive"
3435 | "sheet"
@@ -123,6 +124,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
123124 parquet: 5 * MB,
124125 // Packet records are walked by their headers; the page reads the whole body.
125126 pcap: 5 * MB,
127 // Parsed whole for its header and a sample of at most 5,000 points; over it the source is kept.
128 pcd: 5 * MB,
126129 model3d: 100 * MB,
127130 archive: 50 * MB,
128131 sheet: 10 * MB,
@@ -472,6 +475,14 @@ const isPcap = (path: string, head: Uint8Array): boolean =>
472475 bytes(0x4d, 0x3c, 0xb2, 0xa1)(head) ||
473476 bytes(0x0a, 0x0d, 0x0d, 0x0a)(head));
474477
478 /**
479 * A PCD file opens on comment lines and then `VERSION`; a binary body follows its `DATA` line, so
480 * only the header is looked at, and NUL bytes in the head are expected.
481 */
482 const isPcd = (path: string, head: Uint8Array): boolean =>
483 extension(path) === "pcd" &&
484 /^(?:#[^\n]*\n|[ \t\r]*\n)*VERSION[ \t]/i.test(new TextDecoder("latin1").decode(head.subarray(0, 1024)));
485
475486 /** For a caller that has only a name: the kind its extension gives. */
476487 export const NO_BYTES: Uint8Array = new Uint8Array(0);
477488
@@ -558,6 +569,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
558569 if (office !== undefined) return office;
559570 if (isArchive(path, head)) return "archive";
560571 if (isPcap(path, head)) return "pcap";
572 if (isPcd(path, head)) return "pcd";
561573 // A CAD or 3D source is named by its magic as well as its name, and has NULs in its head.
562574 if (binaryFacts(extension(path), head) !== undefined) return "cad";
563575 // A WebAssembly module opens on `\0asm`, a NUL in its head; the name alone never decides.
@@ -619,6 +631,7 @@ export function kindByName(path: string): FileKind {
619631 if (isComposeName(path)) return "compose";
620632 if (ext === "xlsx") return "sheet";
621633 if (ext === "pcap" || ext === "pcapng" || ext === "cap") return "pcap";
634 if (ext === "pcd") return "pcd";
622635 if (ext === "wasm") return "wasm";
623636 if (OFFICE[ext] !== undefined) return OFFICE[ext]!;
624637 if (FACTS_EXTENSIONS.includes(ext)) return "cad";
@@ -730,6 +743,7 @@ const SNIFFED_EXTENSIONS: Readonly<Partial<Record<FileKind, readonly string[]>>>
730743 sheet: ["xlsx"],
731744 archive: ["zip", "tar", "tgz"],
732745 pcap: ["pcap", "pcapng", "cap"],
746 pcd: ["pcd"],
733747 wasm: ["wasm"],
734748 cad: [...FACTS_EXTENSIONS],
735749 prproj: ["prproj"],
src/web/render/pcd-css.ts added +9
@@ -0,0 +1,9 @@
1 /** The point-cloud scatter's styles, apart from `pcd.ts` so `style.ts` imports no renderer. */
2
3 export const pcdCss = /* css */ `
4 @layer content {
5 .pcd-scatter { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr)); gap: var(--gap, 12px); margin: var(--gap, 12px) 0; }
outdated

Principle 3: use the spacing tokens, not literal 12px gap and padding. Also see the principle 6 note in the review body about the per-panel rect.

6 .pcd-panel { margin: 0; }
7 .pcd-panel svg { display: block; width: 100%; height: auto; aspect-ratio: 1; color: var(--fg); }
8 }
9 `;
src/web/render/pcd.ts added +343
@@ -0,0 +1,343 @@
1 /**
2 * A Point Cloud Library `.pcd` file (ASCII or binary) as its header and a scatter of up to
3 * `SAMPLE_CAP` points. Format: https://pointclouds.org/documentation/tutorials/pcd_file_format.html
4 * (PCD v0.7: VERSION, FIELDS, SIZE, TYPE, COUNT, WIDTH, HEIGHT, VIEWPOINT, POINTS, DATA).
5 *
6 * The scatter is three orthogonal projections (x-y, x-z, y-z) drawn as SVG, one `<path>` of
7 * round-capped zero-length strokes per panel: no script, no library. PCD states no unit, so none is
8 * drawn: the page says the axes are in the file's own units. The bounds are those of the sampled
9 * points, and the page says so.
10 *
11 * Bounds, before any loop: the header is at most `HEADER_CAP` bytes and `FIELDS_CAP` fields; the
12 * file is capped by `RENDER_CAP.pcd` before it gets here; a binary body must hold `POINTS * stride`
13 * bytes (checked by multiplication, never by a loop on the count); an ASCII body is walked once,
14 * line by line, at most the bytes it has, and only the sampled lines are split. Reads at most
15 * `SAMPLE_CAP` points. `binary_compressed` (LZF) is not read: the page says so and keeps the
16 * source.
17 */
18
19 import { escapeHtml, html, raw } from "../html.ts";
20 import { fileSize } from "../ui.ts";
21 import { RENDER_CAP } from "./kinds.ts";
22 import type { Rendered, RenderInput } from "./renderers.ts";
23
24 export const SAMPLE_CAP = 5000;
25 export const HEADER_CAP = 16 * 1024;
26 export const FIELDS_CAP = 64;
27
28 /** Thrown with a sentence-sized reason when the file cannot be shown as a point cloud. */
29 export class Unreadable extends Error {}
30
31 export interface PcdField {
32 readonly name: string;
33 readonly type: "F" | "U" | "I";
34 readonly size: number;
35 readonly count: number;
36 }
37 export interface Pcd {
38 readonly version: string;
39 readonly fields: readonly PcdField[];
40 readonly width: number;
41 readonly height: number;
42 /** The points the header declares. */
43 readonly points: number;
44 readonly data: "ascii" | "binary";
45 /** tx ty tz qw qx qy qz. */
46 readonly viewpoint: readonly number[];
47 /** Bytes in one binary point. */
48 readonly stride: number;
49 /**
50 * Sampled points, `[x, y, z]`, at most `SAMPLE_CAP`; points with a NaN or infinite axis are left
51 * out.
52 */
53 readonly sample: readonly (readonly [number, number, number])[];
54 /** Sampled rows that held no finite x, y and z. */
55 readonly skipped: number;
56 /** Min and max of each axis over the sample; undefined when the sample is empty. */
57 readonly bounds?: { readonly min: readonly number[]; readonly max: readonly number[] };
58 }
59
60 const IDENTITY = [0, 0, 0, 1, 0, 0, 0];
61
62 /** A non-negative integer from header text, or undefined. */
63 function count(text: string | undefined): number | undefined {
64 if (text === undefined || !/^\d{1,15}$/.test(text)) return undefined;
65 return Number(text);
66 }
67
68 interface Header {
69 fields: PcdField[];
70 width: number;
71 height: number;
72 points: number;
73 data: "ascii" | "binary";
74 viewpoint: number[];
75 version: string;
76 /** Where the body starts. */
77 at: number;
78 }
79
80 function readHeader(bytes: Uint8Array): Header {
81 const head = new TextDecoder("latin1").decode(bytes.subarray(0, HEADER_CAP));
82 const names: string[] = [];
83 let sizes: number[] = [];
84 let types: string[] = [];
85 let counts: number[] | undefined;
86 let width: number | undefined;
87 let height: number | undefined;
88 let points: number | undefined;
89 let data: string | undefined;
90 let version = "";
91 let viewpoint = IDENTITY;
92 let at = 0;
93 while (data === undefined) {
94 const nl = head.indexOf("\n", at);
95 if (nl < 0) throw new Unreadable("its header does not end with a DATA line");
96 const line = head.slice(at, nl).replace(/\r$/, "").trim();
97 at = nl + 1;
98 if (line === "" || line.startsWith("#")) continue;
99 const w = line.split(/\s+/);
100 const key = w[0]!.toUpperCase();
101 const rest = w.slice(1);
102 if (key === "VERSION") version = (rest[0] ?? "").slice(0, 16);
103 else if (key === "FIELDS" || key === "COLUMNS") {
104 if (rest.length > FIELDS_CAP) throw new Unreadable(`it names more than ${FIELDS_CAP} fields`);
105 names.push(...rest.map((n) => n.slice(0, 64)));
106 } else if (key === "SIZE") sizes = rest.map(Number);
107 else if (key === "TYPE") types = rest;
108 else if (key === "COUNT") counts = rest.map(Number);
109 else if (key === "WIDTH") width = count(rest[0]);
110 else if (key === "HEIGHT") height = count(rest[0]);
111 else if (key === "POINTS") points = count(rest[0]);
112 else if (key === "VIEWPOINT") {
113 const v = rest.map(Number);
114 if (v.length !== 7 || !v.every(Number.isFinite)) throw new Unreadable("its VIEWPOINT is not seven numbers");
115 viewpoint = v;
116 } else if (key === "DATA") data = (rest[0] ?? "").toLowerCase();
117 else throw new Unreadable("its header holds a line this does not know");
118 }
119 if (data === "binary_compressed") throw new Unreadable("its data is LZF-compressed (binary_compressed), which is not read here");
120 if (data !== "ascii" && data !== "binary") throw new Unreadable("its DATA is neither ascii nor binary");
121 if (names.length === 0) throw new Unreadable("it has no FIELDS");
122 if (sizes.length !== names.length || types.length !== names.length)
123 throw new Unreadable("FIELDS, SIZE and TYPE do not name the same number of fields");
124 const cs = counts ?? names.map(() => 1);
125 if (cs.length !== names.length) throw new Unreadable("COUNT does not name every field");
126 const fields: PcdField[] = [];
127 for (let i = 0; i < names.length; i++) {
128 const type = types[i]!.toUpperCase();
129 const size = sizes[i]!;
130 const n = cs[i]!;
131 const ok = type === "F" ? size === 4 || size === 8 : type === "U" || type === "I" ? size === 1 || size === 2 || size === 4 : false;
132 if (!ok) throw new Unreadable(`field ${i + 1} has a type or size that is not read`);
133 if (!Number.isInteger(n) || n < 1 || n > 4096) throw new Unreadable(`field ${i + 1} has a COUNT that is not read`);
134 fields.push({ name: names[i]!, type: type as "F" | "U" | "I", size, count: n });
135 }
136 const w = width ?? (points !== undefined && height === undefined ? points : undefined);
137 const h = height ?? 1;
138 if (w === undefined) throw new Unreadable("it has no WIDTH");
139 const declared = points ?? w * h;
140 if (declared > 2 ** 40) throw new Unreadable("it declares more points than a file can hold");
141 return { fields, width: w, height: h, points: declared, data, viewpoint, version, at: at };
142 }
143
144 function axisSlots(fields: readonly PcdField[]): [number, number, number] {
145 const at: Record<string, number> = {};
146 let n = 0;
147 for (const f of fields) {
148 if (!(f.name in at)) at[f.name] = n;
149 n += f.count;
150 }
151 const pick = (name: string): number => at[name] ?? fail(name);
152 return [pick("x"), pick("y"), pick("z")];
153 }
154
155 function fail(name: string): never {
156 throw new Unreadable(`it has no ${name} field`);
157 }
158
159 /** The cloud as plain data; throws `Unreadable` when it is not a PCD this can show. */
160 export function readPcd(bytes: Uint8Array): Pcd {
161 const h = readHeader(bytes);
162 const [sx, sy, sz] = axisSlots(h.fields);
163 const body = bytes.subarray(h.at);
164 const step = Math.max(1, Math.ceil(h.points / SAMPLE_CAP));
165 const sample: [number, number, number][] = [];
166 let skipped = 0;
167 const take = (x: number, y: number, z: number): void => {
168 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z)) sample.push([x, y, z]);
169 else skipped++;
170 };
171
172 // Where each value of a point starts, in bytes (binary) and its reader.
173 const offsets: number[] = [];
174 let stride = 0;
175 for (const f of h.fields)
176 for (let i = 0; i < f.count; i++) {
177 offsets.push(stride);
178 stride += f.size;
179 }
180 const kinds: PcdField[] = h.fields.flatMap((f) => Array.from({ length: f.count }, () => f));
181
182 if (h.data === "binary") {
183 if (h.points * stride > body.length) throw new Unreadable("the file ends before its header says it should");
184 const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
185 const at = (row: number, slot: number): number => {
186 const f = kinds[slot]!;
187 const o = row * stride + offsets[slot]!;
188 if (f.type === "F") return f.size === 4 ? view.getFloat32(o, true) : view.getFloat64(o, true);
189 if (f.type === "U") return f.size === 1 ? view.getUint8(o) : f.size === 2 ? view.getUint16(o, true) : view.getUint32(o, true);
190 return f.size === 1 ? view.getInt8(o) : f.size === 2 ? view.getInt16(o, true) : view.getInt32(o, true);
191 };
192 for (let row = 0; row < h.points && sample.length + skipped < SAMPLE_CAP; row += step) take(at(row, sx), at(row, sy), at(row, sz));
193 } else {
194 const text = new TextDecoder().decode(body);
195 const need = Math.max(sx, sy, sz);
196 let pos = 0;
197 let row = 0;
198 // One pass, line by line: bounded by the text, and only a sampled line is split.
199 while (row < h.points && pos < text.length) {
200 let nl = text.indexOf("\n", pos);
201 if (nl < 0) nl = text.length;
202 const line = text.slice(pos, nl);
203 pos = nl + 1;
204 if (line.trim() === "") continue;
205 if (row % step === 0) {
206 const v = line.trim().split(/\s+/, need + 1);
207 if (v.length <= need) throw new Unreadable(`point ${row + 1} has too few values`);
208 take(Number(v[sx]), Number(v[sy]), Number(v[sz]));
209 }
210 row++;
211 }
212 if (row < h.points) throw new Unreadable("the file ends before its header says it should");
213 }
214
215 let bounds: Pcd["bounds"];
216 if (sample.length > 0) {
217 const min = [Infinity, Infinity, Infinity];
218 const max = [-Infinity, -Infinity, -Infinity];
219 for (const p of sample)
220 for (let a = 0; a < 3; a++) {
221 if (p[a]! < min[a]!) min[a] = p[a]!;
222 if (p[a]! > max[a]!) max[a] = p[a]!;
223 }
224 bounds = { min, max };
225 }
226 return {
227 version: h.version, fields: h.fields, width: h.width, height: h.height, points: h.points, data: h.data,
228 viewpoint: h.viewpoint, stride, sample, skipped, ...(bounds ? { bounds } : {}),
229 };
230 }
231
232 /** `1234.5678` as the shortest text that holds six significant digits. */
233 const num = (n: number): string => (Object.is(n, -0) ? "0" : String(+n.toPrecision(6)));
234 const clean = (s: string): string => escapeHtml(s.replace(/[\u0000-\u001f\u007f]/g, "�"));
235 const plural = (n: number, one: string): string => `${n.toLocaleString()} ${one}${n === 1 ? "" : "s"}`;
236
237 /**
238 * What `read_file` says of a `.pcd` beside its content: the header's facts and the sample's range.
239 */
240 export function aboutPcd(body: Uint8Array): Record<string, unknown> {
241 try {
242 const p = readPcd(body);
243 return {
244 kind: "pcd", points: p.points, width: p.width, height: p.height, data: p.data,
245 fields: p.fields.map((f) => f.name), sampled: p.sample.length, ...(p.bounds ? { bounds: p.bounds } : {}),
246 says: `PCD, ${plural(p.points, "point")}, ${p.fields.length} fields, ${p.data}`,
247 };
248 } catch (e) {
249 return { kind: "pcd", says: `PCD, unreadable: ${e instanceof Unreadable ? e.message : "it could not be read"}` };
250 }
251 }
252
253 /**
254 * The header facts and the field table as rows, for the terminal's table; a sentence when the file
255 * cannot be shown (the same gate as the page).
256 */
257 export function pcdFacts(body: Uint8Array): [string, string][] | string {
258 if (body.length > RENDER_CAP.pcd) return "not drawn as a point cloud: it is over 5 MB";
259 try {
260 const p = readPcd(body);
261 const rows: [string, string][] = [
262 ["Points", p.points.toLocaleString()],
263 ["Width x height", `${p.width.toLocaleString()} x ${p.height.toLocaleString()}`],
264 ["Data", p.data],
265 ["Version", p.version || "not stated"],
266 ["Sampled", `${p.sample.length.toLocaleString()} of ${p.points.toLocaleString()}`],
267 ];
268 if (p.bounds) for (const [i, a] of ["x", "y", "z"].entries()) rows.push([`${a} range (sample)`, `${num(p.bounds.min[i]!)} to ${num(p.bounds.max[i]!)}`]);
269 for (const f of p.fields) rows.push([`Field ${f.name.replace(/[\u0000-\u001f\u007f]/g, "�")}`, `${f.type}${f.size} x ${f.count}`]);
270 return rows;
271 } catch (e) {
272 return e instanceof Unreadable ? e.message : "it could not be read";
273 }
274 }
275
276 const PANEL = 240;
277 const PAD = 12;
278
279 /**
280 * One projection: axes `a` over `b`, scaled to the larger span so shapes keep their proportions.
281 */
282 function panel(p: Pcd, a: number, b: number, label: string): string {
283 const { min, max } = p.bounds!;
284 const spanA = max[a]! - min[a]!;
285 const spanB = max[b]! - min[b]!;
286 const span = Math.max(spanA, spanB) || 1;
287 const k = (PANEL - 2 * PAD) / span;
288 let d = "";
289 for (const pt of p.sample) {
290 const x = PAD + (pt[a]! - min[a]!) * k;
291 const y = PANEL - PAD - (pt[b]! - min[b]!) * k;
292 d += `M${x.toFixed(1)} ${y.toFixed(1)}h0`;
293 }
294 const ax = "xyz"[a]!;
295 const ay = "xyz"[b]!;
296 return (
297 `<figure class="pcd-panel"><svg viewBox="0 0 ${PANEL} ${PANEL}" role="img" aria-label="${escapeHtml(label)}">` +
298 `<path d="M${PAD} ${PANEL - PAD}H${PANEL - PAD}M${PAD} ${PANEL - PAD}V${PAD}" fill="none" stroke="currentColor" stroke-opacity=".25"/>` +
299 `<path d="${d}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>` +
300 `<figcaption class="muted small">${ax} (right) · ${ay} (up)<br>${ax} ${num(min[a]!)} to ${num(max[a]!)}<br>${ay} ${num(min[b]!)} to ${num(max[b]!)}</figcaption></figure>`
301 );
302 }
303
304 export function pcd(input: RenderInput): Rendered {
305 let p: Pcd;
306 try {
307 p = readPcd(input.body);
308 } catch (e) {
309 const why = e instanceof Unreadable ? e.message : "it could not be read";
310 return { content: html``, lines: 0, fallback: `This point cloud cannot be shown: ${why}.` };
311 }
312 const summary = `PCD · ${plural(p.points, "point")} · ${fileSize(input.size)}`;
313 const vp = p.viewpoint;
314 const facts: [string, string][] = [
315 ["Points", p.points.toLocaleString()],
316 ["Width × height", `${p.width.toLocaleString()} × ${p.height.toLocaleString()}${p.height > 1 ? " (organized)" : ""}`],
317 ["Data", p.data],
318 ["Version", p.version || "not stated"],
319 ["Viewpoint", `translation ${vp.slice(0, 3).map(num).join(", ")}; quaternion w x y z ${vp.slice(3).map(num).join(", ")}`],
320 ["Bytes per point", p.data === "binary" ? String(p.stride) : "text rows"],
321 ];
322 const fieldRows = p.fields
323 .map((f) => `<tr><td>${clean(f.name)}</td><td>${f.type}</td><td class="num">${f.size}</td><td class="num">${f.count}</td></tr>`)
324 .join("");
325 const notes: string[] = [];
326 if (p.sample.length === 0) notes.push("No point with a finite x, y and z was sampled, so nothing is drawn.");
327 else
328 notes.push(
329 `Drawn from ${plural(p.sample.length, "sampled point")} of ${p.points.toLocaleString()} (at most ${SAMPLE_CAP.toLocaleString()}, evenly spaced). PCD states no unit: axes are in the file's own units, and the ranges are those of the sample.`,
330 );
331 if (p.skipped > 0) notes.push(`${plural(p.skipped, "sampled row")} had a NaN or infinite coordinate and is left out.`);
332 const scatter =
333 p.bounds === undefined
334 ? ""
335 : `<div class="pcd-scatter">${panel(p, 0, 1, "Top: x against y")}${panel(p, 0, 2, "Front: x against z")}${panel(p, 1, 2, "Side: y against z")}</div>`;
336 const content = [
337 `<dl class="status-rows">${facts.map(([k, v]) => `<div class="status-row"><dt>${escapeHtml(k)}</dt><dd>${clean(v)}</dd></div>`).join("")}</dl>`,
338 scatter,
339 `<div class="csv-scroll"><table class="table" data-dense aria-label="Fields"><thead><tr><th>Field</th><th>Type</th><th class="num">Size (bytes)</th><th class="num">Count</th></tr></thead><tbody>${fieldRows}</tbody></table></div>`,
340 ...notes.map((n) => `<p class="muted small">${escapeHtml(n)}</p>`),
341 ].join("\n");
342 return { content: html`${raw(content)}`, lines: 0, summary };
343 }
src/web/render/renderers.ts +2
@@ -75,6 +75,7 @@ import { ora } from "./ora.ts";
7575 import { sqlite } from "./sqlite.ts";
7676 import { parquet } from "./parquet.ts";
7777 import { pcap } from "./pcap.ts";
78 import { pcd } from "./pcd.ts";
7879 import { subtitles } from "./subtitles.ts";
7980 import { video } from "./video.ts";
8081
@@ -146,6 +147,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
146147 sqlite,
147148 parquet,
148149 pcap,
150 pcd,
149151 audio,
150152 video,
151153 model3d,
src/web/style.ts +2
@@ -29,6 +29,7 @@ import { base, layers, reset, utilities } from "./style/base.ts";
2929 import { components } from "./style/components.ts";
3030 import { content } from "./style/content.ts";
3131 import { gcodeCss } from "./render/gcode-css.ts";
32 import { pcdCss } from "./render/pcd-css.ts";
3233 import { model3dCss } from "./render/model3d-css.ts";
3334 import { pickCss } from "./pick.ts";
3435 import { studioCss } from "./studio/style.ts";
@@ -46,6 +47,7 @@ export const css = [
4647 content,
4748 model3dCss,
4849 gcodeCss,
50 pcdCss,
4951 utilities,
5052 pickCss,
5153 ].join("\n");
test/fixtures/cloud-compressed.pcd added
Binary file not shown.
test/fixtures/cloud.pcd added +311
@@ -0,0 +1,311 @@
1 # .PCD v0.7
2 VERSION 0.7
3 FIELDS x y z
4 SIZE 4 4 4
5 TYPE F F F
6 COUNT 1 1 1
7 WIDTH 300
8 HEIGHT 1
9 VIEWPOINT 0 0 0 1 0 0 0
10 POINTS 300
11 DATA ascii
12 0 0 0
13 0.1 0 0
14 0.2 0 0
15 0.3 0 0
16 0.4 0 0
17 0.5 0 0
18 0.6 0 0
19 0.7 0 0
20 0.8 0 0
21 0.9 0 0
22 0 0.1 0
23 0.1 0.1 0
24 0.2 0.1 0
25 0.3 0.1 0
26 0.4 0.1 0
27 0.5 0.1 0
28 0.6 0.1 0
29 0.7 0.1 0
30 0.8 0.1 0
31 0.9 0.1 0
32 0 0.2 0
33 0.1 0.2 0
34 0.2 0.2 0
35 0.3 0.2 0
36 0.4 0.2 0
37 0.5 0.2 0
38 0.6 0.2 0
39 0.7 0.2 0
40 0.8 0.2 0
41 0.9 0.2 0
42 0 0.3 0
43 0.1 0.3 0
44 0.2 0.3 0
45 0.3 0.3 0
46 0.4 0.3 0
47 0.5 0.3 0
48 0.6 0.3 0
49 0.7 0.3 0
50 0.8 0.3 0
51 0.9 0.3 0
52 0 0.4 0
53 0.1 0.4 0
54 0.2 0.4 0
55 0.3 0.4 0
56 0.4 0.4 0
57 0.5 0.4 0
58 0.6 0.4 0
59 0.7 0.4 0
60 0.8 0.4 0
61 0.9 0.4 0
62 0 0.5 0
63 0.1 0.5 0
64 0.2 0.5 0
65 0.3 0.5 0
66 0.4 0.5 0
67 0.5 0.5 0
68 0.6 0.5 0
69 0.7 0.5 0
70 0.8 0.5 0
71 0.9 0.5 0
72 0 0.6 0
73 0.1 0.6 0
74 0.2 0.6 0
75 0.3 0.6 0
76 0.4 0.6 0
77 0.5 0.6 0
78 0.6 0.6 0
79 0.7 0.6 0
80 0.8 0.6 0
81 0.9 0.6 0
82 0 0.7 0
83 0.1 0.7 0
84 0.2 0.7 0
85 0.3 0.7 0
86 0.4 0.7 0
87 0.5 0.7 0
88 0.6 0.7 0
89 0.7 0.7 0
90 0.8 0.7 0
91 0.9 0.7 0
92 0 0.8 0
93 0.1 0.8 0
94 0.2 0.8 0
95 0.3 0.8 0
96 0.4 0.8 0
97 0.5 0.8 0
98 0.6 0.8 0
99 0.7 0.8 0
100 0.8 0.8 0
101 0.9 0.8 0
102 0 0.9 0
103 0.1 0.9 0
104 0.2 0.9 0
105 0.3 0.9 0
106 0.4 0.9 0
107 0.5 0.9 0
108 0.6 0.9 0
109 0.7 0.9 0
110 0.8 0.9 0
111 0.9 0.9 0
112 0 0 0.2
113 0.1 0 0.2
114 0.2 0 0.2
115 0.3 0 0.2
116 0.4 0 0.2
117 0.5 0 0.2
118 0.6 0 0.2
119 0.7 0 0.2
120 0.8 0 0.2
121 0.9 0 0.2
122 0 0.1 0.2
123 0.1 0.1 0.2
124 0.2 0.1 0.2
125 0.3 0.1 0.2
126 0.4 0.1 0.2
127 0.5 0.1 0.2
128 0.6 0.1 0.2
129 0.7 0.1 0.2
130 0.8 0.1 0.2
131 0.9 0.1 0.2
132 0 0.2 0.2
133 0.1 0.2 0.2
134 0.2 0.2 0.2
135 0.3 0.2 0.2
136 0.4 0.2 0.2
137 0.5 0.2 0.2
138 0.6 0.2 0.2
139 0.7 0.2 0.2
140 0.8 0.2 0.2
141 0.9 0.2 0.2
142 0 0.3 0.2
143 0.1 0.3 0.2
144 0.2 0.3 0.2
145 0.3 0.3 0.2
146 0.4 0.3 0.2
147 0.5 0.3 0.2
148 0.6 0.3 0.2
149 0.7 0.3 0.2
150 0.8 0.3 0.2
151 0.9 0.3 0.2
152 0 0.4 0.2
153 0.1 0.4 0.2
154 0.2 0.4 0.2
155 0.3 0.4 0.2
156 0.4 0.4 0.2
157 0.5 0.4 0.2
158 0.6 0.4 0.2
159 0.7 0.4 0.2
160 0.8 0.4 0.2
161 0.9 0.4 0.2
162 0 0.5 0.2
163 0.1 0.5 0.2
164 0.2 0.5 0.2
165 0.3 0.5 0.2
166 0.4 0.5 0.2
167 0.5 0.5 0.2
168 0.6 0.5 0.2
169 0.7 0.5 0.2
170 0.8 0.5 0.2
171 0.9 0.5 0.2
172 0 0.6 0.2
173 0.1 0.6 0.2
174 0.2 0.6 0.2
175 0.3 0.6 0.2
176 0.4 0.6 0.2
177 0.5 0.6 0.2
178 0.6 0.6 0.2
179 0.7 0.6 0.2
180 0.8 0.6 0.2
181 0.9 0.6 0.2
182 0 0.7 0.2
183 0.1 0.7 0.2
184 0.2 0.7 0.2
185 0.3 0.7 0.2
186 0.4 0.7 0.2
187 0.5 0.7 0.2
188 0.6 0.7 0.2
189 0.7 0.7 0.2
190 0.8 0.7 0.2
191 0.9 0.7 0.2
192 0 0.8 0.2
193 0.1 0.8 0.2
194 0.2 0.8 0.2
195 0.3 0.8 0.2
196 0.4 0.8 0.2
197 0.5 0.8 0.2
198 0.6 0.8 0.2
199 0.7 0.8 0.2
200 0.8 0.8 0.2
201 0.9 0.8 0.2
202 0 0.9 0.2
203 0.1 0.9 0.2
204 0.2 0.9 0.2
205 0.3 0.9 0.2
206 0.4 0.9 0.2
207 0.5 0.9 0.2
208 0.6 0.9 0.2
209 0.7 0.9 0.2
210 0.8 0.9 0.2
211 0.9 0.9 0.2
212 0 0 0.4
213 0.1 0 0.4
214 0.2 0 0.4
215 0.3 0 0.4
216 0.4 0 0.4
217 0.5 0 0.4
218 0.6 0 0.4
219 0.7 0 0.4
220 0.8 0 0.4
221 0.9 0 0.4
222 0 0.1 0.4
223 0.1 0.1 0.4
224 0.2 0.1 0.4
225 0.3 0.1 0.4
226 0.4 0.1 0.4
227 0.5 0.1 0.4
228 0.6 0.1 0.4
229 0.7 0.1 0.4
230 0.8 0.1 0.4
231 0.9 0.1 0.4
232 0 0.2 0.4
233 0.1 0.2 0.4
234 0.2 0.2 0.4
235 0.3 0.2 0.4
236 0.4 0.2 0.4
237 0.5 0.2 0.4
238 0.6 0.2 0.4
239 0.7 0.2 0.4
240 0.8 0.2 0.4
241 0.9 0.2 0.4
242 0 0.3 0.4
243 0.1 0.3 0.4
244 0.2 0.3 0.4
245 0.3 0.3 0.4
246 0.4 0.3 0.4
247 0.5 0.3 0.4
248 0.6 0.3 0.4
249 0.7 0.3 0.4
250 0.8 0.3 0.4
251 0.9 0.3 0.4
252 0 0.4 0.4
253 0.1 0.4 0.4
254 0.2 0.4 0.4
255 0.3 0.4 0.4
256 0.4 0.4 0.4
257 0.5 0.4 0.4
258 0.6 0.4 0.4
259 0.7 0.4 0.4
260 0.8 0.4 0.4
261 0.9 0.4 0.4
262 0 0.5 0.4
263 0.1 0.5 0.4
264 0.2 0.5 0.4
265 0.3 0.5 0.4
266 0.4 0.5 0.4
267 0.5 0.5 0.4
268 0.6 0.5 0.4
269 0.7 0.5 0.4
270 0.8 0.5 0.4
271 0.9 0.5 0.4
272 0 0.6 0.4
273 0.1 0.6 0.4
274 0.2 0.6 0.4
275 0.3 0.6 0.4
276 0.4 0.6 0.4
277 0.5 0.6 0.4
278 0.6 0.6 0.4
279 0.7 0.6 0.4
280 0.8 0.6 0.4
281 0.9 0.6 0.4
282 0 0.7 0.4
283 0.1 0.7 0.4
284 0.2 0.7 0.4
285 0.3 0.7 0.4
286 0.4 0.7 0.4
287 0.5 0.7 0.4
288 0.6 0.7 0.4
289 0.7 0.7 0.4
290 0.8 0.7 0.4
291 0.9 0.7 0.4
292 0 0.8 0.4
293 0.1 0.8 0.4
294 0.2 0.8 0.4
295 0.3 0.8 0.4
296 0.4 0.8 0.4
297 0.5 0.8 0.4
298 0.6 0.8 0.4
299 0.7 0.8 0.4
300 0.8 0.8 0.4
301 0.9 0.8 0.4
302 0 0.9 0.4
303 0.1 0.9 0.4
304 0.2 0.9 0.4
305 0.3 0.9 0.4
306 0.4 0.9 0.4
307 0.5 0.9 0.4
308 0.6 0.9 0.4
309 0.7 0.9 0.4
310 0.8 0.9 0.4
311 0.9 0.9 0.4
test/fuzz-renderers.test.ts +6
@@ -55,6 +55,12 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
5555 path: "data.csv",
5656 files: ['name,url,note\nAda,https://a.test,"quoted, cell"\nBob,javascript:alert(1),x\n'],
5757 },
58 pcd: {
59 path: "cloud.pcd",
60 files: [
61 "# .PCD v0.7 - Point Cloud Data file format\nVERSION 0.7\nFIELDS x y z label<b>\nSIZE 4 4 4 4\nTYPE F F F U\nCOUNT 1 1 1 1\nWIDTH 3\nHEIGHT 1\nVIEWPOINT 0 0 0 1 0 0 0\nPOINTS 3\nDATA ascii\n0 0 0 1\n1.5 2 -3 2\nnan 1 1 3\n",
62 ],
63 },
5864 xcf: { path: "a.xcf", files: [xcfSample()] },
5965 tsv: { path: "data.tsv", files: ["a\tb\tc\n1\t2\t3\n"] },
6066 jsonl: {
test/pcd-render.test.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * A .pcd point cloud: header facts, a sampled scatter, the cap, and what a hostile file cannot do.
3 */
4 import { describe, expect, test } from "bun:test";
5 import { fileKind, kindMatches, RENDER_CAP, HEAD_BYTES } from "../src/web/render/kinds.ts";
6 import { aboutPcd, pcd, pcdFacts, readPcd, SAMPLE_CAP } from "../src/web/render/pcd.ts";
7 import { RENDERERS, rendererFor, plainReason } from "../src/web/render/renderers.ts";
8 import { HOSTILE } from "./helpers/hostile.ts";
9
10 const enc = new TextEncoder();
11 const header = (o: { fields?: string; size?: string; type?: string; count?: string; width?: number; height?: number; points?: number; data?: string; extra?: string } = {}): string =>
12 `# .PCD v0.7 - Point Cloud Data file format\nVERSION 0.7\nFIELDS ${o.fields ?? "x y z"}\nSIZE ${o.size ?? "4 4 4"}\nTYPE ${o.type ?? "F F F"}\nCOUNT ${o.count ?? "1 1 1"}\nWIDTH ${o.width ?? 3}\nHEIGHT ${o.height ?? 1}\nVIEWPOINT 0 0 0 1 0 0 0\nPOINTS ${o.points ?? o.width ?? 3}\nDATA ${o.data ?? "ascii"}\n${o.extra ?? ""}`;
13 const ascii = (rows: number[][]): Uint8Array => enc.encode(header({ width: rows.length }) + rows.map((r) => r.join(" ")).join("\n") + "\n");
14 function binary(rows: number[][], head = header({ width: rows.length, data: "binary" })): Uint8Array {
15 const h = enc.encode(head);
16 const out = new Uint8Array(h.length + rows.length * 12);
17 out.set(h);
18 const v = new DataView(out.buffer);
19 rows.forEach((r, i) => r.forEach((n, j) => v.setFloat32(h.length + i * 12 + j * 4, n, true)));
20 return out;
21 }
22 const draw = (body: Uint8Array, path = "a.pcd") => pcd({ path, size: body.length, body, media: "", download: "" });
23
24 describe("a .pcd point cloud", () => {
25 test("is a kind of its own, by name and by its VERSION line", () => {
26 expect(fileKind("a.pcd", ascii([[0, 0, 0]]))).toBe("pcd");
27 expect(fileKind("a.pcd", binary([[0, 0, 0]]).subarray(0, HEAD_BYTES))).toBe("pcd");
28 expect(fileKind("a.pcd", enc.encode("hello\n"))).toBe("text");
29 expect(fileKind("a.txt", ascii([[0, 0, 0]]))).toBe("text");
30 expect(RENDERERS.pcd).toBe(pcd);
31 expect(kindMatches("pcd")).toContain(".pcd");
32 expect(RENDER_CAP.pcd).toBe(5_000_000);
33 });
34
35 test("reads the header and the points, ASCII and binary alike", () => {
36 const rows = [[0, 0, 0], [1, 2, 3], [-1.5, 4, 0.25]];
37 for (const body of [ascii(rows), binary(rows)]) {
38 const p = readPcd(body);
39 expect(p.points).toBe(3);
40 expect([p.width, p.height]).toEqual([3, 1]);
41 expect(p.fields.map((f) => f.name)).toEqual(["x", "y", "z"]);
42 expect(p.sample as unknown as number[][]).toEqual(rows);
43 expect(p.bounds).toEqual({ min: [-1.5, 0, 0], max: [1, 4, 3] });
44 expect(p.viewpoint).toEqual([0, 0, 0, 1, 0, 0, 0]);
45 }
46 expect(readPcd(binary(rows)).stride).toBe(12);
47 });
48
49 test("draws the facts and three projections as SVG with no script", () => {
50 const out = draw(ascii([[0, 0, 0], [10, 20, 30]]));
51 const text = out.content.text;
52 expect(out.summary).toContain("2 points");
53 expect(text).toContain("Viewpoint");
54 expect(text.match(/<svg/g)?.length).toBe(3);
55 expect(text).toContain("x 0 to 10");
56 expect(text).toContain("z 0 to 30");
57 expect(text).toContain("own units");
58 expect(text).not.toContain("<script");
59 });
60
61 test("samples at most 5,000 points, evenly, and says how many of how many", () => {
62 const n = 20_000;
63 const rows = Array.from({ length: n }, (_, i) => [i, 0, 0]);
64 for (const body of [ascii(rows), binary(rows)]) {
65 const p = readPcd(body);
66 expect(p.points).toBe(n);
67 expect(p.sample.length).toBe(SAMPLE_CAP);
68 expect(p.sample[0]![0]).toBe(0);
69 expect(p.sample[1]![0]).toBe(4);
70 }
71 expect(draw(ascii(rows)).content.text).toContain("5,000 sampled points of 20,000");
72 });
73
74 test("leaves out NaN points and says so", () => {
75 const out = draw(enc.encode(header({ width: 2 }) + "nan nan nan\n1 2 3\n"));
76 expect(readPcd(enc.encode(header({ width: 2 }) + "nan nan nan\n1 2 3\n")).skipped).toBe(1);
77 expect(out.content.text).toContain("1 sampled row had a NaN");
78 });
79
80 test("escapes every value drawn from the file", () => {
81 for (const bad of HOSTILE) {
82 const name = bad.replace(/\s+/g, "_").replace(/[\u0000-\u001f]/g, "");
83 if (name === "") continue;
84 const body = enc.encode(header({ fields: `x y z ${name}`, size: "4 4 4 4", type: "F F F F", count: "1 1 1 1", width: 1 }) + "1 2 3 4\n");
85 const text = draw(body).content.text;
86 expect(text).not.toContain("<script");
87 expect(text).not.toMatch(/<img|<svg onload|\bonerror=/i);
88 }
89 const text = draw(enc.encode(header({ fields: "x y z <b>bold</b>", size: "4 4 4 4", type: "F F F F", count: "1 1 1 1", width: 1 }) + "1 2 3 4\n")).content.text;
90 expect(text).toContain("&lt;b&gt;bold&lt;/b&gt;");
91 expect(text).not.toContain("<b>bold");
92 });
93
94 test("a file over the cap keeps the source view and says why in one line", () => {
95 const body = ascii([[0, 0, 0]]);
96 const blob = { kind: "text" as const, body, size: RENDER_CAP.pcd + 1 };
97 expect(rendererFor("a.pcd", blob)).toBeUndefined();
98 expect(plainReason("a.pcd", blob)).toContain("too large");
99 expect(rendererFor("a.pcd", { kind: "text" as const, body, size: body.length })).toBeDefined();
100 });
101
102 test("a file that does not parse falls back with one line, never throws", () => {
103 const cases: Record<string, Uint8Array> = {
104 "no DATA": enc.encode("VERSION 0.7\nFIELDS x y z\n"),
105 "no z": enc.encode(header({ fields: "x y w" }) + "1 2 3\n"),
106 compressed: enc.encode(header({ data: "binary_compressed" })),
107 "too short ascii": ascii([[0, 0, 0]]).subarray(0, -6),
108 "too short binary": binary([[0, 0, 0], [1, 1, 1]]).subarray(0, -1),
109 "mismatched SIZE": enc.encode(header({ size: "4 4" }) + "1 2 3\n"),
110 "bad type": enc.encode(header({ type: "F F Q" }) + "1 2 3\n"),
111 "bad viewpoint": enc.encode(header().replace("VIEWPOINT 0 0 0 1 0 0 0", "VIEWPOINT 1 2") + "1 2 3\n"),
112 };
113 for (const [name, body] of Object.entries(cases)) {
114 const out = draw(body);
115 expect(out.fallback, name).toMatch(/^This point cloud cannot be shown: .+\.$/);
116 expect(out.fallback, name).not.toContain("\n");
117 }
118 });
119
120 test("a lying header is bounded before any loop", () => {
121 // Counts in the trillions with a few bytes of body: refused by arithmetic, instantly.
122 const t0 = performance.now();
123 const huge = enc.encode(header({ width: 1_000_000_000_000, points: 1_000_000_000_000, data: "binary" }) + "xxxx");
124 expect(draw(huge).fallback).toContain("ends before");
125 const hugeAscii = enc.encode(header({ width: 1_000_000_000_000, points: 1_000_000_000_000 }) + "1 2 3\n");
126 expect(draw(hugeAscii).fallback).toContain("ends before");
127 const absurd = enc.encode(header({ points: 99999999999999 }) + "1 2 3\n");
128 expect(draw(absurd).fallback).toContain("cannot be shown");
129 const manyFields = enc.encode(header({ fields: Array.from({ length: 500 }, (_, i) => `f${i}`).join(" ") }));
130 expect(draw(manyFields).fallback).toContain("more than 64 fields");
131 const bigCount = enc.encode(header({ count: "1 1 99999999" }) + "1 2 3\n");
132 expect(draw(bigCount).fallback).toContain("COUNT");
133 expect(performance.now() - t0).toBeLessThan(500);
134 });
135
136 test("an endless header with no DATA line stops at the header cap", () => {
137 const body = enc.encode("VERSION 0.7\n" + "# filler\n".repeat(5000));
138 expect(draw(body).fallback).toContain("DATA");
139 });
140
141 test("read_file's about carries the same facts", () => {
142 const a = aboutPcd(ascii([[0, 0, 0], [1, 1, 1]]));
143 expect(a).toMatchObject({ kind: "pcd", points: 2, width: 2, height: 1, data: "ascii", fields: ["x", "y", "z"], sampled: 2 });
144 expect(String(a["says"])).toContain("2 points");
145 expect(String(aboutPcd(enc.encode("junk"))["says"])).toContain("unreadable");
146 });
147 });
148
149 describe("the committed fixtures and the terminal's facts", () => {
150 const fixture = async (n: string) => new Uint8Array(await Bun.file(`${import.meta.dir}/fixtures/${n}`).arrayBuffer());
151 test("an ASCII fixture draws three panels with axis baselines and no box", async () => {
152 const out = draw(await fixture("cloud.pcd"), "cloud.pcd");
153 const text = String(out.content);
154 expect(text.match(/class="pcd-panel"/g)?.length).toBe(3);
155 expect(text).not.toContain("<rect");
156 });
157 test("a binary_compressed fixture keeps the source with one line saying why", async () => {
158 const out = draw(await fixture("cloud-compressed.pcd"), "cloud-compressed.pcd");
159 expect(out.fallback).toContain("cannot be shown");
160 });
161 test("pcdFacts gives the terminal rows, or the page's reason", async () => {
162 const rows = pcdFacts(await fixture("cloud.pcd"));
163 expect(Array.isArray(rows) && rows[0]).toEqual(["Points", "300"]);
164 expect(typeof pcdFacts(enc.encode("junk"))).toBe("string");
165 expect(pcdFacts(new Uint8Array(RENDER_CAP.pcd + 1))).toContain("over 5 MB");
166 });
167 });
test/tui-workspace-formats-more.test.ts +19
@@ -239,6 +239,25 @@ describe("the terminal workspace, by file type", () => {
239239 }
240240 });
241241
242 test("a .pcd opens as its header facts and field rows, sharing the web reader, and s flips to the source", async () => {
243 const made = await createRepo(forge, alice, { name: "scans", visibility: "public", description: "clouds" });
244 if (!made.ok) throw new Error("repo failed");
245 const content = "VERSION 0.7\nFIELDS x y z\nSIZE 4 4 4\nTYPE F F F\nCOUNT 1 1 1\nWIDTH 2\nHEIGHT 1\nVIEWPOINT 0 0 0 1 0 0 0\nPOINTS 2\nDATA ascii\n0 0 0\n1 2 3\n";
246 await commitToBranch(forge, alice, made.value, { message: "seed", files: [{ path: "cloud.pcd", content }] });
247 const h = boot();
248 try {
249 await h.settle();
250 await open(h, "scans");
251 await openFile(h, "cloud.pcd");
252 expect(h.text()).toContain("Points");
253 expect(h.text()).toContain("range (sample)");
254 await h.press("s");
255 expect(h.text()).toContain("FIELDS x y z");
256 } finally {
257 h.stop();
258 }
259 });
260
242261 test("a .step opens as its facts, types and products, sharing the web reader, and s flips to the source", async () => {
243262 const made = await createRepo(forge, alice, { name: "parts", visibility: "public", description: "cad" });
244263 if (!made.ok) throw new Error("repo failed");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs