[K4] Merge: STEP-Import im Kern (truck liefert flachen Puffer, ein Undo-Schritt)
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
12 files changed
+243
-37
No files matched your search
@@ -367,6 +367,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
Griff, Import oder den Ops (`history.op.<art>:<liste>`); Anzeige `historyLabelText`. Panel `HistoryPanel` (Bearbeiten > Verlauf,
|
||||
nicht im Standard-Layout), jüngster oben, Wiederholen-Schritte gedimmt, Klick = `jumpHistory`. Offen: Beschriftungen für
|
||||
Eigenschafts-Änderungen aus Panels sind nur „X ändern" (kein Feldname); kein Tastenkürzel; nicht auf dem Mac getestet.
|
||||
Transformation/GPU-Cache der Plan-Ansicht, Werkzeug-Vorschau aus UI-Zustand. Rest-Pendenzen:
|
||||
Import-Ops als JSON zurück (42 MB beim 150k-Kataster), Undo-Liste in der UI [84]. Nicht auf dem Mac getestet.
|
||||
Ziel (Entscheid 28.10., Maintainer): nur die UI bleibt TS, alles andere Rust. Vorgehen in Stufen, jede verdrahtet und mit
|
||||
Gleichheitstest gegen die TS-Fassung, die im selben Schritt verschwindet:
|
||||
- ✅ **S1 Dokument im Kern** (28.10.): `document.rs` hält das Projekt als JSON-Baum, `core/document.ts` spiegelt jede
|
||||
@@ -972,7 +974,15 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
umwandeln + Commit im Kern), neu 2,0–2,7 s (Kern: Zusammenfassung ≈ 0,1 s, Import ≈ 1,7–2,0 s, `JSON.parse` der
|
||||
Ops ≈ 0,6 s); CLI `convert` (inkl. Lesen und 78 MB Schreiben) alt ≈ 9,4 s, neu ≈ 9,6–11,9 s (das alte CLI ging
|
||||
am Kern-Dokument vorbei). Offen: Ops-Rückgabe als JSON (42 MB beim 150k-Kataster) — die Leseansicht könnte
|
||||
die Elemente billiger bekommen; STEP-Import (truck) unverändert in TS; nicht in Tauri/macOS geprüft.
|
||||
die Elemente billiger bekommen; nicht in Tauri/macOS geprüft.
|
||||
**STEP-Import im Kern (29.10.):** truck (`trucksolid`, eigenes WASM) liest und tesselliert wie bisher, liefert aber
|
||||
einen flachen `Float64Array` (`import_step_flat`, Aufbau `brep::step_meshes_flat`; JSON-`import_step` entfällt);
|
||||
der Kern (`import_context.rs::decode_step/step_meshes`, Bindung `doc_import_step`, TS `ProjectDocument.importStep`,
|
||||
App: `readStepFlat` → `commitImport`) macht je Körper ein Kontext-Mesh („Import“, Kategorie 10) als EIN Undo-Schritt.
|
||||
Gelöscht: `io/stepImport.ts`. Gleichheit (einmalig gegen die alte TS-Fassung): Demo-Haus-, Wand+Zylinder- und
|
||||
Quader-STEP aus dem eigenen Export → Meshes (Namen, Positionen f32-genau wie über JSON, Indizes, Schlüsselfolge)
|
||||
zeichengleich bis auf ids. CLI importiert kein STEP (nur Export). Bleibend: `io/stepImport.test.ts`, Rust
|
||||
`step_tests`. Nur im Linux-Container geprüft, nicht in Tauri/macOS.
|
||||
Offene Entscheide/Risiken: Kosten der JSON-Übergabe bei grossen Projekten (Teil-Updates statt Neuaufbau), Struktur-Sharing im
|
||||
React-Store (TS-Spiegel bleibt bis S3), Befehls-Zustandsautomaten sind viel Code (`src/commands/cmds/*`).
|
||||
- **Fertig wenn** (je Etappe): TS-Fassung gelöscht, `npm run check` grün, App/CLI/IFC unverändert.
|
||||
|
||||
@@ -498,3 +498,98 @@ pub fn mesh_objects_to_meshes(objects: &[MeshObject], file_name: &str, placement
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ── STEP ([K4] S4, vorher `io/stepImport.ts`) ────────────────────────────────
|
||||
|
||||
/// Körper aus dem flachen Puffer von truck (`trucksolid::brep::step_meshes_flat`):
|
||||
/// `[1, n, (np, ni, Positionen…, Indizes…) je Körper]`, Positionen f32 in f64 geweitet.
|
||||
pub fn decode_step(f: &[f64]) -> Result<Vec<(Vec<f32>, Vec<f64>)>, String> {
|
||||
let bad = || "STEP-Import: Puffer beschädigt".to_string();
|
||||
if f.len() < 2 || f[0] != 1.0 || !(f[1] >= 0.0 && f[1].fract() == 0.0) {
|
||||
return Err("STEP-Import: unbekannte Kodierung".into());
|
||||
}
|
||||
let mut at = 2;
|
||||
let mut out = Vec::new();
|
||||
let mut k = 0.0;
|
||||
while k < f[1] {
|
||||
let h = f.get(at..at + 2).ok_or_else(bad)?;
|
||||
let (np, ni) = (h[0], h[1]);
|
||||
at += 2;
|
||||
if !(np.fract() == 0.0 && ni.fract() == 0.0 && np >= 0.0 && ni >= 0.0) || at + np as usize + ni as usize > f.len() {
|
||||
return Err(bad());
|
||||
}
|
||||
let positions = f[at..at + np as usize].iter().map(|&x| x as f32).collect();
|
||||
at += np as usize;
|
||||
let indices = f[at..at + ni as usize].to_vec();
|
||||
at += ni as usize;
|
||||
out.push((positions, indices));
|
||||
k += 1.0;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// STEP-Körper → Kontext-Meshes der Kategorie „Import“, Koordinaten unverändert (Meter, Z = Höhe), ohne
|
||||
/// `layer`. Zahlen wie vorher über JSON: die f32-Positionen mit ihrer kürzesten Dezimaldarstellung.
|
||||
pub fn step_meshes(bodies: &[(Vec<f32>, Vec<f64>)], file_name: &str, now: f64) -> Vec<Value> {
|
||||
let base = base_name(file_name, "STEP");
|
||||
let stamp = stamp36(now);
|
||||
let n = bodies.len();
|
||||
bodies
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, (pos, idx))| {
|
||||
let mut o = Map::new();
|
||||
o.insert("id".into(), format!("imported-step-{stamp}-{}", next_seq()).into());
|
||||
o.insert("type".into(), "importedMesh".into());
|
||||
o.insert("name".into(), if n > 1 { format!("{base} ({}/{n})", i + 1) } else { base.clone() }.into());
|
||||
o.insert("categoryCode".into(), GENERIC_IMPORT_CODE.into());
|
||||
o.insert("positions".into(), Value::Array(pos.iter().map(|&x| js_num(x.to_string().parse().unwrap_or(f64::from(x)))).collect()));
|
||||
o.insert("indices".into(), Value::Array(idx.iter().map(|&k| js_num(k)).collect()));
|
||||
Value::Object(o)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod step_tests {
|
||||
use super::*;
|
||||
|
||||
fn flat() -> Vec<f64> {
|
||||
// zwei Körper: Dreieck mit 0.1f32 (nicht exakt in f64), Dreieck mit ganzen Zahlen
|
||||
let mut f = vec![1.0, 2.0, 9.0, 3.0];
|
||||
f.extend([0.1f32, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, -0.0].iter().map(|&x| x as f64));
|
||||
f.extend([0.0, 1.0, 2.0, 9.0, 3.0]);
|
||||
f.extend([5.0, 0.0, 0.0, 6.0, 0.0, 0.0, 5.0, 1.0, 0.0]);
|
||||
f.extend([0.0, 1.0, 2.0]);
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn koerper_werden_kontext_meshes() {
|
||||
let bodies = decode_step(&flat()).unwrap();
|
||||
let m = step_meshes(&bodies, "haus.stp", 1.0e12);
|
||||
assert_eq!(m.len(), 2);
|
||||
assert_eq!(m[0]["name"], "haus (1/2)");
|
||||
assert_eq!(m[1]["name"], "haus (2/2)");
|
||||
assert_eq!(m[0]["categoryCode"], "10");
|
||||
assert!(m[0].get("layer").is_none());
|
||||
assert_eq!(m[0]["positions"][0], json!(0.1));
|
||||
assert_eq!(m[1]["indices"], json!([0, 1, 2]));
|
||||
assert!(m[0]["id"].as_str().unwrap().starts_with("imported-step-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ein_koerper_traegt_den_dateinamen_ohne_nummer() {
|
||||
let f = vec![1.0, 1.0, 3.0, 3.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
|
||||
let m = step_meshes(&decode_step(&f).unwrap(), ".step", 1.0);
|
||||
assert_eq!(m[0]["name"], "STEP");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kaputte_puffer_werden_verworfen() {
|
||||
assert!(decode_step(&[]).is_err());
|
||||
assert!(decode_step(&[2.0, 0.0]).is_err());
|
||||
assert!(decode_step(&[1.0, 1.0, 9.0, 3.0, 0.0]).is_err());
|
||||
assert!(decode_step(&[1.0, f64::NAN]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -204,6 +204,31 @@ pub fn doc_import_mesh(h: u32, flat: &[f64], strings_json: &str, opts_json: &str
|
||||
.unwrap_or_else(|| err("Dokument nicht offen"))
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
struct StepOptions {
|
||||
file_name: String,
|
||||
}
|
||||
|
||||
/// Gelesenes STEP (flacher Puffer von truck) als Kontext-Meshes ins Dokument `h`, ein Undo-Schritt.
|
||||
/// Antwort: `{"ops":[…],"contextObjects":n}`.
|
||||
#[wasm_bindgen]
|
||||
pub fn doc_import_step(h: u32, flat: &[f64], opts_json: &str, key: &str, now_ms: f64) -> String {
|
||||
let now = now_of(now_ms);
|
||||
let opts: StepOptions = serde_json::from_str(opts_json).unwrap_or_default();
|
||||
let bodies = match crate::import_context::decode_step(flat) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return err(e),
|
||||
};
|
||||
with_doc(h, |doc| {
|
||||
let meshes = crate::import_context::step_meshes(&bodies, &opts.file_name, now);
|
||||
let n = meshes.len();
|
||||
let ops = crate::import_context::context_ops(doc.root(), meshes);
|
||||
commit(doc, ops, &[("contextObjects", n.into())], key, now)
|
||||
})
|
||||
.unwrap_or_else(|| err("Dokument nicht offen"))
|
||||
}
|
||||
|
||||
/// Kurzbericht einer gelesenen PDF-Seite (CLI `pdf-info`): Zahlen, Ebenen, Umriss.
|
||||
#[wasm_bindgen]
|
||||
pub fn pdf_page_info(geom: &[f64], strings_json: &str) -> String {
|
||||
|
||||
@@ -690,7 +690,6 @@ pub fn export_step_core(specs: &[SolidSpec], header: &StepHeader) -> Res<String>
|
||||
}
|
||||
|
||||
/// Ein eingelesener STEP-Körper (Shell) als Mesh.
|
||||
#[derive(Serialize)]
|
||||
pub struct StepMesh {
|
||||
pub positions: Vec<f32>,
|
||||
pub indices: Vec<u32>,
|
||||
@@ -820,6 +819,18 @@ pub fn step_length_unit_in_m(text: &str) -> f64 {
|
||||
1.0
|
||||
}
|
||||
|
||||
/// STEP-Körper als flacher Puffer `[1, n, (np, ni, Positionen…, Indizes…) je Körper]` (Grenze zum Kern).
|
||||
pub fn step_meshes_flat(meshes: &[StepMesh]) -> Vec<f64> {
|
||||
let mut f = vec![1.0, meshes.len() as f64];
|
||||
for m in meshes {
|
||||
f.push(m.positions.len() as f64);
|
||||
f.push(m.indices.len() as f64);
|
||||
f.extend(m.positions.iter().map(|&x| x as f64));
|
||||
f.extend(m.indices.iter().map(|&i| i as f64));
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
/// Liest eine STEP-Datei und tesselliert alle Shells (relative Toleranz `rel_tol` der
|
||||
/// Bounding-Box-Diagonale, z. B. 0.001).
|
||||
pub fn import_step_core(text: &str, rel_tol: f64) -> Res<Vec<StepMesh>> {
|
||||
|
||||
@@ -440,11 +440,12 @@ mod web {
|
||||
}
|
||||
|
||||
/// Liest STEP-Text und tesselliert alle Körper (`relTol` = Toleranz relativ zur
|
||||
/// Bounding-Box-Diagonale, Default 0.001). Output JSON: `[{positions, indices}, …]`.
|
||||
/// Bounding-Box-Diagonale, Default 0.001). Flacher Puffer für den Kern (`import_step.rs`):
|
||||
/// `[1, n, (np, ni, Positionen…, Indizes…) je Körper]`, Positionen als f32 in f64 geweitet.
|
||||
#[wasm_bindgen]
|
||||
pub fn import_step(text: &str, rel_tol: f64) -> std::result::Result<String, JsError> {
|
||||
pub fn import_step_flat(text: &str, rel_tol: f64) -> std::result::Result<Vec<f64>, JsError> {
|
||||
let meshes = brep::import_step_core(text, rel_tol).map_err(|e| JsError::new(&e))?;
|
||||
serde_json::to_string(&meshes).map_err(|e| JsError::new(&e.to_string()))
|
||||
Ok(brep::step_meshes_flat(&meshes))
|
||||
}
|
||||
|
||||
/// Boolesche Operation zwischen zwei Dreiecks-Meshes (Mesh-Ebenen-CSG via
|
||||
|
||||
+7
-3
@@ -54,7 +54,7 @@ import { UnsavedChangesDialog } from "./ui/UnsavedChangesDialog";
|
||||
import { RecoverAutosaveDialog } from "./ui/RecoverAutosaveDialog";
|
||||
import { Toast } from "./ui/Toast";
|
||||
import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./native/projectFile";
|
||||
import { stepTextToImportedMeshes } from "./io/stepImport";
|
||||
import { readStepFlat } from "./engine/truckSolid";
|
||||
import { formatIfcElementsSummary, formatIfcReport, readIfcFlat } from "./io/ifcImport";
|
||||
import { IfcImportDialog, type IfcImportMode } from "./ui/IfcImportDialog";
|
||||
import { MeshImportHost } from "./ui/MeshImportDialog";
|
||||
@@ -3288,8 +3288,12 @@ export default function App() {
|
||||
if (!f) return;
|
||||
void f
|
||||
.text()
|
||||
.then((text) => stepTextToImportedMeshes(text, f.name))
|
||||
.then((objs) => addContextObjectsAndFit(objs))
|
||||
.then((text) => readStepFlat(text))
|
||||
.then((flat) => {
|
||||
// Der Kern macht je Körper ein Kontext-Mesh und übernimmt sie als EINEN Undo-Schritt ([K4] S4).
|
||||
const r = getState().commitImport((doc, base, now) => doc.importStep(base, flat, { fileName: f.name }, now));
|
||||
if (r) fitToContextObjects(addedItems(r.ops, "context") as ContextObject[]);
|
||||
})
|
||||
.catch((err) =>
|
||||
notify(`${t("step.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"),
|
||||
);
|
||||
|
||||
@@ -388,6 +388,11 @@ export class ProjectDocument {
|
||||
);
|
||||
}
|
||||
|
||||
/** STEP-Import (truck → Kern, [K4] S4): ein Kontext-Mesh je Körper, ein Undo-Schritt. */
|
||||
importStep(base: Project, flat: Float64Array, opts: { fileName: string }, now: number) {
|
||||
return this.commitCore<{ contextObjects: number }>(base, (h) => core().doc_import_step(h, flat, JSON.stringify(opts), "", now));
|
||||
}
|
||||
|
||||
/** Abfrage eines Befehls zwischen den Schritten (`doc_cmd_query`: Treffer, Vorschau-Formen), JSON-Antwort. */
|
||||
cmdQuery<T>(req: object): T {
|
||||
if (!this.handle) throw new Error("Kern-Abfrage „cmdQuery“: Dokument nicht offen");
|
||||
|
||||
@@ -15,6 +15,19 @@ function combineSolids(project: typeof sampleProject, a: ExtrudedSolid, b: Extru
|
||||
import { extrudedSolidSpec } from "../plan/extrudedSolidSpec";
|
||||
import type { ExtrudedSolid } from "../model/types";
|
||||
|
||||
/** Flacher STEP-Puffer von truck (`[1, n, (np, ni, Positionen…, Indizes…)…]`) → Körper. */
|
||||
function stepBodies(f: Float64Array): Array<{ positions: number[]; indices: number[] }> {
|
||||
const out: Array<{ positions: number[]; indices: number[] }> = [];
|
||||
let at = 2;
|
||||
for (let k = 0; k < f[1]; k++) {
|
||||
const [np, ni] = [f[at], f[at + 1]];
|
||||
at += 2;
|
||||
out.push({ positions: Array.from(f.subarray(at, at + np)), indices: Array.from(f.subarray(at + np, at + np + ni)) });
|
||||
at += np + ni;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
let mod: any;
|
||||
beforeAll(async () => {
|
||||
mod = await import("./pkgTruck/trucksolid.js");
|
||||
@@ -78,7 +91,7 @@ describe("trucksolid-WASM", () => {
|
||||
const wall = { kind: "extrudePlane", points: [0, 0, 5, 0, 5, 2.6, 0, 2.6], holes: [[1, 0.9, 2.2, 0.9, 2.2, 2.1, 1, 2.1]], origin: [0, 0, 0], uAxis: [1, 0, 0], vAxis: [0, 0, 1], depth: -0.3 };
|
||||
const cyl = { kind: "cylinder", cx: 10, cy: 0, z0: 0, r: 1, height: 2 };
|
||||
const step: string = mod.export_step(JSON.stringify({ solids: [wall, cyl], fileName: "t.stp" }));
|
||||
const back = JSON.parse(mod.import_step(step, 0.0005)) as Array<{ positions: number[]; indices: number[] }>;
|
||||
const back = stepBodies(mod.import_step_flat(step, 0.0005));
|
||||
expect(back).toHaveLength(2);
|
||||
const vols = back.map(volume).sort((a, b) => a - b);
|
||||
expect(vols[0]).toBeCloseTo((5 * 2.6 - 1.2 * 1.2) * 0.3, 1); // Wand
|
||||
|
||||
@@ -163,7 +163,10 @@ export async function exportStepSolids(
|
||||
return guarded((m) => m.export_step(JSON.stringify({ solids, fileName, organizationSystem: "dossier" })));
|
||||
}
|
||||
|
||||
/** Liest STEP-Text und liefert je Körper ein Dreiecks-Mesh (`relTol` relativ zur Diagonale). */
|
||||
export async function importStepMeshes(text: string, relTol = 0.0005): Promise<ExtrudedMesh[]> {
|
||||
return JSON.parse(await guarded((m) => m.import_step(text, relTol))) as ExtrudedMesh[];
|
||||
/**
|
||||
* Liest STEP-Text und liefert die tessellierten Körper als flachen Puffer für den Kern
|
||||
* (`ProjectDocument.importStep`; Aufbau `trucksolid::brep::step_meshes_flat`). `relTol` relativ zur Diagonale.
|
||||
*/
|
||||
export async function readStepFlat(text: string, relTol = 0.0005): Promise<Float64Array> {
|
||||
return guarded((m) => m.import_step_flat(text, relTol));
|
||||
}
|
||||
@@ -3,6 +3,19 @@ import { readFileSync } from "node:fs";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { projectSolidSpecs, wallProfile } from "./exportStep";
|
||||
|
||||
/** Flacher STEP-Puffer von truck (`[1, n, (np, ni, Positionen…, Indizes…)…]`) → Körper. */
|
||||
function stepBodies(f: Float64Array): Array<{ positions: number[]; indices: number[] }> {
|
||||
const out: Array<{ positions: number[]; indices: number[] }> = [];
|
||||
let at = 2;
|
||||
for (let k = 0; k < f[1]; k++) {
|
||||
const [np, ni] = [f[at], f[at + 1]];
|
||||
at += 2;
|
||||
out.push({ positions: Array.from(f.subarray(at, at + np)), indices: Array.from(f.subarray(at + np, at + np + ni)) });
|
||||
at += np + ni;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("wallProfile", () => {
|
||||
it("Fenster im Inneren wird zum Loch, Tür am Wandfuss zur Kerbe im Aussenring", () => {
|
||||
const p = wallProfile(5, 2.6, [
|
||||
@@ -46,7 +59,7 @@ describe("STEP-Export Ende-zu-Ende (truck-WASM)", () => {
|
||||
const specs = projectSolidSpecs(sampleProject);
|
||||
const step: string = mod.export_step(JSON.stringify({ solids: specs, fileName: "demo.stp" }));
|
||||
expect(step.startsWith("ISO-10303-21;")).toBe(true);
|
||||
const back = JSON.parse(mod.import_step(step, 0.002)) as Array<{ positions: number[]; indices: number[] }>;
|
||||
const back = stepBodies(mod.import_step_flat(step, 0.002));
|
||||
expect(back.length).toBeGreaterThan(5);
|
||||
expect(back.every((m) => m.indices.length >= 12)).toBe(true);
|
||||
}, 60_000);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// STEP-Import Ende-zu-Ende: truck liest (flacher Puffer) → der Kern macht Kontext-Meshes, ein Undo-Schritt.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { documentFor } from "../core/document";
|
||||
import type { ImportedMesh, Project } from "../model/types";
|
||||
|
||||
const STEP_BOX = (x0: number, y0: number, z0: number, x1: number, y1: number, z1: number) => ({
|
||||
kind: "cuboid",
|
||||
min: [x0, y0, z0],
|
||||
max: [x1, y1, z1],
|
||||
});
|
||||
|
||||
const stripCode10 = (ls: Project["layers"]): Project["layers"] =>
|
||||
ls.filter((l) => l.code !== "10").map((l) => (l.children ? { ...l, children: stripCode10(l.children) } : l));
|
||||
|
||||
describe("STEP-Import im Kern", () => {
|
||||
it("zwei Körper → zwei Kontext-Meshes, Kategorie ergänzt, ein Undo-Schritt", async () => {
|
||||
const mod: any = await import("../engine/pkgTruck/trucksolid.js");
|
||||
await mod.default({ module_or_path: readFileSync("src/engine/pkgTruck/trucksolid_bg.wasm") });
|
||||
const step: string = mod.export_step(
|
||||
JSON.stringify({ solids: [STEP_BOX(0, 0, 0, 2, 1, 3), STEP_BOX(5, 0, 0, 6, 1, 1)], fileName: "k.stp" }),
|
||||
);
|
||||
const flat: Float64Array = mod.import_step_flat(step, 0.0005);
|
||||
|
||||
const base = { ...sampleProject, context: undefined, layers: stripCode10(sampleProject.layers) };
|
||||
const doc = documentFor(base);
|
||||
const r = doc.importStep(base, flat, { fileName: "Haus.stp" }, 1.7e12);
|
||||
expect("problems" in r).toBe(false);
|
||||
if ("problems" in r) return;
|
||||
expect(r.contextObjects).toBe(2);
|
||||
const ctx = (r.project.context ?? []) as ImportedMesh[];
|
||||
expect(ctx.map((m) => m.name)).toEqual(["Haus (1/2)", "Haus (2/2)"]);
|
||||
expect(ctx.every((m) => m.categoryCode === "10" && m.id.startsWith("imported-step-"))).toBe(true);
|
||||
expect(ctx[0].indices.length).toBe(36);
|
||||
expect(Math.max(...ctx[0].positions.filter((_, i) => i % 3 === 0))).toBeCloseTo(2, 5);
|
||||
expect(JSON.stringify(r.project.layers)).toContain('"code":"10"');
|
||||
expect(JSON.stringify(base.layers)).not.toContain('"code":"10"');
|
||||
// ein Undo-Schritt stellt das Projekt wieder her
|
||||
expect(doc.historyState().undo).toBe(1);
|
||||
const back = doc.undo(r.project);
|
||||
expect(back?.context ?? []).toEqual([]);
|
||||
expect(back?.layers).toEqual(base.layers);
|
||||
}, 120_000);
|
||||
|
||||
it("kaputter Puffer wird abgewiesen", () => {
|
||||
const doc = documentFor(sampleProject);
|
||||
expect(() => doc.importStep(sampleProject, new Float64Array([1, 3]), { fileName: "x.stp" }, 1)).toThrow(/Puffer/);
|
||||
});
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
// STEP-Import (ISO 10303-42 B-Rep) über truck-stepio: jede Shell der Datei wird zu einem
|
||||
// tessellierten `ImportedMesh` des Kontexts (Kategorie „Import"), anwählbar wie jeder
|
||||
// andere importierte Körper. Koordinaten bleiben unverändert (Meter, Z = Höhe).
|
||||
|
||||
import { importStepMeshes } from "../engine/truckSolid";
|
||||
import { GENERIC_IMPORT_CATEGORY } from "../model/contextCategories";
|
||||
import type { ImportedMesh } from "../model/types";
|
||||
|
||||
let counter = 0;
|
||||
|
||||
/** Liest STEP-Text → ein `ImportedMesh` je Körper. Wirft bei unlesbarer Datei. */
|
||||
export async function stepTextToImportedMeshes(text: string, fileName: string): Promise<ImportedMesh[]> {
|
||||
const base = fileName.replace(/\.[^.]+$/, "") || "STEP";
|
||||
const meshes = await importStepMeshes(text);
|
||||
const stamp = Date.now().toString(36);
|
||||
return meshes.map((m, i) => ({
|
||||
id: `imported-step-${stamp}-${counter++}`,
|
||||
type: "importedMesh" as const,
|
||||
name: meshes.length > 1 ? `${base} (${i + 1}/${meshes.length})` : base,
|
||||
categoryCode: GENERIC_IMPORT_CATEGORY.code,
|
||||
positions: m.positions,
|
||||
indices: m.indices,
|
||||
}));
|
||||
}
|
||||
Reference in new issue
Block a user