Merge [B9] Punktwolken-Leser in Rust: LAS/LAZ, E57, PLY, XYZ/PTS mit Ausduennen; CLI pointcloud-info

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 14:28:54 +00:00
commit f18b4e22ad
15 files changed
+2154 -3

No files matched your search

+41 -1
View File
@@ -18,6 +18,8 @@
// IFC als Kontext-Meshes ([B3]), mit --elements als echte
// Bauteile ([B4]); Bericht als JSON auf stdout
// dossier-cli <projekt.obp> model3d [--out modell.json] 3D-Modell fürs Headless-Rendern (render_png)
// dossier-cli pointcloud-info <datei.las|laz|e57|ply|xyz|pts> [--voxel 0.05] [--max 2000000]
// Punktwolke lesen ([B9]) und Bericht als JSON (ohne Projekt)
// dossier-cli <projekt.obp> mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate
// dossier-cli <projekt.obp> bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf)
//
@@ -33,6 +35,7 @@ import {
buildPlanDwg,
buildPlanDxfBinary,
loadFileio,
readPointCloudFlat,
readIfc,
readIfcElements,
ifcElementsToProject,
@@ -153,15 +156,52 @@ function out(args: Args, text: string | Uint8Array, defaultName: string): void {
}
}
/** `pointcloud-info <datei> [--voxel m] [--max n]`: liest und dünnt aus, gibt den Bericht als JSON aus. */
async function pointCloudInfo(args: Args, src: string | undefined): Promise<number> {
if (!src) fail("pointcloud-info: Datei fehlt (Aufruf: pointcloud-info <datei> [--voxel 0.05] [--max 2000000])");
setWasmBytesProvider(async (name) => {
const rel = WASM_FILES[name];
if (!rel) throw new Error(`unbekanntes WASM-Modul ${name}`);
return readFileSync(join(wasmDir(), rel));
});
await loadFileio();
let bytes: Buffer;
try {
bytes = readFileSync(src);
} catch (e) {
fail(`Datei nicht lesbar: ${src} (${e instanceof Error ? e.message : String(e)})`);
}
const num = (k: string, d: number): number => {
const v = Number(args.flags.get(k) ?? d);
if (!Number.isFinite(v) || v < 0) fail(`--${k}: keine gültige Zahl`);
return v;
};
const t0 = performance.now();
let cloud;
try {
cloud = readPointCloudFlat(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), src, {
voxel: num("voxel", 0),
maxPoints: num("max", 2_000_000),
});
} catch (e) {
fail(`${src}: ${e instanceof Error ? e.message : String(e)}`);
}
const ms = Math.round(performance.now() - t0);
process.stdout.write(JSON.stringify({ file: src, bytes: bytes.byteLength, ms, ...cloud.report }, null, 2) + "\n");
return 0;
}
export async function run(argv: string[]): Promise<number> {
const args = parseArgs(argv);
const convertMode = args.positional[0] === "convert";
const [file, command, ...rest] = args.positional;
if (file === "pointcloud-info") return pointCloudInfo(args, command);
if (!file || (!command && args.cmds.length === 0)) {
process.stderr.write(
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun|model3d> [Optionen]\n" +
" dossier-cli convert <eingabe.dxf|dwg|ifc|obp> <ausgabe.obp|dxf|dwg|ifc|obj|stl|glb|gltf|step> [--cmd \"befehl …\"]…\n" +
" dossier-cli <projekt.obp> --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n",
" dossier-cli <projekt.obp> --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" +
" dossier-cli pointcloud-info <datei> [--voxel 0.05] [--max 2000000]\n",
);
return 2;
}
+2
View File
@@ -32,3 +32,5 @@ export { sampleProject } from "../model/sampleProject";
export { parseDxf } from "../io/dxfParser";
export { contoursToDrawings, textsToDrawings, planImportCategories, distinctImportLayers } from "../io/dxfToDrawings";
export { emptyProject } from "../model/sampleProject";
export { readPointCloud, readPointCloudFlat, isPointCloudFile, DEFAULT_MAX_POINTS } from "../io/pointCloud";
export type { PointCloudData, PointCloudOptions, PointCloudReport } from "../io/pointCloud";
+96
View File
@@ -0,0 +1,96 @@
// Punktwolken-Fassade ([B9]): Rundreise über das Rust-WASM (kleine, im Test erzeugte Dateien).
// Die Formatdetails (LAS 1.0–1.4, LAZ, E57, PLY) prüfen die Rust-Tests in `pointcloud*.rs`.
import { beforeAll, describe, expect, it } from "vitest";
import { loadFileioForTests } from "../engine/fileioWasm.testing";
import { isPointCloudFile, readPointCloud, readPointCloudFlat } from "./pointCloud";
beforeAll(loadFileioForTests);
/** LAS 1.2, Punktformat 2 (XYZ, Intensität, Klasse, RGB), Skala 1 mm. */
function makeLas(n: number): Uint8Array {
const rec = 26;
const buf = new Uint8Array(227 + n * rec);
const dv = new DataView(buf.buffer);
buf.set([0x4c, 0x41, 0x53, 0x46], 0);
buf[24] = 1;
buf[25] = 2;
dv.setUint16(94, 227, true);
dv.setUint32(96, 227, true);
buf[104] = 2;
dv.setUint16(105, rec, true);
dv.setUint32(107, n, true);
const off = [2683000, 1248000, 400];
for (let i = 0; i < 3; i++) {
dv.setFloat64(131 + 8 * i, 0.001, true);
dv.setFloat64(155 + 8 * i, off[i], true);
}
dv.setFloat64(179, 2683000 + 99.9, true);
dv.setFloat64(187, 2683000, true);
dv.setFloat64(195, 1248000 + 9.9, true);
dv.setFloat64(203, 1248000, true);
dv.setFloat64(211, 405, true);
dv.setFloat64(219, 400, true);
for (let k = 0; k < n; k++) {
const o = 227 + k * rec;
dv.setInt32(o, Math.round((k % 1000) * 100), true); // x: 0,1 m Raster
dv.setInt32(o + 4, Math.round(Math.floor(k / 1000) * 100), true);
dv.setInt32(o + 8, (k % 6) * 1000, true);
dv.setUint16(o + 12, k % 500, true);
buf[o + 15] = k % 2 === 0 ? 2 : 6;
dv.setUint16(o + 20, 65535, true);
}
return buf;
}
describe("readPointCloud (Rust-WASM)", () => {
it("liest LAS: Werte, Anzahl, Ursprung, Klassifikation", () => {
const c = readPointCloudFlat(makeLas(2000), "t.las", { maxPoints: 0 });
expect(c.report.format).toBe("las");
expect(c.report.pointsKept).toBe(2000);
expect(c.xyz.length).toBe(6000);
// absolut = origin + xyz
expect(c.origin[0] + c.xyz[3]).toBeCloseTo(2683000.1, 3);
expect(c.origin[2] + c.xyz[5]).toBeCloseTo(401, 3);
expect(c.rgb?.[0]).toBe(255);
expect(c.classification?.[0]).toBe(2);
expect(c.classification?.[1]).toBe(6);
expect(c.report.classCounts).toEqual([[2, 1000], [6, 1000]]);
// f32 relativ zum Ursprung genügt für mm
expect(Math.max(...c.xyz.map(Math.abs))).toBeLessThan(200);
});
it("dünnt über Budget und Voxel aus", () => {
const las = makeLas(5000);
const budget = readPointCloudFlat(las, "t.las", { maxPoints: 300 });
expect(budget.report.pointsRead).toBe(5000);
expect(budget.xyz.length / 3).toBeLessThanOrEqual(300);
expect(budget.report.voxel).toBeGreaterThan(0);
const vox = readPointCloudFlat(las, "t.las", { voxel: 1, maxPoints: 0 });
// x: 100 Zellen, y: 0–0,4 m = 1 Zelle, z: 0–5 m = 6 Zellen
expect(vox.xyz.length / 3).toBe(600);
// Bounding-Box bleibt die der ganzen Datei
expect(budget.report.bboxMax[0]).toBeCloseTo(2683000 + 99.9, 3);
});
it("liest XYZ-Text über readPointCloud (ohne Worker)", async () => {
const text = new TextEncoder().encode("2600000.5 1200000.5 400\n2600001.5 1200001.5 401\n");
const c = await readPointCloud(text.buffer as ArrayBuffer, "a.xyz");
expect(c.report.format).toBe("xyz");
expect(c.report.pointsKept).toBe(2);
});
it("wirft bei Unsinn verständliche Fehler (kein Panic)", () => {
expect(() => readPointCloudFlat(new Uint8Array(0), "x.las")).toThrow();
expect(() => readPointCloudFlat(new Uint8Array([1, 2, 3, 4, 5, 6]), "x.bin")).toThrow();
expect(() => readPointCloudFlat(makeLas(10).slice(0, 100), "x.las")).toThrow(/abgeschnitten/);
// Danach funktioniert das Modul weiter.
expect(readPointCloudFlat(makeLas(3), "ok.las", { maxPoints: 0 }).report.pointsKept).toBe(3);
});
it("erkennt Dateiendungen", () => {
expect(isPointCloudFile("Kachel_2683_1248.LAZ")).toBe(true);
expect(isPointCloudFile("scan.e57")).toBe(true);
expect(isPointCloudFile("plan.dxf")).toBe(false);
});
});
+146
View File
@@ -0,0 +1,146 @@
// Punktwolken lesen ([B9] für [27]): dünne Fassade über den Rust-Leser (`src-tauri/fileio/src/pointcloud*.rs`):
// LAS 1.0–1.4, LAZ, E57, PLY, XYZ, PTS. Gleicher Weg wie der DWG-Import (`dwgParser.ts`): im Browser in
// einem Web-Worker (`pointCloud.worker.ts`), damit die UI bei hunderten MB nicht einfriert; ohne `Worker`
// (Node: CLI, Tests) direkt im aufrufenden Thread.
//
// Rust dünnt STREAMEND aus (Voxel-Raster und/oder Punktbudget), sodass auch 50 Mio. Punkte als
// wenige Millionen im Browser ankommen. Koordinaten sind f32 RELATIV zu `origin` (ganze Meter, f64):
// absolut = origin + xyz. In LV95 reicht f32 so auf Kachelgrösse für mm; absolut hätte es ~0,25 m.
//
// Nur die Datei laden — im Modell (`Project.pointClouds`) und im Renderer ist noch nichts verdrahtet
// (Vorschlag in TODO.md [27]).
import { fileioLoaded, loadFileio } from "../engine/fileioWasm";
import type { PointCloudWorkerRequest, PointCloudWorkerResponse } from "./pointCloud.worker";
/** Voreinstellung des Punktbudgets für die Anzeige (Rust dünnt darüber hinaus aus). */
export const DEFAULT_MAX_POINTS = 5_000_000;
export interface PointCloudOptions {
/** Voxel-Kantenlänge in m (0/leer = kein festes Raster). */
voxel?: number;
/** Höchstzahl behaltener Punkte (Voreinstellung {@link DEFAULT_MAX_POINTS}; 0 = unbegrenzt). */
maxPoints?: number;
}
/** Bericht aus Rust (`PointReport`, camelCase). */
export interface PointCloudReport {
format: "las" | "laz" | "e57" | "ply" | "xyz" | "pts";
version: string;
pointFormat: number | null;
pointsDeclared: number;
pointsRead: number;
pointsKept: number;
pointsInvalid: number;
/** Zuletzt verwendete Voxelkante in m (0 = nicht ausgedünnt). */
voxel: number;
/** Bounding-Box aller gelesenen Punkte, absolut. */
bboxMin: [number, number, number];
bboxMax: [number, number, number];
origin: [number, number, number];
hasColor: boolean;
hasIntensity: boolean;
hasClassification: boolean;
intensityRange: [number, number] | null;
/** `[Klassifikationscode, Anzahl]`, aufsteigend. */
classCounts: Array<[number, number]>;
/** EPSG-Code laut Datei (LV95 = 2056), falls genannt. */
epsg: number | null;
truncated: boolean;
warnings: string[];
}
export interface PointCloudData {
/** Ursprung in Dateikoordinaten; absolut = origin + xyz. */
origin: [number, number, number];
/** x,y,z je Punkt (f32, relativ zu `origin`). */
xyz: Float32Array;
/** r,g,b je Punkt (8 Bit) oder `null`. */
rgb: Uint8Array | null;
/** Intensität je Punkt (u16) oder `null`. */
intensity: Uint16Array | null;
/** ASPRS-Klassifikation je Punkt oder `null`. */
classification: Uint8Array | null;
report: PointCloudReport;
}
/** Dateien, die als Punktwolke geöffnet werden können (Endungen, klein). */
export const POINT_CLOUD_EXTENSIONS = ["las", "laz", "e57", "ply", "xyz", "pts"] as const;
export function isPointCloudFile(name: string): boolean {
const ext = name.toLowerCase().split(".").pop() ?? "";
return (POINT_CLOUD_EXTENSIONS as readonly string[]).includes(ext);
}
function resolveOptions(o: PointCloudOptions | undefined): { voxel: number; maxPoints: number } {
const voxel = o?.voxel !== undefined && Number.isFinite(o.voxel) && o.voxel > 0 ? o.voxel : 0;
const maxPoints = o?.maxPoints === undefined ? DEFAULT_MAX_POINTS : o.maxPoints;
return { voxel, maxPoints: Number.isFinite(maxPoints) && maxPoints > 0 ? Math.floor(maxPoints) : 0 };
}
/** Synchron lesen; das Format-Modul muss geladen sein (`loadFileio()`). Wirft bei unlesbaren Dateien. */
export function readPointCloudFlat(
input: ArrayBuffer | Uint8Array,
name: string,
options?: PointCloudOptions,
): PointCloudData {
const m = fileioLoaded();
if (!m) throw new Error("Format-Modul nicht geladen: loadFileio() muss vor dem Lesen laufen.");
const { voxel, maxPoints } = resolveOptions(options);
const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
let res: ReturnType<typeof m.read_point_cloud>;
try {
res = m.read_point_cloud(bytes, name, voxel, maxPoints);
} catch (e) {
throw new Error(typeof e === "string" ? e : e instanceof Error ? e.message : "Punktwolke nicht lesbar");
}
try {
const rgb = res.rgb();
const intensity = res.intensity();
const classification = res.classification();
const o = res.origin();
return {
origin: [o[0], o[1], o[2]],
xyz: res.xyz(),
rgb: rgb.length ? rgb : null,
intensity: intensity.length ? intensity : null,
classification: classification.length ? classification : null,
report: JSON.parse(res.report_json()) as PointCloudReport,
};
} finally {
res.free();
}
}
async function runWorker(req: PointCloudWorkerRequest, transfer: Transferable[]): Promise<PointCloudWorkerResponse> {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL("./pointCloud.worker.ts", import.meta.url), { type: "module" });
worker.onmessage = (e: MessageEvent<PointCloudWorkerResponse>) => {
worker.terminate();
resolve(e.data);
};
worker.onerror = (e) => {
worker.terminate();
reject(new Error(e.message || "Punktwolken-Import (Worker) fehlgeschlagen"));
};
worker.postMessage(req, transfer);
});
}
/**
* Liest eine Punktwolke (Format wird am Inhalt erkannt, `name` nur für XYZ/PTS). Im Browser im Worker
* (der Eingabepuffer wird dorthin ÜBERTRAGEN und ist danach leer), sonst im aufrufenden Thread.
*/
export async function readPointCloud(
data: ArrayBuffer,
name: string,
options?: PointCloudOptions,
): Promise<PointCloudData> {
if (typeof Worker === "undefined") {
await loadFileio();
return readPointCloudFlat(data, name, options);
}
const res = await runWorker({ type: "read", data, name, options }, [data]);
if (res.type === "result") return res.cloud;
throw new Error(res.message);
}
+30
View File
@@ -0,0 +1,30 @@
// Web-Worker für den Punktwolken-Import: lädt das Rust-Format-Modul und liest die Datei AUSSERHALB
// des Haupt-Threads (Muster `dxfParser.worker.ts`). Ein Worker je Aufruf, danach beendet.
//
// → { type: "read", data: ArrayBuffer, name: string, options?: PointCloudOptions }
// ← { type: "result", cloud: PointCloudData } | { type: "error", message }
//
// Die Typed Arrays gehen übertragen (nicht kopiert) zurück.
import { loadFileio } from "../engine/fileioWasm";
import { readPointCloudFlat } from "./pointCloud";
import type { PointCloudData, PointCloudOptions } from "./pointCloud";
export type PointCloudWorkerRequest = { type: "read"; data: ArrayBuffer; name: string; options?: PointCloudOptions };
export type PointCloudWorkerResponse = { type: "result"; cloud: PointCloudData } | { type: "error"; message: string };
const post = (msg: PointCloudWorkerResponse, transfer: Transferable[] = []) =>
(self as unknown as Worker).postMessage(msg, transfer);
self.onmessage = async (e: MessageEvent<PointCloudWorkerRequest>) => {
try {
await loadFileio();
if (e.data?.type !== "read") throw new Error("Unbekannte Anfrage");
const cloud = readPointCloudFlat(e.data.data, e.data.name, e.data.options);
const transfer: Transferable[] = [cloud.xyz.buffer];
for (const a of [cloud.rgb, cloud.intensity, cloud.classification]) if (a) transfer.push(a.buffer);
post({ type: "result", cloud }, transfer);
} catch (err) {
post({ type: "error", message: err instanceof Error ? err.message : String(err) });
}
};