[K4] Projekt-Verschiebung und Auswahl-Export im Kern: translateProject/translateOps, filterProjectToSelection (geo_translate.rs, selection_filter.rs)

Wurzel-Abfragen translatePatch/translateOps/selectionFilterPatch; TS-Rechnung in geoRebase.ts und exportScope.ts gelöscht.
This commit is contained in:
Claude committed 2026-10-29 07:04:16 +00:00
1 parent a69a79284c
commit 1987bade3a
8 files changed
+397 -174

No files matched your search

+10 -2
View File
@@ -274,8 +274,8 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
0 Befunde, glTF-Validator über 390 GLB/glTF 0 Fehler (nach [C11]-Korrektur der leeren Szene). Messung (Node,
Linux-Container, `--no-opt`-WASM, bigSample(20)): IFC 82,5 s → 2,4 s, GLB 212 s → 1,9 s; Beispielprojekt IFC
11 → 4 ms, GLB 15 → 2,5 ms (vorher je Bauteil ein eigenes Kern-Dokument aus dem ganzen Projekt-JSON). Nicht in
der Tauri-App geprüft (e2e im Browser: IFC-Export grün). Bleibt: DXF-Sammler (`exportDxf.ts`), STEP (truck) und
die Modell-Verschiebung `translateProject` in TS (Befehl „Neuer Bezugspunkt“, DXF).
der Tauri-App geprüft (e2e im Browser: IFC-Export grün). Bleibt: DXF-Sammler (`exportDxf.ts`) und STEP (truck);
die Modell-Verschiebung `translateProject` liegt seit 29.10. im Kern (s. S3).
Nächste: Export (Schedule/CSV, STL/OBJ, STEP), Plan/Schnitt/Ansicht-Sammler (generatePlan, toSection, toElevation) — hängt an Plan-Puffer v2.
Grundriss (28.10.): Decken, Dächer, Räume, Wände+Öffnungen, Treppen, Stützen, Extrusionen, Kontext und Schnittlinien
kommen über `planDomains` aus dem Dokument ([K3d]); seit 29.10. auch die 2D-Zeichnungen (`plan/drawings.rs`); übrig in
@@ -452,6 +452,14 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
vorhanden/fehlend, fehlende/negative/0-Abstände, Toleranz 0/0,01/0,5) und 4000 Einzel-Regeln/Bedingungen/Duplikat-Listen,
Wand-ids samt Zähler gleich, Ergebnis zeichengleich bis auf die Schlüsselreihenfolge von Wänden mit `wallTypeId: undefined`.
Abweichung (gewollt): Achsen je Aufruf auf 1 000 000 begrenzt (TS rechnete bei absurd kleinem Abstand endlos).
**Projekt-Verschiebung und Auswahl-Export im Kern (29.10.):** `geo_translate.rs` (`translateProject`/`translateOps` aus
`model/geoRebase.ts`: Translation aller Modell-Koordinaten inkl. Kontext, Zeichnungen, Geo-Anker; Befehl „Neuer
Bezugspunkt“, `projectToWorldCoords` für DXF/IFC-Welt-Koordinaten) und `selection_filter.rs` (`filterProjectToSelection`
aus `state/exportScope.ts`: Export „nur Auswahl“), beide als Wurzel-Abfragen (`translatePatch`/`translateOps`/
`selectionFilterPatch`); die Fassaden setzen `{...project, ...patch}` zusammen, `projectGeoOrigin` (Einzeiler) bleibt in TS.
Gleichheit (einmalig, Test gelöscht): 3000 Zufallsprojekte mit allen Elementarten, allen 18 Zeichnungs-Formen, Kontext
(Mesh/Terrain/Bild/Konturen mit Bogen), Geo-Anker, Verschiebung (0,0) — Projekt, Ops und Welt-Koordinaten
zeichengleich; 5000 Auswahl-Filter (doppelte ids, fehlende Listen).
- ◐ **S4 Typen aus Rust**: `types.ts` wird aus den Rust-Strukturen erzeugt (ts-rs); Datei-I/O (`projectFormat`, Migration, IFC/DXF/
STEP-Ex- und -Import) im Kern.
**Typen (28.10.):** Das Rust-Modell (`core/src/model/generated.rs`, `manual.rs`) ist die Quelle; ts-rs 12 (MIT, nur
+293
View File
@@ -0,0 +1,293 @@
//! Verschiebung des ganzen Projekts um einen festen Vektor ([K4] S3, vorher `translateProject` in
//! `src/model/geoRebase.ts`; Befehl „Neuer Bezugspunkt", Welt-Koordinaten für DXF/IFC-Export): reine
//! Translation aller Modell-Koordinaten (Wände, Decken, Dächer, Treppen, Räume, Stützen, Extrusionen,
//! 2D-Zeichnungen, Kontext-Schicht, Schnitt-/Ansichtslinien, Geo-Anker). Richtungsvektoren und Winkel
//! bleiben, Höhen (z) auch. Rechnung auf der rohen Projekt-Wurzel (`serde_json`).
//!
//! Wie in TS bestehen verschobene Punkte nur aus `x`/`y` (weitere Felder eines Punkts entfallen).
use serde_json::{json, Map, Value};
/// Projekt-Listen, die verschoben werden (jedes Element hat eine `id`), in Op-Reihenfolge.
pub const TRANSLATED_LISTS: [&str; 10] = ["walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels"];
fn shift(p: &Value, dx: f64, dy: f64) -> Value {
let c = |k: &str| p.get(k).and_then(Value::as_f64).unwrap_or(f64::NAN);
json!({"x": c("x") + dx, "y": c("y") + dy})
}
fn shift_all(v: Option<&Value>, dx: f64, dy: f64) -> Value {
Value::Array(v.and_then(Value::as_array).map(|a| a.iter().map(|p| shift(p, dx, dy)).collect()).unwrap_or_default())
}
fn truthy(v: Option<&Value>) -> bool {
match v {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0 && !f.is_nan()),
Some(Value::String(s)) => !s.is_empty(),
Some(_) => true,
}
}
/// `{...m, key: v}` — ein vorhandener Schlüssel behält seine Stelle; `None` = `undefined` (Feld entfällt).
fn set(m: &mut Map<String, Value>, key: &str, v: Option<Value>) {
match v {
Some(v) => {
m.insert(key.to_string(), v);
}
None => {
m.shift_remove(key);
}
}
}
fn obj(v: &Value) -> Map<String, Value> {
v.as_object().cloned().unwrap_or_default()
}
/// Felder `keys` (je ein Punkt) einer Geometrie verschieben.
fn shift_pts_fields(g: &mut Map<String, Value>, keys: &[&str], dx: f64, dy: f64, lists: &[&str]) {
for k in keys {
if let Some(p) = g.get(*k) {
let n = shift(p, dx, dy);
g.insert((*k).to_string(), n);
}
}
for k in lists {
if g.contains_key(*k) {
let n = shift_all(g.get(*k), dx, dy);
g.insert((*k).to_string(), n);
}
}
}
/// Geometrie einer 2D-Zeichnung verschieben (`switch (g.shape)`).
fn shift_geom(g: &Value, dx: f64, dy: f64) -> Value {
let mut m = obj(g);
match g.get("shape").and_then(Value::as_str).unwrap_or("") {
"line" | "xline" | "ray" => shift_pts_fields(&mut m, &["a", "b"], dx, dy, &[]),
"polyline" | "bezier" | "spline" | "dimension" => shift_pts_fields(&mut m, &[], dx, dy, &["pts"]),
"rect" | "image" => shift_pts_fields(&mut m, &["min", "max"], dx, dy, &[]),
"circle" | "arc" | "ellipse" => shift_pts_fields(&mut m, &["center"], dx, dy, &[]),
"kote" | "detailref" | "scalebar" | "pointmarker" | "block" => shift_pts_fields(&mut m, &["at"], dx, dy, &[]),
"text" => {
shift_pts_fields(&mut m, &["at"], dx, dy, &[]);
if truthy(g.get("leaderTarget")) {
shift_pts_fields(&mut m, &["leaderTarget"], dx, dy, &[]);
}
for k in ["leaderBendPoints", "pathPts"] {
if truthy(g.get(k)) {
shift_pts_fields(&mut m, &[], dx, dy, &[k]);
}
}
}
_ => {}
}
Value::Object(m)
}
/// Kontur: Punkte und Mitte eines Kreisbogens (`curve.cx/cy`).
fn shift_contour(c: &Value, dx: f64, dy: f64) -> Value {
let mut m = obj(c);
set(&mut m, "pts", Some(shift_all(c.get("pts"), dx, dy)));
let curve = if truthy(c.get("curve")) {
let mut cv = obj(&c["curve"]);
let n = |k: &str, d: f64| cv.get(k).and_then(Value::as_f64).map_or(f64::NAN, |v| v + d);
let (cx, cy) = (n("cx", dx), n("cy", dy));
cv.insert("cx".into(), json!(cx));
cv.insert("cy".into(), json!(cy));
Some(Value::Object(cv))
} else {
None
};
set(&mut m, "curve", curve);
Value::Object(m)
}
/// Kontext-Objekt: Konturen-Satz, Bild (min/max) oder Mesh (`positions` = flache `[x, y, z]`-Tripel, nur x/y).
fn shift_context(o: &Value, dx: f64, dy: f64) -> Value {
let mut m = obj(o);
match o.get("type").and_then(Value::as_str) {
Some("contourSet") => {
let cs: Vec<Value> = o.get("contours").and_then(Value::as_array).map(|a| a.iter().map(|c| shift_contour(c, dx, dy)).collect()).unwrap_or_default();
set(&mut m, "contours", Some(Value::Array(cs)));
}
Some("image") => shift_pts_fields(&mut m, &["min", "max"], dx, dy, &[]),
_ => {
let mut pos: Vec<Value> = o.get("positions").and_then(Value::as_array).cloned().unwrap_or_default();
let mut i = 0;
while i + 2 < pos.len() {
let a = pos[i].as_f64().unwrap_or(f64::NAN) + dx;
let b = pos[i + 1].as_f64().unwrap_or(f64::NAN) + dy;
pos[i] = json!(a);
pos[i + 1] = json!(b);
i += 3;
}
set(&mut m, "positions", Some(Value::Array(pos)));
}
}
Value::Object(m)
}
/// Ein Listen-Element verschieben; `false` = unverändert (nur Zeichenebenen ohne `linePoints`).
fn shift_element(key: &str, e: &Value, dx: f64, dy: f64) -> (Value, bool) {
let mut m = obj(e);
match key {
"walls" => shift_pts_fields(&mut m, &["start", "end"], dx, dy, &[]),
"ceilings" => {
shift_pts_fields(&mut m, &[], dx, dy, &["outline"]);
if let Some(h) = e.get("openings").and_then(Value::as_array) {
let n: Vec<Value> = h.iter().map(|h| shift_all(Some(h), dx, dy)).collect();
m.insert("openings".into(), Value::Array(n));
}
}
"roofs" => {
shift_pts_fields(&mut m, &[], dx, dy, &["outline"]);
if truthy(e.get("holes")) {
if let Some(h) = e.get("holes").and_then(Value::as_array) {
let n: Vec<Value> = h.iter().map(|h| shift_all(Some(h), dx, dy)).collect();
m.insert("holes".into(), Value::Array(n));
}
}
}
"stairs" => {
shift_pts_fields(&mut m, &["start"], dx, dy, &[]);
let c = if truthy(e.get("center")) { Some(shift(&e["center"], dx, dy)) } else { None };
set(&mut m, "center", c);
}
"rooms" => {
shift_pts_fields(&mut m, &[], dx, dy, &["boundary"]);
let c = if truthy(e.get("stampAnchor")) { Some(shift(&e["stampAnchor"], dx, dy)) } else { None };
set(&mut m, "stampAnchor", c);
}
"columns" => shift_pts_fields(&mut m, &["position"], dx, dy, &[]),
"extrudedSolids" => {
shift_pts_fields(&mut m, &[], dx, dy, &["points"]);
let c = if truthy(e.get("circle")) {
let mut c = obj(&e["circle"]);
let n = shift(c.get("center").unwrap_or(&Value::Null), dx, dy);
c.insert("center".into(), n);
Some(Value::Object(c))
} else {
None
};
set(&mut m, "circle", c);
}
"drawings2d" => {
let g = shift_geom(e.get("geom").unwrap_or(&Value::Null), dx, dy);
m.insert("geom".into(), g);
}
"context" => return (shift_context(e, dx, dy), true),
"drawingLevels" => {
let lp = e.get("linePoints").and_then(Value::as_array).filter(|a| !a.is_empty());
return match lp {
Some(a) if truthy(e.get("linePoints")) => {
let n = vec![shift(&a[0], dx, dy), shift(a.get(1).unwrap_or(&Value::Null), dx, dy)];
m.insert("linePoints".into(), Value::Array(n));
(Value::Object(m), true)
}
_ => (e.clone(), false),
};
}
_ => {}
}
(Value::Object(m), true)
}
/// Verschobene Listen und Geo-Anker (nur Schlüssel, die es im Projekt gibt); `None` bei `dx = dy = 0`
/// (nichts zu tun). Jedes Element mit Änderungs-Kennzeichen (`false`: dasselbe Element wie vorher).
pub fn translate(root: &Map<String, Value>, dx: f64, dy: f64) -> Option<Vec<(&'static str, Vec<(Value, bool)>)>> {
if dx == 0.0 && dy == 0.0 {
return None;
}
Some(
TRANSLATED_LISTS
.iter()
.filter_map(|key| root.get(*key).and_then(Value::as_array).map(|a| (*key, a.iter().map(|e| shift_element(key, e, dx, dy)).collect())))
.collect(),
)
}
/// Geo-Anker verschoben (`geoAnchor.model`), `None` ohne Anker.
pub fn translate_anchor(root: &Map<String, Value>, dx: f64, dy: f64) -> Option<Value> {
let a = root.get("geoAnchor").filter(|v| truthy(Some(v)))?;
let mut m = obj(a);
m.insert("model".into(), shift(a.get("model").unwrap_or(&Value::Null), dx, dy));
Some(Value::Object(m))
}
/// Patch für `{...project, ...patch}`: verschobene Listen und Geo-Anker (`translateProject`). Leer bei `dx = dy = 0`.
pub fn project_patch(root: &Map<String, Value>, dx: f64, dy: f64) -> Map<String, Value> {
let mut out = Map::new();
let Some(lists) = translate(root, dx, dy) else { return out };
for (key, els) in lists {
out.insert(key.to_string(), Value::Array(els.into_iter().map(|(v, _)| v).collect()));
}
if let Some(a) = translate_anchor(root, dx, dy) {
out.insert("geoAnchor".into(), a);
}
out
}
/// Ops für die Verschiebung (`translateOps`): je geändertem Element ein `replace` (Listen-Reihenfolge), der Geo-Anker als Feld.
pub fn translate_ops(root: &Map<String, Value>, dx: f64, dy: f64) -> Vec<Value> {
let mut ops = Vec::new();
let Some(lists) = translate(root, dx, dy) else { return ops };
for (key, els) in lists {
for (v, changed) in els {
if changed {
ops.push(json!({"kind": "replace", "collection": key, "entity": v}));
}
}
}
if let Some(a) = translate_anchor(root, dx, dy) {
ops.push(json!({"kind": "setField", "key": "geoAnchor", "value": a}));
}
ops
}
#[cfg(test)]
mod tests {
use super::*;
fn root(v: Value) -> Map<String, Value> {
v.as_object().unwrap().clone()
}
#[test]
fn verschiebt_alles_und_laesst_hoehen() {
let p = root(json!({
"walls": [{"id": "w", "start": {"x": 1, "y": 2}, "end": {"x": 3, "y": 4}, "height": 2.6}],
"stairs": [{"id": "s", "start": {"x": 0, "y": 0}, "dir": {"x": 1, "y": 0}}],
"drawings2d": [{"id": "d", "geom": {"shape": "text", "at": {"x": 1, "y": 1}, "leaderTarget": {"x": 2, "y": 2}, "pathPts": [{"x": 5, "y": 5}]}}],
"context": [{"id": "c", "type": "terrainMesh", "positions": [1, 2, 9, 4, 5, 8, 7]}, {"id": "i", "type": "image", "min": {"x": 0, "y": 0}, "max": {"x": 1, "y": 1}}],
"drawingLevels": [{"id": "l1"}, {"id": "l2", "linePoints": [{"x": 0, "y": 0}, {"x": 1, "y": 1}]}],
"geoAnchor": {"lv95": {"e": 1, "n": 2}, "model": {"x": 5, "y": 6}},
}));
let patch = project_patch(&p, 10.0, -1.0);
assert_eq!(patch["walls"][0]["start"], json!({"x": 11.0, "y": 1.0}));
assert_eq!(patch["walls"][0]["height"], 2.6);
assert_eq!(patch["stairs"][0]["dir"], json!({"x": 1, "y": 0}));
assert!(patch["stairs"][0].get("center").is_none());
assert_eq!(patch["drawings2d"][0]["geom"]["leaderTarget"], json!({"x": 12.0, "y": 1.0}));
assert_eq!(patch["drawings2d"][0]["geom"]["pathPts"][0], json!({"x": 15.0, "y": 4.0}));
assert_eq!(patch["context"][0]["positions"], json!([11.0, 1.0, 9, 14.0, 4.0, 8, 7]));
assert_eq!(patch["context"][1]["max"], json!({"x": 11.0, "y": 0.0}));
assert_eq!(patch["geoAnchor"]["model"], json!({"x": 15.0, "y": 5.0}));
assert_eq!(patch["geoAnchor"]["lv95"], json!({"e": 1, "n": 2}));
assert!(project_patch(&p, 0.0, 0.0).is_empty());
}
#[test]
fn ops_ohne_unveraenderte_ebenen() {
let p = root(json!({
"walls": [{"id": "w", "start": {"x": 0, "y": 0}, "end": {"x": 1, "y": 0}}],
"drawingLevels": [{"id": "l1"}, {"id": "l2", "linePoints": [{"x": 0, "y": 0}, {"x": 1, "y": 1}]}],
}));
let ops = translate_ops(&p, 1.0, 1.0);
let ids: Vec<&str> = ops.iter().map(|o| o["entity"]["id"].as_str().unwrap()).collect();
assert_eq!(ids, vec!["w", "l2"]);
assert!(translate_ops(&p, 0.0, 0.0).is_empty());
}
}
+2
View File
@@ -78,6 +78,8 @@ pub mod pens;
pub mod folder_tree;
pub mod layout_model;
pub mod parametric_walls;
pub mod geo_translate;
pub mod selection_filter;
#[cfg(feature = "web")]
mod web;
+15
View File
@@ -83,6 +83,21 @@ pub fn run_root(root: &serde_json::Map<String, serde_json::Value>, name: &str, t
let a: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("layoutTitleBlock: {e}"))?;
json(&crate::layout_model::resolve_title_block(root, &a["layout"], &a["master"], a["today"].as_str().unwrap_or("")))
}
// Verschiebung des Projekts ([K4] S3, `geo_translate.rs`): `text` = JSON `[dx, dy]`; `translatePatch` liefert
// die verschobenen Listen + Geo-Anker (für `{...project, ...patch}`), `translateOps` die Ops dazu.
"translatePatch" | "translateOps" => {
let [dx, dy]: [f64; 2] = serde_json::from_str(text).map_err(|e| format!("{name}: {e}"))?;
if name == "translatePatch" {
json(&crate::geo_translate::project_patch(root, dx, dy))
} else {
json(&crate::geo_translate::translate_ops(root, dx, dy))
}
}
// Export-Scope „nur Auswahl" ([K4] S3, `selection_filter.rs`): `text` = JSON der ids je Art (`GroupMembership`).
"selectionFilterPatch" => {
let m: crate::groups::Membership = serde_json::from_str(text).map_err(|e| format!("selectionFilterPatch: {e}"))?;
json(&crate::selection_filter::filter_patch(root, &m))
}
_ => Err(format!("Unbekannte Wurzel-Abfrage: {name}")),
}
}
+59
View File
@@ -0,0 +1,59 @@
//! Export-Scope „nur Auswahl" ([K4] S3, vorher `filterProjectToSelection` in `src/state/exportScope.ts`):
//! die Listen der acht Elementarten auf die ausgewählten ids kürzen (jede Art ohne Eintrag wird leer);
//! Bibliotheken, Ebenen und Geschosse bleiben, damit id-Verweise weiter auflösen. Liefert die gekürzten
//! Listen als Patch für `{...project, ...patch}`.
use crate::groups::Membership;
use serde_json::{Map, Value};
use std::collections::HashSet;
/// Projekt-Liste → (Mitglieds-ids der Art).
const KINDS: [(&str, &str); 8] = [
("walls", "wallIds"),
("drawings2d", "drawingIds"),
("ceilings", "ceilingIds"),
("rooms", "roomIds"),
("stairs", "stairIds"),
("columns", "columnIds"),
("roofs", "roofIds"),
("openings", "openingIds"),
];
/// Gekürzte Listen (alle acht Schlüssel, fehlende Listen = leer); Elemente in Listen-Reihenfolge, auch Doppelte.
pub fn filter_patch(root: &Map<String, Value>, members: &Membership) -> Map<String, Value> {
let mut out = Map::new();
for (key, kind) in KINDS {
let ids: HashSet<&str> = members.list(kind).map(|l| l.iter().map(String::as_str).collect()).unwrap_or_default();
let kept: Vec<Value> = root
.get(key)
.and_then(Value::as_array)
.map(|a| a.iter().filter(|e| e.get("id").and_then(Value::as_str).is_some_and(|id| ids.contains(id))).cloned().collect())
.unwrap_or_default();
out.insert(key.to_string(), Value::Array(kept));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn nur_ausgewaehlte_bleiben() {
let root = json!({
"walls": [{"id": "a"}, {"id": "b"}, {"id": "a"}],
"rooms": [{"id": "r"}],
"drawings2d": [{"id": "d"}],
"layers": [{"code": "20"}],
});
let m = Membership { wall_ids: vec!["a".into()], ..Default::default() };
let p = filter_patch(root.as_object().unwrap(), &m);
assert_eq!(p["walls"], json!([{"id": "a"}, {"id": "a"}]));
assert_eq!(p["rooms"], json!([]));
assert_eq!(p["drawings2d"], json!([]));
assert_eq!(p["roofs"], json!([]));
assert_eq!(p.len(), 8);
assert!(p.get("layers").is_none());
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ export type LoadFileResult =
| { ok: false; error: string };
/** Wurzel-Abfragen des Kerns (`queries.rs::run_root`). */
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "folderPdfPages" | "layoutTitleBlock";
export type RootQueryName = "penRebakeOps" | "penDeleteOps" | "penSeedOps" | "folderPdfPages" | "layoutTitleBlock" | "translatePatch" | "translateOps" | "selectionFilterPatch";
/** Abfragen des Kerns (`queries.rs`). */
export type QueryName =
+11 -149
View File
@@ -12,48 +12,14 @@
// (Column.rotation, Text-/Bild-Rotation, Tür-Schwenk) müssten bei einer Drehung
// mitgeführt werden — eine Rotation ist ein eigener, grösserer Schritt.
//
// Die Rechnung liegt im Rust-Kern ([K4] S3, `src-tauri/core/src/geo_translate.rs`, Wurzel-Abfragen
// `translatePatch`/`translateOps`); hier bleiben die Fassaden und der Ursprung aus dem Geo-Anker.
//
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import { replaceItem, setField } from "../core/opsBuild";
import type { CoreOp } from "../core/ops";
import type {
ContextObject,
Contour,
Project,
Vec2,
} from "./types";
const shift = (p: Vec2, dx: number, dy: number): Vec2 => ({ x: p.x + dx, y: p.y + dy });
const shiftAll = (pts: Vec2[], dx: number, dy: number): Vec2[] => pts.map((p) => shift(p, dx, dy));
/** Kontur (Höhenlinie): Punkte + optionale Kreis-/Bogen-Mitte verschieben. */
function shiftContour(c: Contour, dx: number, dy: number): Contour {
return {
...c,
pts: shiftAll(c.pts, dx, dy),
curve: c.curve ? { ...c.curve, cx: c.curve.cx + dx, cy: c.curve.cy + dy } : undefined,
};
}
/**
* Kontext-Objekt (importiertes Mesh/Terrain/Konturen-Satz) verschieben.
* `positions` ist ein flaches [x,y,z=Höhe, …]-Array — nur x/y (Grundriss)
* verschieben, die Höhe (z) bleibt unverändert.
*/
function shiftContextObject(obj: ContextObject, dx: number, dy: number): ContextObject {
if (obj.type === "contourSet") {
return { ...obj, contours: obj.contours.map((c) => shiftContour(c, dx, dy)) };
}
if (obj.type === "image") {
return { ...obj, min: shift(obj.min, dx, dy), max: shift(obj.max, dx, dy) };
}
const positions = obj.positions.slice();
for (let i = 0; i + 2 < positions.length; i += 3) {
positions[i] += dx;
positions[i + 1] += dy;
}
return { ...obj, positions };
}
import { documentFor } from "../core/document";
import type { Project } from "./types";
/**
* Verschiebt SÄMTLICHE Modell-Koordinaten eines Projekts um den festen Vektor
@@ -62,127 +28,23 @@ function shiftContextObject(obj: ContextObject, dx: number, dy: number): Context
* (Import/Terrain/Konturen), Schnitt-/Ansichtslinien sowie den Geo-Anker
* (`geoAnchor.model`, damit der LV95-Bezug exakt erhalten bleibt). Richtungs-
* Vektoren (z. B. `Stair.dir`) und Winkel-Felder bleiben unangetastet — eine
* reine Translation ändert keine Orientierung.
* reine Translation ändert keine Orientierung. Unveränderte Teile behalten ihre Identität;
* (0,0) liefert das Projekt selbst.
*/
export function translateProject(project: Project, dx: number, dy: number): Project {
if (dx === 0 && dy === 0) return project;
return {
...project,
walls: project.walls.map((w) => ({
...w,
start: shift(w.start, dx, dy),
end: shift(w.end, dx, dy),
})),
ceilings: project.ceilings?.map((c) => ({
...c,
outline: shiftAll(c.outline, dx, dy),
openings: c.openings?.map((h) => shiftAll(h, dx, dy)),
})),
roofs: project.roofs?.map((r) => ({
...r,
outline: shiftAll(r.outline, dx, dy),
...(r.holes ? { holes: r.holes.map((h) => shiftAll(h, dx, dy)) } : {}),
})),
stairs: project.stairs?.map((s) => ({
...s,
start: shift(s.start, dx, dy),
center: s.center ? shift(s.center, dx, dy) : undefined,
})),
rooms: project.rooms?.map((r) => ({
...r,
boundary: shiftAll(r.boundary, dx, dy),
stampAnchor: r.stampAnchor ? shift(r.stampAnchor, dx, dy) : undefined,
})),
columns: project.columns?.map((c) => ({ ...c, position: shift(c.position, dx, dy) })),
extrudedSolids: project.extrudedSolids?.map((s) => ({
...s,
points: shiftAll(s.points, dx, dy),
circle: s.circle ? { ...s.circle, center: shift(s.circle.center, dx, dy) } : undefined,
})),
drawings2d: project.drawings2d.map((d) => {
const g = d.geom;
switch (g.shape) {
case "line":
case "xline":
case "ray":
return { ...d, geom: { ...g, a: shift(g.a, dx, dy), b: shift(g.b, dx, dy) } };
case "polyline":
return { ...d, geom: { ...g, pts: shiftAll(g.pts, dx, dy) } };
case "rect":
return { ...d, geom: { ...g, min: shift(g.min, dx, dy), max: shift(g.max, dx, dy) } };
case "circle":
return { ...d, geom: { ...g, center: shift(g.center, dx, dy) } };
case "arc":
return { ...d, geom: { ...g, center: shift(g.center, dx, dy) } };
case "ellipse":
return { ...d, geom: { ...g, center: shift(g.center, dx, dy) } };
case "bezier":
return { ...d, geom: { ...g, pts: shiftAll(g.pts, dx, dy) } };
case "spline":
return { ...d, geom: { ...g, pts: shiftAll(g.pts, dx, dy) } };
case "dimension":
return { ...d, geom: { ...g, pts: shiftAll(g.pts, dx, dy) } };
case "kote":
return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } };
case "detailref":
return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } };
case "scalebar":
return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } };
case "pointmarker":
return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } };
case "text":
return {
...d,
geom: {
...g,
at: shift(g.at, dx, dy),
...(g.leaderTarget ? { leaderTarget: shift(g.leaderTarget, dx, dy) } : {}),
...(g.leaderBendPoints ? { leaderBendPoints: shiftAll(g.leaderBendPoints, dx, dy) } : {}),
...(g.pathPts ? { pathPts: shiftAll(g.pathPts, dx, dy) } : {}),
},
};
case "block":
return { ...d, geom: { ...g, at: shift(g.at, dx, dy) } };
case "image":
return { ...d, geom: { ...g, min: shift(g.min, dx, dy), max: shift(g.max, dx, dy) } };
}
}),
context: project.context?.map((o) => shiftContextObject(o, dx, dy)),
drawingLevels: project.drawingLevels.map((lvl) =>
lvl.linePoints
? { ...lvl, linePoints: [shift(lvl.linePoints[0], dx, dy), shift(lvl.linePoints[1], dx, dy)] }
: lvl,
),
geoAnchor: project.geoAnchor
? { ...project.geoAnchor, model: shift(project.geoAnchor.model, dx, dy) }
: undefined,
};
const patch = documentFor(project).queryRoot<Partial<Project>>("translatePatch", JSON.stringify([dx, dy]));
return { ...project, ...patch };
}
/** Projekt-Listen, die {@link translateProject} verschiebt (jedes Element hat eine `id`). */
const TRANSLATED_LISTS = [
"walls", "ceilings", "roofs", "stairs", "rooms", "columns", "extrudedSolids", "drawings2d", "context", "drawingLevels",
] as const;
/**
* Ops für {@link translateProject}: je geändertem Element ein `replace` (Reihenfolge und Identität
* unveränderter Elemente bleiben), `geoAnchor` als Feld. Das Ergebnis von `applyOps` ist gleich
* `translateProject(project, dx, dy)`.
*/
export function translateOps(project: Project, dx: number, dy: number): CoreOp[] {
const next = translateProject(project, dx, dy);
if (next === project) return [];
const ops: CoreOp[] = [];
for (const key of TRANSLATED_LISTS) {
const before = project[key] as readonly { id: string }[] | undefined;
const after = next[key] as readonly { id: string }[] | undefined;
if (!before || !after) continue;
after.forEach((e, i) => {
if (e !== before[i]) ops.push(replaceItem(key, e as never));
});
}
if (next.geoAnchor !== project.geoAnchor) ops.push(setField("geoAnchor", next.geoAnchor));
return ops;
if (dx === 0 && dy === 0) return [];
return documentFor(project).queryRoot<CoreOp[]>("translateOps", JSON.stringify([dx, dy]));
}
/**
+6 -22
View File
@@ -1,6 +1,6 @@
// Export-Scope „nur Auswahl" (Nutzer-Wunsch aus der 2D-Lücken-Recherche:
// „Export exportiert immer den GANZEN Plan" — weder DXF- noch PDF-Dialog
// bieten einen Scope). Reine Projekt-Transform-Funktion: baut ein Project,
// bieten einen Scope). Projekt-Transform ([K4] S3: Rechnung im Kern): baut ein Project,
// das NUR die ausgewählten Elemente der acht `MemberKind`-Arten enthält
// (dieselbe Abdeckung wie `objectLock.ts`/`groupActions.ts`), sonst
// unverändert (Bibliotheken/Ebenen/Geschosse bleiben stehen, damit ID-
@@ -14,41 +14,25 @@
// gefilterten) Wände, nicht ausgewählte Wände nehmen also automatisch
// keine Türen mehr mit.
//
// Reines Modul: keine React-/Store-Abhängigkeit, wie `objectLock.ts`.
// Keine React-/Store-Abhängigkeit, wie `objectLock.ts`.
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
import type { Project } from "../model/types";
import { documentFor } from "../core/document";
import type { GroupMembership } from "./groupActions";
/**
* Baut ein Project, das nur die in `members` aufgeführten Elemente der acht
* Arten enthält — jede Art OHNE Eintrag (oder mit leerer Liste) wird
* komplett geleert (das ist der Zweck: „nur Auswahl", nicht „alles ausser
* explizit ausgeschlossen").
* explizit ausgeschlossen"). Die Kürzung rechnet der Kern (`selection_filter.rs`).
*/
export function filterProjectToSelection(
project: Project,
members: Partial<GroupMembership>,
): Project {
const wallIds = new Set(members.wallIds ?? []);
const drawingIds = new Set(members.drawingIds ?? []);
const ceilingIds = new Set(members.ceilingIds ?? []);
const roomIds = new Set(members.roomIds ?? []);
const stairIds = new Set(members.stairIds ?? []);
const columnIds = new Set(members.columnIds ?? []);
const roofIds = new Set(members.roofIds ?? []);
const openingIds = new Set(members.openingIds ?? []);
return {
...project,
walls: project.walls.filter((w) => wallIds.has(w.id)),
drawings2d: project.drawings2d.filter((d) => drawingIds.has(d.id)),
ceilings: (project.ceilings ?? []).filter((c) => ceilingIds.has(c.id)),
rooms: (project.rooms ?? []).filter((r) => roomIds.has(r.id)),
stairs: (project.stairs ?? []).filter((s) => stairIds.has(s.id)),
columns: (project.columns ?? []).filter((c) => columnIds.has(c.id)),
roofs: (project.roofs ?? []).filter((r) => roofIds.has(r.id)),
openings: (project.openings ?? []).filter((o) => openingIds.has(o.id)),
};
const patch = documentFor(project).queryRoot<Partial<Project>>("selectionFilterPatch", JSON.stringify(members));
return { ...project, ...patch };
}
/** Gesamtzahl ausgewählter Elemente über alle acht Arten (0 = keine Auswahl). */