Merge [C2] DXF/DWG-Export fuer Fachplaner: echte DIMENSION mit DIMSTYLE, Tueren/Fenster/Symbole als BLOCK+INSERT mit ATTRIB, Textstile, LTYPE aus Linienstilen, Raumstempel, Papierbereich-Layout

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-28 16:36:59 +00:00
commit 11eccf47bd
17 files changed
+2107 -60

No files matched your search

+23
View File
@@ -690,6 +690,29 @@ Code-Übernahme Lizenz der Abhängigkeiten prüfen, Pflicht [51].
Anonymblock nur als Text; Toleranzen/Alternativeinheiten/Textrahmen fehlen; Layout-Ansichtsfenster
(Modellansicht im Papierbereich) werden nicht abgebildet; bei Aufteilung grosser DXF (≥ 4 MB, parallel) fehlt
der Layout-Bericht; Ordinate-Bemassung; Tauri/macOS nicht getestet.
- ✅ **Export für Fachplaner** (28.10.): statt loser Linien schreibt der Export dort, wo das Modell die Information
trägt, CAD-Objekte (`export/exportDxf.ts` sammelt, `fileio/src/export.rs` + `export_dim.rs` bauen; neue
Datensätze der flachen Zeichnung, Version bleibt 1). **Bemassung:** `Drawing2D {shape:"dimension"}` → je Segment
eine echte ausgerichtete DIMENSION mit Anonymblock `*D…` (Hilfslinien, Masslinie, 45°-Architekturstriche, Masszahl
über der Linie, nie kopfüber) und DIMSTYLE `DOSSIER_1-<N>` (DIMSCALE = Massstab, DIMTXT/DIMTSZ/DIMEXO/DIMEXE in
Papier-mm, DIMTAD 1, Textstil); von Hand verschobene Masszahlen bleiben. **Türen/Fenster** (Primitive mit
`openingId`, Rahmen aus der Wand) → BLOCK `Tuer_90x210`/`Fenster_…` in Wandrichtung + INSERT mit ATTRIB (ID, TYP,
TYPENAME, BREITE_M, HOEHE_M, BRUESTUNG_M); gleiche lokale Geometrie teilt sich einen Block. **Möbel/Symbole/
Nordpfeil** (`shape:"block"`) → BLOCK je Definition (Name = Blockname) + INSERT mit Drehung/Skalierung.
**Linientypen:** Strichmuster → LTYPE (Name des Projekt-Linienstils bzw. `DOSSIER_STRICH_…`, Papier-mm × Massstab),
je Entität gesetzt. **Textstile:** STYLE `DOSSIER` mit Schriftname aus den Projekt-Textstilen (sonst Arial), Fett/
Kursiv als eigene Stile; Raumstempel (Name/Nutzung/Fläche) neu als TEXT, zentriert/links/rechts (72), Zeilen wie im
Plan; mehrzeilige/umbrochene Texte je Zeile. Strichstärken der Ebenen rasten auf CAD-Stufen; unsichtbare Pick-Bänder
(Dach, Schnittlinie) entfallen; Schnittsymbole auf Ebene `SECTIONS`. **Papierbereich:** optional ein Layout
(A4–A0 oder Sonderformat) mit Ansichtsfenster im Planmassstab (`--layout`). Dialog: Massstab, Einheit der Masszahl
(m/cm), Papierbereich; CLI `dxf|dwg --scale N --dim-unit cm --layout`. Geprüft: `cargo test` (acadrust-Rundreise DXF/
Binär/DWG je Datensatzart), ezdxf-Auditor 0 Fehler (`exportDxf.cad.test.ts`, `scripts/validate-dxf.py` liest jetzt
Blöcke, Stile, Linientypen, DIMSTYLE, Layouts), libredwg (DWG), eigener DXF-Import (Masszahlen, Geometrie).
**Offen:** in AutoCAD/BricsCAD selbst nicht geöffnet (DIMTSZ-Strichlänge, Textlage und `*D`-Block dort ungeprüft);
Wand/Decke/Treppe bleiben Linien/Polylinien (Plan liefert keine Bauteil-Instanzen); keine Strichstärke je Entität
(nur je Ebene); Schnittsymbole nicht als Block (Plan trägt keine Kennung); Ebenennamen `Code_Name` (kein SIA-2014-
Schema im Projekt); Masszahl-Einheit nur über Option (keine Projekteinstellung vorhanden); Ansichtsfenster ohne
eingefrorene Ebenen/Plotstil; Tauri/macOS nicht getestet.
- ○ **[C3] MCP an die laufende App** (`--connect 127.0.0.1:7979`, Werkzeuge `screenshot`, `ui_click`,
`render` → PNG, `execute` = jeder Befehl mit JSON): genau die fehlende Hälfte von [9]; setzt [6] voraus. · M
- ◐ **[C4] CLI-Skripte** (`run --script`, `--cmd` mehrfach mit `{last}`, `convert`): Befehle headless
+65
View File
@@ -60,12 +60,77 @@ def main(path: str) -> int:
item["text"] = e.dxf.text
item["at"] = [e.dxf.insert.x, e.dxf.insert.y]
item["height"] = e.dxf.height
item["style"] = e.dxf.style
item["halign"] = e.dxf.halign
item["valign"] = e.dxf.valign
item["rotation"] = e.dxf.rotation
if e.dxf.hasattr("align_point"):
item["align_point"] = [e.dxf.align_point.x, e.dxf.align_point.y]
elif t == "INSERT":
item["name"] = e.dxf.name
item["at"] = [e.dxf.insert.x, e.dxf.insert.y]
item["rotation"] = e.dxf.rotation
item["scale"] = [e.dxf.xscale, e.dxf.yscale]
item["attribs"] = {a.dxf.tag: a.dxf.text for a in e.attribs}
elif t == "DIMENSION":
item["dimtype"] = e.dimtype
item["block"] = e.dxf.geometry
item["dimstyle"] = e.dxf.dimstyle
item["defpoint"] = [e.dxf.defpoint.x, e.dxf.defpoint.y]
item["p1"] = [e.dxf.defpoint2.x, e.dxf.defpoint2.y]
item["p2"] = [e.dxf.defpoint3.x, e.dxf.defpoint3.y]
item["measurement"] = e.dxf.actual_measurement
if e.dxf.hasattr("linetype"):
item["linetype"] = e.dxf.linetype
entities.append(item)
layers = {
l.dxf.name: {"lineweight": l.dxf.lineweight, "rgb": l.rgb and list(l.rgb)} for l in doc.layers
}
blocks = {}
for b in doc.blocks:
n = {}
for be in b:
n[be.dxftype()] = n.get(be.dxftype(), 0) + 1
blocks[b.name] = {"entities": n, "anonymous": b.name.startswith("*D")}
styles = {st.dxf.name: (st.dxf.font if st.dxf.hasattr("font") else None) for st in doc.styles}
ttf = {}
for st in doc.styles:
try:
ttf[st.dxf.name] = st.get_extended_font_data()[0]
except Exception:
pass
linetypes = {lt.dxf.name: list(lt.pattern_tags.tags and [t.value for t in lt.pattern_tags.tags if t.code == 49]) for lt in doc.linetypes}
dimstyles = {
d.dxf.name: {k: d.dxf.get(k) for k in ("dimscale", "dimtxt", "dimtsz", "dimexo", "dimexe", "dimgap", "dimtad", "dimdec", "dimlfac", "dimtxsty")}
for d in doc.dimstyles
}
layouts = {}
for lay in doc.layouts:
if lay.name == "Model":
continue
vps = [
{
"id": v.dxf.id,
"center": [v.dxf.center.x, v.dxf.center.y],
"size": [v.dxf.width, v.dxf.height],
"view_center": [v.dxf.view_center_point.x, v.dxf.view_center_point.y],
"view_height": v.dxf.view_height,
}
for v in lay.viewports()
]
dl = lay.dxf_layout.dxf
layouts[lay.name] = {
"viewports": vps,
"paper": [dl.paper_width, dl.paper_height] if dl.hasattr("paper_width") else None,
}
out = {
"version": doc.dxfversion,
"blocks": blocks,
"styles": styles,
"fonts": ttf,
"linetypes": linetypes,
"dimstyles": dimstyles,
"layouts": layouts,
"insunits": doc.header.get("$INSUNITS"),
"errors": [str(err.message) for err in auditor.errors],
"layers": layers,
+589 -2
View File
@@ -34,6 +34,20 @@
// GRADIENT = 8, layer, rgb1 (0xRRGGBB), rgb2 (0xRRGGBB), angle (rad, Richtung rgb1 → rgb2, DXF-Konvention),
// kind (0 = linear, 1 = radial: rgb1 in der Mitte, rgb2 am Rand), n, x0, y0, … (äusserer Rand)
//
// Seit [C2] (28.10., „Fachplaner-Export“) zusätzlich — alles rückwärtskompatibel (Version bleibt 1):
// LTYPE = 9, name_idx, n, e0 … e(n−1) Linientyp (Meter; > 0 Strich, < 0 Lücke, 0 Punkt); Index = Reihenfolge
// LAYERLT = 10, layer, ltype Standard-Linientyp einer Ebene
// PEN = 11, ltype (−1 = nach Ebene) gilt für alle folgenden Entitäten bis zum nächsten PEN
// STYLE = 12, name_idx, font_idx, bold, italic, width_factor Textstil (TrueType-Schriftname); Index = Reihenfolge
// TEXT2 = 13, layer, text_idx, x, y, height, rotation, halign (0 links, 1 Mitte, 2 rechts), style (−1 = Standard)
// DIMSTYLE = 14, name_idx, textstyle (−1), scale, txt, tick, exo, exe, gap, dec, lfac, post_idx (−1) (Papier-Meter, s. export_dim.rs)
// DIM = 15, layer, dimstyle, x1, y1, x2, y2, dx, dy (Punkt auf der Masslinie), has_text, tx, ty
// BLOCK = 16, name_idx, desc_idx (−1), n_att, (tag_idx, prompt_idx, default_idx, x, y, height) × n_att
// — alle Entitätsdatensätze bis BLOCK_END gehören in die Blockdefinition (Koordinaten blocklokal)
// BLOCK_END= 17
// INSERT = 18, layer, name_idx, x, y, rotation, sx, sy, n_att, (tag_idx, value_idx) × n_att
// LAYOUT = 19, name_idx, paper_w, paper_h (mm), vp_cx, vp_cy, vp_w, vp_h (mm), view_cx, view_cy (Modell-m), scale_denominator
//
// `layer` ist der Index des LAYER-Datensatzes (Reihenfolge des Auftretens, ab 0), er muss vorher
// stehen. Schraffuren sind echte HATCH-Entitäten ([C2], 28.10.): Vollfüllung (`SOLID`) oder ein
// Linienmuster, das hier aus Winkel und Linienabstand der Dossier-Schraffur gebaut wird (je Linienschar
@@ -51,11 +65,18 @@ use acadrust::entities::{
BoundaryEdge, BoundaryPath, BoundaryPathFlags, Hatch, HatchGradientPattern, HatchPattern, HatchPatternLine,
HatchPatternType, PolylineEdge,
};
use acadrust::entities::{
AttributeDefinition, AttributeEntity, Insert, TextHorizontalAlignment, Viewport,
};
use acadrust::tables::{BlockRecord, LineType, LineTypeElement, TextStyle};
use acadrust::types::Handle;
use acadrust::{
Arc, CadDocument, Circle, Color, DwgWriter, DxfVersion, DxfWriter, EntityType, Layer, Line,
LineWeight, LwPolyline, Text, Vector2, Vector3,
};
use crate::export_dim::{build_aligned, into_entity, make_dimstyle, DimStyleDef};
/// Version der flachen Kodierung (erstes Element des Puffers).
pub const FLAT_VERSION: f64 = 1.0;
@@ -67,6 +88,17 @@ pub const REC_CIRCLE: f64 = 5.0;
pub const REC_TEXT: f64 = 6.0;
pub const REC_HATCH: f64 = 7.0;
pub const REC_GRADIENT: f64 = 8.0;
pub const REC_LTYPE: f64 = 9.0;
pub const REC_LAYER_LTYPE: f64 = 10.0;
pub const REC_PEN: f64 = 11.0;
pub const REC_STYLE: f64 = 12.0;
pub const REC_TEXT2: f64 = 13.0;
pub const REC_DIMSTYLE: f64 = 14.0;
pub const REC_DIM: f64 = 15.0;
pub const REC_BLOCK: f64 = 16.0;
pub const REC_BLOCK_END: f64 = 17.0;
pub const REC_INSERT: f64 = 18.0;
pub const REC_LAYOUT: f64 = 19.0;
/// DXF-Ausgabeversion (s. Kopf).
pub const DXF_VERSION: DxfVersion = DxfVersion::AC1032;
@@ -155,12 +187,18 @@ fn all_finite(v: &[f64]) -> bool {
v.iter().all(|x| x.is_finite())
}
/// Genormte CAD-Strichstärken (1/100 mm). Andere Werte kennt AutoCAD nicht; es rundet beim Lesen
/// uneinheitlich, darum rasten wir selbst auf die nächste Stufe ein.
const STD_LINE_WEIGHTS: [i16; 24] =
[0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211];
fn line_weight(v: f64) -> LineWeight {
if !v.is_finite() || v < 0.0 {
return LineWeight::Default;
}
// Gültige DXF-Stufen enden bei 211 (2.11 mm).
LineWeight::Value(v.round().min(211.0) as i16)
let w = v.round().min(211.0) as i16;
let nearest = STD_LINE_WEIGHTS.iter().copied().min_by_key(|s| (s - w).abs()).unwrap_or(25);
LineWeight::Value(nearest)
}
fn layer_color(rgb: f64) -> Color {
@@ -228,6 +266,76 @@ fn make_gradient_hatch(pts: &[f64], rgb1: u32, rgb2: u32, angle: f64, radial: bo
hatch
}
/// Obergrenzen gegen Unsinn im Puffer.
const MAX_LTYPE_ELEMENTS: usize = 16;
const MAX_BLOCK_ATTS: usize = 32;
/// Blockname bereinigen: wie Ebenennamen, ein führendes `*` (= Anonymblock) wird zu `_`.
fn sanitize_block_name(name: &str) -> String {
let n = sanitize_layer_name(name);
if let Some(rest) = n.strip_prefix('*') {
format!("_{rest}")
} else {
n
}
}
/// Neuer Blockeintrag (BLOCK-Tabelle) mit eigenen Handles; Entitäten werden über `owner_handle` zugeordnet.
fn new_block_record(doc: &mut CadDocument, name: &str, anonymous: bool) -> Result<Handle, String> {
let mut rec = BlockRecord::new(name);
rec.handle = doc.allocate_handle();
rec.block_entity_handle = doc.allocate_handle();
rec.block_end_handle = doc.allocate_handle();
rec.flags.anonymous = anonymous;
let h = rec.handle;
doc.block_records.add(rec).map_err(|e| format!("Block {name}: {e}"))?;
Ok(h)
}
/// Eine Blockdefinition: Handle des Blockeintrags und ihre Attributdefinitionen (Tag, ATTDEF-Handle, Höhe).
struct BlockDef {
atts: Vec<(String, Handle, f64)>,
}
/// Papierbereich: ein Layout in mm mit einem Ansichtsfenster auf den Modellbereich. `v` = Papierbreite,
/// Papierhöhe, Mittelpunkt (x, y) und Grösse (b, h) des Fensters auf dem Papier (mm), Mittelpunkt des
/// Bildausschnitts im Modell (m), Massstabsnenner. Massstab: 1 m Modell = 1000/Nenner mm Papier.
fn add_layout_with_viewport(doc: &mut CadDocument, name: &str, v: &[f64]) -> Result<(), String> {
let (pw, ph, cx, cy, vw, vh) = (v[0], v[1], v[2], v[3], v[4], v[5]);
let layout_handle = doc.add_layout(name).map_err(|e| format!("Layout {name}: {e}"))?;
// Papiergrösse und Grenzen im Layout-Objekt; Blattviewport (ID 1) deckt das Papier.
let mut overall = Handle::NULL;
if let Some(acadrust::objects::ObjectType::Layout(l)) = doc.objects.get_mut(&layout_handle) {
l.paper_width = pw;
l.paper_height = ph;
l.min_limits = (0.0, 0.0);
l.max_limits = (pw, ph);
l.min_extents = (0.0, 0.0, 0.0);
l.max_extents = (pw, ph, 0.0);
overall = l.viewport;
}
if let Some(EntityType::Viewport(vp)) = doc.get_entity_mut(overall) {
vp.center = Vector3::new(pw / 2.0, ph / 2.0, 0.0);
vp.width = pw;
vp.height = ph;
vp.view_center = Vector3::new(pw / 2.0, ph / 2.0, 0.0);
vp.view_height = ph;
}
let mut vp = Viewport::new();
vp.id = 2;
vp.status = acadrust::entities::ViewportStatusFlags::default_on();
vp.center = Vector3::new(cx, cy, 0.0);
vp.width = vw;
vp.height = vh;
vp.view_center = Vector3::new(v[6], v[7], 0.0);
vp.view_target = Vector3::new(v[6], v[7], 0.0);
vp.set_scale(1000.0 / v[8]);
vp.common.layer = "0".to_string();
doc.add_entity_to_layout(EntityType::Viewport(Box::new(vp)), name)
.map_err(|e| format!("Ansichtsfenster {name}: {e}"))?;
Ok(())
}
/// Baut aus der flachen Zeichnung ein acadrust-Dokument (Einheit Meter, metrisch).
pub fn build_document(flat: &[f64], strings: &str) -> Result<CadDocument, String> {
let strs: Vec<&str> = if strings.is_empty() { Vec::new() } else { strings.split('\0').collect() };
@@ -245,6 +353,25 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result<CadDocument, String
doc.header.measurement = 1; // metrisch
// Ebenen-Index (Datensatzreihenfolge) → bereinigter Name.
let mut layers: Vec<String> = Vec::new();
// Linientypen, Textstile, Bemassungsstile: Index (Datensatzreihenfolge) → Name bzw. Definition.
let mut ltypes: Vec<String> = Vec::new();
let mut styles: Vec<String> = Vec::new();
let mut dimstyles: Vec<DimStyleDef> = Vec::new();
let mut blocks: std::collections::HashMap<String, BlockDef> = std::collections::HashMap::new();
let mut cur_ltype = String::new();
let mut cur_block: Option<Handle> = None;
let mut dim_counter = 0usize;
// Optionaler Index: −1 = nicht gesetzt.
let opt_idx = |v: f64, what: &str| -> Result<Option<usize>, String> {
if v == -1.0 {
Ok(None)
} else if v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v <= u32::MAX as f64 {
Ok(Some(v as usize))
} else {
Err(format!("ungültiger Index {v} ({what})"))
}
};
while !r.done() {
let tag = r.f()?;
@@ -262,8 +389,174 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result<CadDocument, String
layers.push(name);
continue;
}
if tag == REC_LTYPE {
let name = sanitize_layer_name(str_at(r.idx()?)?);
let n = r.idx()?;
if n > MAX_LTYPE_ELEMENTS {
return Err(format!("zu viele Linientyp-Elemente ({n}) bei {}", r.pos - 1));
}
let el = r.take(n)?;
let valid = n >= 2 && all_finite(el) && el.iter().map(|e| e.abs()).sum::<f64>() > 1e-9;
// Ungültiges Muster: Index bleibt belegt, der Linientyp ist dann durchgezogen.
if !valid || ["continuous", "bylayer", "byblock"].contains(&name.to_lowercase().as_str()) {
ltypes.push("Continuous".to_string());
} else {
if !doc.line_types.contains(&name) {
let mut lt = LineType::new(name.clone());
lt.description = format!("Dossier {name}");
for &e in el {
lt.add_element(if e > 0.0 {
LineTypeElement::dash(e)
} else if e < 0.0 {
LineTypeElement::space(-e)
} else {
LineTypeElement::dot()
});
}
lt.pattern_length = el.iter().map(|e| e.abs()).sum();
doc.line_types.add(lt).map_err(|e| format!("Linientyp {name}: {e}"))?;
}
ltypes.push(name);
}
continue;
}
if tag == REC_LAYER_LTYPE {
let li = r.idx()?;
let ti = r.idx()?;
let lname = layers.get(li).ok_or_else(|| format!("Ebene {li} nicht definiert"))?.clone();
let lt = ltypes.get(ti).ok_or_else(|| format!("Linientyp {ti} nicht definiert"))?.clone();
if lname != "0" && lt != "Continuous" {
if let Some(layer) = doc.layers.get_mut(&lname) {
layer.line_type = lt;
}
}
continue;
}
if tag == REC_PEN {
cur_ltype = match opt_idx(r.f()?, "Linientyp")? {
None => String::new(),
Some(i) => ltypes.get(i).ok_or_else(|| format!("Linientyp {i} nicht definiert"))?.clone(),
};
if cur_ltype == "Continuous" {
cur_ltype.clear();
}
continue;
}
if tag == REC_STYLE {
let name = sanitize_layer_name(str_at(r.idx()?)?);
let font = str_at(r.idx()?)?.trim().to_string();
let bold = r.f()? != 0.0;
let italic = r.f()? != 0.0;
let width = r.f()?;
if !doc.text_styles.contains(&name) {
let mut st = TextStyle::with_truetype(name.clone(), if font.is_empty() { "Arial" } else { &font });
st.font_file = String::new(); // Auflösung über den TrueType-Namen (XDATA), nicht über eine Datei
st.handle = doc.allocate_handle(); // DIMSTYLE verweist (Code 340) über dieses Handle auf den Stil
st.true_type_font_flags = 34 | if bold { 0x0200_0000 } else { 0 } | if italic { 0x0100_0000 } else { 0 };
if width.is_finite() && width > 0.0 {
st.width_factor = width;
}
doc.text_styles.add(st).map_err(|e| format!("Textstil {name}: {e}"))?;
}
styles.push(name);
continue;
}
if tag == REC_DIMSTYLE {
let name = sanitize_layer_name(str_at(r.idx()?)?);
let ts = opt_idx(r.f()?, "Textstil")?;
let v = r.take(8)?;
let post = match opt_idx(r.f()?, "Format")? {
Some(i) => str_at(i)?.to_string(),
None => String::new(),
};
let def = DimStyleDef {
name: name.clone(),
text_style: match ts {
Some(i) => styles.get(i).ok_or_else(|| format!("Textstil {i} nicht definiert"))?.clone(),
None => "Standard".to_string(),
},
scale: v[0],
txt: v[1],
tick: v[2],
exo: v[3],
exe: v[4],
gap: v[5],
dec: if v[6].is_finite() { v[6] as i16 } else { -1 },
lfac: v[7],
post,
};
if def.is_valid() && !doc.dim_styles.contains(&name) {
let mut ds = make_dimstyle(&def);
if let Some(ts) = doc.text_styles.get(&def.text_style) {
ds.dimtxsty_handle = ts.handle;
}
doc.dim_styles.add(ds).map_err(|e| format!("Bemassungsstil {name}: {e}"))?;
}
dimstyles.push(def);
continue;
}
if tag == REC_BLOCK {
if cur_block.is_some() {
return Err(format!("Block in Block bei {}", r.pos - 1));
}
let name = sanitize_block_name(str_at(r.idx()?)?);
let desc = match opt_idx(r.f()?, "Beschreibung")? {
Some(i) => str_at(i)?.to_string(),
None => String::new(),
};
let n_att = r.idx()?;
if n_att > MAX_BLOCK_ATTS {
return Err(format!("zu viele Attribute ({n_att}) bei {}", r.pos - 1));
}
let h = new_block_record(&mut doc, &name, false)?;
if let Some(br) = doc.block_records.get_mut(&name) {
br.description = desc;
}
let mut atts = Vec::new();
for _ in 0..n_att {
let tag_s = str_at(r.idx()?)?.to_uppercase().replace(' ', "_");
let prompt = str_at(r.idx()?)?.to_string();
let default = str_at(r.idx()?)?.to_string();
let v = r.take(3)?;
if !all_finite(v) || v[2] <= 0.0 || tag_s.is_empty() {
continue;
}
let mut ad = AttributeDefinition::new(tag_s.clone(), prompt, default);
ad.insertion_point = Vector3::new(v[0], v[1], 0.0);
ad.height = v[2];
ad.flags.invisible = true; // Daten, keine Beschriftung: erscheint nur im Attribut-Editor/in Tabellen
ad.common.layer = "0".to_string();
ad.common.owner_handle = h;
let ah = doc.add_entity(EntityType::AttributeDefinition(ad)).map_err(|e| format!("ATTDEF: {e}"))?;
atts.push((tag_s, ah, v[2]));
}
if !atts.is_empty() {
if let Some(br) = doc.block_records.get_mut(&name) {
br.flags.has_attributes = true;
}
}
blocks.insert(name, BlockDef { atts });
cur_block = Some(h);
continue;
}
if tag == REC_BLOCK_END {
if cur_block.take().is_none() {
return Err(format!("BLOCK_END ohne BLOCK bei {}", r.pos - 1));
}
continue;
}
if tag == REC_LAYOUT {
let name = sanitize_layer_name(str_at(r.idx()?)?);
let v = r.take(9)?;
// Papier ≥ 10 mm, Ansichtsfenster ≥ 1 mm, Massstab > 0; sonst bleibt der Papierbereich weg.
if all_finite(v) && v[0] >= 10.0 && v[1] >= 10.0 && v[4] >= 1.0 && v[5] >= 1.0 && v[8] > 0.0 && cur_block.is_none() {
add_layout_with_viewport(&mut doc, &name, v)?;
}
continue;
}
let li = r.idx()?;
let layer = layers.get(li).ok_or_else(|| format!("Ebene {li} nicht definiert"))?.clone();
// Entitäten, die selbst Blöcke/mehrere Entitäten erzeugen (DIM), legen ihre Nebenentitäten selbst an.
let entity = if tag == REC_LINE {
let v = r.take(4)?;
all_finite(v).then(|| EntityType::Line(Line::from_coords(v[0], v[1], 0.0, v[2], v[3], 0.0)))
@@ -289,6 +582,27 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result<CadDocument, String
(all_finite(v) && v[2] > 0.0).then(|| {
EntityType::Text(Text::with_value(value, Vector3::new(v[0], v[1], 0.0)).with_height(v[2]).with_rotation(v[3]))
})
} else if tag == REC_TEXT2 {
let value = sanitize_text(str_at(r.idx()?)?);
let v = r.take(4)?;
let halign = r.f()?;
let style = opt_idx(r.f()?, "Textstil")?;
let style_name = match style {
Some(i) => styles.get(i).ok_or_else(|| format!("Textstil {i} nicht definiert"))?.clone(),
None => "Standard".to_string(),
};
(all_finite(v) && v[2] > 0.0 && !value.trim().is_empty()).then(|| {
let at = Vector3::new(v[0], v[1], 0.0);
let mut t = Text::with_value(value, at).with_height(v[2]).with_rotation(v[3]);
t.style = style_name;
// TEXT 72/73: bei Mitte/rechts steht die Lage unter Gruppe 11 (Ausrichtungspunkt).
if halign == 1.0 || halign == 2.0 {
t.horizontal_alignment =
if halign == 1.0 { TextHorizontalAlignment::Center } else { TextHorizontalAlignment::Right };
t.alignment_point = Some(at);
}
EntityType::Text(t)
})
} else if tag == REC_HATCH {
let mode = r.f()?;
let rgb = r.f()?;
@@ -332,11 +646,72 @@ pub fn build_document(flat: &[f64], strings: &str) -> Result<CadDocument, String
(n >= 3 && all_finite(pts) && angle.is_finite() && in_range(rgb1) && in_range(rgb2)).then(|| {
EntityType::Hatch(Box::new(make_gradient_hatch(pts, rgb1 as u32, rgb2 as u32, angle, kind == 1.0)))
})
} else if tag == REC_DIM {
let di = r.idx()?;
let v = r.take(6)?;
let has_text = r.f()? != 0.0;
let t = r.take(2)?;
let def = dimstyles.get(di).ok_or_else(|| format!("Bemassungsstil {di} nicht definiert"))?;
let text_at = has_text.then(|| [t[0], t[1]]);
let block_name = format!("*D{}", dim_counter + 1);
match build_aligned(def, &block_name, &layer, [v[0], v[1]], [v[2], v[3]], [v[4], v[5]], text_at) {
Some(built) if doc.dim_styles.contains(&def.name) => {
dim_counter += 1;
let bh = new_block_record(&mut doc, &block_name, true)?;
for mut be in built.block_entities {
be.common_mut().owner_handle = bh;
doc.add_entity(be).map_err(|e| format!("Bemassungsblock: {e}"))?;
}
Some(into_entity(built.entity))
}
_ => None,
}
} else if tag == REC_INSERT {
let name = sanitize_block_name(str_at(r.idx()?)?);
let v = r.take(5)?;
let n_att = r.idx()?;
if n_att > MAX_BLOCK_ATTS {
return Err(format!("zu viele Attribute ({n_att}) bei {}", r.pos - 1));
}
let mut values: Vec<(String, String)> = Vec::new();
for _ in 0..n_att {
let tag_s = str_at(r.idx()?)?.to_uppercase().replace(' ', "_");
let val = sanitize_text(str_at(r.idx()?)?);
values.push((tag_s, val));
}
let def = blocks.get(&name).ok_or_else(|| format!("Block {name} nicht definiert"))?;
(all_finite(v) && v[3].abs() > 1e-12 && v[4].abs() > 1e-12).then(|| {
let at = Vector3::new(v[0], v[1], 0.0);
let mut ins = Insert::new(name.clone(), at).with_rotation(v[2]).with_scale(v[3], v[4], 1.0);
for (tag_s, ah, height) in &def.atts {
if let Some((_, val)) = values.iter().find(|(t, _)| t == tag_s) {
let mut a = AttributeEntity::new(tag_s.clone(), val.clone());
a.insertion_point = at;
a.alignment_point = at;
a.height = *height * v[3].abs();
a.rotation = v[2];
a.attdef_handle = *ah;
a.flags.invisible = true;
a.common.layer = layer.clone();
ins.attributes.push(a);
}
}
EntityType::Insert(ins)
})
} else {
return Err(format!("unbekannter Datensatz {tag} bei {}", r.pos - 1));
};
if let Some(mut e) = entity {
e.common_mut().layer = layer;
// Linientyp nur auf Linien-artigen Entitäten (Schraffur/Text/Block tragen ihn nicht).
if !cur_ltype.is_empty()
&& matches!(e, EntityType::Line(_) | EntityType::LwPolyline(_) | EntityType::Arc(_) | EntityType::Circle(_))
{
e.common_mut().linetype = cur_ltype.clone();
}
if let Some(owner) = cur_block {
e.common_mut().owner_handle = owner;
}
doc.add_entity(e).map_err(|e| format!("Entität: {e}"))?;
}
}
@@ -784,4 +1159,216 @@ mod tests {
let (flat, strings) = hatch_sample();
check_hatches(&read_dxf(export_dxf_binary(&flat, &strings).unwrap()));
}
// ── [C2] Fachplaner-Export: Linientypen, Textstile, Bemassung, Blöcke, Attribute ─────────────
/// Zeichnung mit allen neuen Datensatzarten (LV95).
fn cad_sample() -> (Vec<f64>, String) {
let strings = [
"21_Wände", // 0 Ebene
"0", // 1 Ebene 0
"DOSSIER_STRICH_0.3_0.1", // 2 Linientyp
"DOSSIER", // 3 Textstil
"Helvetica Neue", // 4 Schrift
"DOSSIER_1-100", // 5 Bemassungsstil
"T_Tür_0.9x2.1", // 6 Block
"Tür 0.90 x 2.10", // 7 Beschreibung
"TYP", // 8 Tag
"Typ", // 9 Prompt
"Tür", // 10 Vorgabe
"BREITE", // 11 Tag
"0.90", // 12 Wert
"Fensterbank Küche",// 13 Text
]
.join("\0");
let (e, n) = (E, N);
let flat = vec![
FLAT_VERSION,
REC_LAYER, 0.0, 0x8a_5a_44 as f64, 50.0,
REC_LAYER, 1.0, -1.0, 25.0,
REC_LTYPE, 2.0, 4.0, 0.03, -0.01, 0.03, -0.01,
REC_LAYER_LTYPE, 0.0, 0.0,
REC_STYLE, 3.0, 4.0, 1.0, 0.0, 1.0,
REC_DIMSTYLE, 5.0, 0.0, 100.0, 0.004, 0.003, 0.001, 0.001, 0.0024, 2.0, 1.0, -1.0,
// Block mit zwei Linien und einem Attribut-Paar (nur TYP definiert, BREITE unbekannt → ignoriert)
REC_BLOCK, 6.0, 7.0, 1.0, 8.0, 9.0, 10.0, 0.0, 0.0, 0.1,
REC_LINE, 1.0, 0.0, 0.0, 0.9, 0.0,
REC_ARC, 1.0, 0.0, 0.0, 0.9, 0.0, std::f64::consts::FRAC_PI_2,
REC_BLOCK_END,
REC_PEN, 0.0,
REC_LINE, 0.0, e, n, e + 4.0, n,
REC_PEN, -1.0,
REC_TEXT2, 0.0, 13.0, e + 2.0, n + 1.0, 0.2, 0.0, 1.0, 0.0,
REC_DIM, 0.0, 0.0, e, n, e + 4.0, n, e, n - 1.0, 0.0, 0.0, 0.0,
REC_INSERT, 0.0, 6.0, e + 1.0, n, 1.0, 1.0, 1.0, 1.0, 8.0, 12.0,
REC_INSERT, 0.0, 6.0, e + 3.0, n, 0.0, 0.5, 0.5, 0.0,
];
(flat, strings)
}
fn check_cad(doc: &CadDocument) {
// Linientyp
let lt = doc.line_types.get("DOSSIER_STRICH_0.3_0.1").expect("Linientyp");
assert_eq!(lt.elements.len(), 4);
assert!((lt.elements[0].length - 0.03).abs() < 1e-12 && (lt.elements[1].length + 0.01).abs() < 1e-12);
let line = doc.model_space_entities().find_map(|x| if let EntityType::Line(l) = x { Some(l) } else { None }).expect("Linie");
assert_eq!(line.common.linetype, "DOSSIER_STRICH_0.3_0.1");
assert_eq!(doc.layers.get("21_Wände").unwrap().line_type, "DOSSIER_STRICH_0.3_0.1");
// Textstil
let st = doc.text_styles.get("DOSSIER").expect("Textstil");
assert_eq!(st.true_type_font, "Helvetica Neue");
// Text mit Mittelausrichtung
let txt = doc.model_space_entities().find_map(|x| if let EntityType::Text(t) = x { Some(t) } else { None }).unwrap();
assert_eq!(txt.value, "Fensterbank Küche");
assert_eq!(txt.horizontal_alignment, TextHorizontalAlignment::Center);
assert_eq!(txt.alignment_point.map(|p| (p.x, p.y)), Some((E + 2.0, N + 1.0)));
// Bemassungsstil
let ds = doc.dim_styles.get("DOSSIER_1-100").expect("Bemassungsstil");
assert!((ds.dimscale - 100.0).abs() < 1e-12 && (ds.dimtxt - 0.004).abs() < 1e-12);
assert!((ds.dimtsz - 0.0015).abs() < 1e-12 && ds.dimtad == 1);
// Bemassung: echte DIMENSION mit Anonymblock
let dim = doc
.model_space_entities()
.find_map(|x| if let EntityType::Dimension(d) = x { Some(d) } else { None })
.expect("DIMENSION");
assert!((dim.base().actual_measurement - 4.0).abs() < 1e-9, "{}", dim.base().actual_measurement);
assert_eq!(dim.base().style_name, "DOSSIER_1-100");
let block = dim.base().block_name.clone();
assert!(block.starts_with("*D"), "{block}");
let in_block: Vec<&EntityType> = doc.entities_in_block(&block).collect();
assert_eq!(in_block.iter().filter(|e| matches!(e, EntityType::Line(_))).count(), 5);
assert!(in_block.iter().any(|e| matches!(e, EntityType::Text(t) if t.value == "4.00")));
// Block + INSERT + Attribut
let br = doc.block_records.get("T_Tür_0.9x2.1").expect("Block");
assert_eq!(br.description, "Tür 0.90 x 2.10");
let content: Vec<&EntityType> = doc.entities_in_block("T_Tür_0.9x2.1").collect();
assert_eq!(content.iter().filter(|e| matches!(e, EntityType::Line(_))).count(), 1);
assert_eq!(content.iter().filter(|e| matches!(e, EntityType::Arc(_))).count(), 1);
assert_eq!(content.iter().filter(|e| matches!(e, EntityType::AttributeDefinition(_))).count(), 1);
let inserts: Vec<&Insert> =
doc.model_space_entities().filter_map(|x| if let EntityType::Insert(i) = x { Some(i) } else { None }).collect();
assert_eq!(inserts.len(), 2);
assert_eq!(inserts[0].block_name, "T_Tür_0.9x2.1");
assert_eq!((inserts[0].insert_point.x, inserts[0].insert_point.y), (E + 1.0, N));
assert_eq!(inserts[0].attributes.len(), 1);
assert_eq!(inserts[0].attributes[0].tag, "TYP");
assert_eq!(inserts[0].attributes[0].value, "0.90"); // Wert 12 steht unter Tag 8 (TYP)
assert!((inserts[1].x_scale() - 0.5).abs() < 1e-12);
assert!(inserts[1].attributes.is_empty());
// Die INSERTs und die Bemassung liegen im Modellbereich, Blockinhalt nicht.
let model = doc.model_space_entities().count();
assert!(doc.entities().count() > model);
}
#[test]
fn fachplaner_export_rundreise_dxf_binaer_und_dwg() {
let (flat, strings) = cad_sample();
check_cad(&read_dxf(export_dxf(&flat, &strings).unwrap()));
check_cad(&read_dxf(export_dxf_binary(&flat, &strings).unwrap()));
check_cad(&read_dwg(export_dwg(&flat, &strings).unwrap()));
}
#[test]
fn dxf_text_traegt_dimension_block_style_und_ltype() {
let (flat, strings) = cad_sample();
let text = String::from_utf8(export_dxf(&flat, &strings).unwrap()).unwrap();
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let has = |code: &str, val: &str| lines.windows(2).any(|w| w[0] == code && w[1] == val);
assert!(has("0", "DIMENSION") && has("100", "AcDbAlignedDimension"));
assert!(has("2", "*D1"));
assert!(has("0", "ATTDEF") && has("0", "ATTRIB"));
assert!(has("2", "DOSSIER_STRICH_0.3_0.1") && has("2", "Helvetica Neue") == false);
assert!(has("1000", "Helvetica Neue"));
assert!(has("72", "1")); // TEXT zentriert
}
#[test]
fn kaputte_cad_datensaetze_sind_fehler_oder_werden_verworfen() {
let head = [FLAT_VERSION, REC_LAYER, 0.0, -1.0, 25.0];
let mk = |rest: &[f64]| {
let mut v = head.to_vec();
v.extend_from_slice(rest);
v
};
// Unbekannte Indizes → Fehler
assert!(export_dxf(&mk(&[REC_DIM, 0.0, 5.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]), "P").is_err());
assert!(export_dxf(&mk(&[REC_INSERT, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0]), "P").is_err()); // Block fehlt
assert!(export_dxf(&mk(&[REC_PEN, 3.0]), "P").is_err());
assert!(export_dxf(&mk(&[REC_BLOCK_END]), "P").is_err());
assert!(export_dxf(&mk(&[REC_BLOCK, 0.0, -1.0, 0.0, REC_BLOCK, 0.0, -1.0, 0.0]), "P").is_err()); // Block im Block
assert!(export_dxf(&mk(&[REC_LTYPE, 0.0, 99.0]), "P").is_err());
assert!(export_dxf(&mk(&[REC_TEXT2, 0.0, 0.0, 0.0]), "P").is_err()); // abgeschnitten
// Entartetes: DIM mit Länge 0 / NaN, INSERT mit Skalierung 0, leerer Text → übersprungen
let ds = [REC_DIMSTYLE, 0.0, -1.0, 100.0, 0.004, 0.003, 0.001, 0.001, 0.0024, 2.0, 1.0, -1.0];
let mut v = mk(&ds);
v.extend_from_slice(&[REC_DIM, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 2.0, 0.0, 0.0, 0.0]);
v.extend_from_slice(&[REC_DIM, 0.0, 0.0, f64::NAN, 1.0, 2.0, 1.0, 0.0, 2.0, 0.0, 0.0, 0.0]);
v.extend_from_slice(&[REC_BLOCK, 0.0, -1.0, 0.0, REC_BLOCK_END, REC_INSERT, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]);
v.extend_from_slice(&[REC_TEXT2, 0.0, 0.0, 0.0, 0.0, 0.2, 0.0, 0.0, -1.0]);
let doc = read_dxf(export_dxf(&v, " ").unwrap());
assert_eq!(doc.entities().filter(|e| !matches!(e, EntityType::Insert(_))).count(), 0);
// Ungültiger Bemassungsstil (Massstab 0): DIM entfällt, Stil wird nicht geschrieben.
let mut bad = mk(&[REC_DIMSTYLE, 0.0, -1.0, 0.0, 0.004, 0.003, 0.001, 0.001, 0.0024, 2.0, 1.0, -1.0]);
bad.extend_from_slice(&[REC_DIM, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]);
let doc = read_dxf(export_dxf(&bad, "S").unwrap());
assert_eq!(doc.entities().count(), 0);
}
#[test]
fn strichstaerken_rasten_auf_cad_stufen() {
assert_eq!(line_weight(18.0), LineWeight::Value(18));
assert_eq!(line_weight(17.0), LineWeight::Value(18));
assert_eq!(line_weight(22.0), LineWeight::Value(20));
assert_eq!(line_weight(1000.0), LineWeight::Value(211));
assert_eq!(line_weight(-3.0), LineWeight::Default);
}
/// Papierbereich: Layout mit Blattviewport und einem Ansichtsfenster im Planmassstab.
fn layout_flat() -> (Vec<f64>, String) {
let flat = vec![
FLAT_VERSION,
REC_LAYER, 0.0, -1.0, 25.0,
REC_LINE, 0.0, E, N, E + 10.0, N,
// A3 quer, Fenster 400 x 277 mm um (210, 148), Ausschnitt um (E+5, N+3), 1:50
REC_LAYOUT, 1.0, 420.0, 297.0, 210.0, 148.5, 400.0, 277.0, E + 5.0, N + 3.0, 50.0,
];
(flat, "P\0Plan 1:50".to_string())
}
fn check_layout(doc: &CadDocument) {
let layout = doc
.objects
.values()
.find_map(|o| if let acadrust::objects::ObjectType::Layout(l) = o { (l.name == "Plan_1_50").then_some(l) } else { None })
.or_else(|| doc.objects.values().find_map(|o| if let acadrust::objects::ObjectType::Layout(l) = o { (l.name.starts_with("Plan")).then_some(l) } else { None }))
.expect("Layout");
assert!((layout.paper_width - 420.0).abs() < 1e-9 && (layout.paper_height - 297.0).abs() < 1e-9);
let vps: Vec<&acadrust::entities::Viewport> = doc
.entities()
.filter_map(|e| if let EntityType::Viewport(v) = e { Some(v.as_ref()) } else { None })
.filter(|v| v.id == 2)
.collect();
assert_eq!(vps.len(), 1);
let vp = vps[0];
assert!((vp.width - 400.0).abs() < 1e-9 && (vp.height - 277.0).abs() < 1e-9);
assert!((vp.view_center.x - (E + 5.0)).abs() < 1e-6 && (vp.view_center.y - (N + 3.0)).abs() < 1e-6);
// 1:50 → 1 m = 20 mm Papier; Ausschnitt 277 mm / 20 = 13.85 m hoch.
assert!((vp.view_height - 13.85).abs() < 1e-9, "{}", vp.view_height);
}
#[test]
fn papierbereich_mit_ansichtsfenster_dxf_und_dwg() {
let (flat, strings) = layout_flat();
check_layout(&read_dxf(export_dxf(&flat, &strings).unwrap()));
check_layout(&read_dwg(export_dwg(&flat, &strings).unwrap()));
}
#[test]
fn entartetes_layout_wird_uebersprungen() {
let (mut flat, strings) = layout_flat();
let n = flat.len();
flat[n - 1] = 0.0; // Massstab 0
let doc = read_dxf(export_dxf(&flat, &strings).unwrap());
assert!(doc.entities().all(|e| !matches!(e, EntityType::Viewport(_))));
}
}
+277
View File
@@ -0,0 +1,277 @@
// Bemassung für den DXF/DWG-Export ([C2], 28.10.): echte DIMENSION-Entitäten (ausgerichtet) samt
// Bemassungsstil (DIMSTYLE) und Anonymblock `*D…`.
//
// Warum der Anonymblock: AutoCAD, BricsCAD & Co. zeichnen eine DIMENSION aus ihren Definitionspunkten
// und dem Stil neu, LibreCAD/ezdxf/viele Betrachter aber nur aus dem Block `*D<n>` (Gruppencode 2 der
// Entität). Wir schreiben beides: die Entität (bearbeitbar, folgt dem Stil) und den Block (sieht überall
// gleich aus, identisch zum Dossier-Plan: Masshilfslinien mit Abstand/Überstand, Masslinie, 45°-
// Architekturstriche, Masszahl über der Linie, nie kopfüber).
//
// Grössen: `DimStyleDef` trägt PAPIER-Meter (Texthöhe 4 mm = 0.004) und den Massstab als `scale`
// (DIMSCALE). In Modell-Metern ist jede Länge `papier × scale` — dieselbe Umrechnung wie
// `model/dimension.ts::mmToModel`. Der Block wird in Weltkoordinaten (LV95 passt) mit diesen
// Modell-Metern gezeichnet.
use acadrust::entities::{
AttachmentPointType, Dimension, DimensionAligned, Line, Text, TextHorizontalAlignment,
};
use acadrust::tables::DimStyle;
use acadrust::{EntityType, Vector3};
/// Bemassungsstil in Papier-Metern (Länge × `scale` = Modell-Meter).
#[derive(Debug, Clone, PartialEq)]
pub struct DimStyleDef {
pub name: String,
/// Name des Textstils (STYLE) der Masszahl.
pub text_style: String,
/// Massstabsnenner (DIMSCALE), z. B. 100 bei 1:100.
pub scale: f64,
/// Texthöhe (DIMTXT).
pub txt: f64,
/// Gesamtlänge des Architekturstrichs.
pub tick: f64,
/// Abstand Masshilfslinie ← bemessener Punkt (DIMEXO).
pub exo: f64,
/// Überstand der Masshilfslinie über die Masslinie (DIMEXE).
pub exe: f64,
/// Abstand Masszahl ↔ Masslinie (DIMGAP).
pub gap: f64,
/// Nachkommastellen der Masszahl (DIMDEC).
pub dec: i16,
/// Faktor Modell-Meter → Anzeigeeinheit (DIMLFAC): 1 = Meter, 100 = Zentimeter.
pub lfac: f64,
/// Format der Masszahl mit `<>` als Platzhalter (DIMPOST), leer = nur die Zahl.
pub post: String,
}
impl DimStyleDef {
/// Alle Werte endlich, Massstab/Texthöhe positiv, Nachkommastellen im DXF-Bereich.
pub fn is_valid(&self) -> bool {
[self.scale, self.txt, self.tick, self.exo, self.exe, self.gap, self.lfac].iter().all(|v| v.is_finite())
&& self.scale > 0.0
&& self.txt > 0.0
&& self.tick >= 0.0
&& self.exo >= 0.0
&& self.exe >= 0.0
&& self.gap >= 0.0
&& self.lfac > 0.0
&& (0..=8).contains(&self.dec)
}
}
/// DIMSTYLE-Tabelleneintrag: Architekturstrich statt Pfeil (DIMTSZ), Masszahl über der Masslinie, in
/// Linienrichtung (DIMTAD 1, DIMTIH/DIMTOH aus), Dezimalzahl mit Punkt (DIMLUNIT 2, DIMDSEP '.').
pub fn make_dimstyle(d: &DimStyleDef) -> DimStyle {
let mut s = DimStyle::new(d.name.clone());
s.dimscale = d.scale;
s.dimtxt = d.txt;
s.dimtsz = d.tick / 2.0; // Strich reicht je Seite um die Hälfte
s.dimasz = d.tick / 2.0;
s.dimexo = d.exo;
s.dimexe = d.exe;
s.dimgap = d.gap;
s.dimdle = 0.0;
s.dimtad = 1;
s.dimtih = false;
s.dimtoh = false;
s.dimjust = 0;
s.dimdec = d.dec;
s.dimlfac = d.lfac;
s.dimlunit = 2;
s.dimdsep = '.' as i16;
s.dimzin = 0;
s.dimpost = d.post.clone();
s.dimtxsty = d.text_style.clone();
s
}
/// Masszahl wie CAD sie aus dem Stil bildet: `wert × lfac` auf `dec` Stellen, in `post` an Stelle von `<>`.
pub fn format_measurement(d: &DimStyleDef, meters: f64) -> String {
let num = format!("{:.*}", d.dec.max(0) as usize, meters * d.lfac);
if d.post.contains("<>") {
d.post.replace("<>", &num)
} else if d.post.is_empty() {
num
} else {
// Ein Format ohne Platzhalter ersetzt die Zahl (wie in CAD) — hier nie gewollt: Zahl behalten.
num
}
}
/// Eine ausgerichtete Bemassung samt Inhalt ihres Anonymblocks (Weltkoordinaten, Ebene `layer`).
pub struct BuiltDimension {
pub entity: DimensionAligned,
pub block_entities: Vec<EntityType>,
}
/// `p1`/`p2` = bemessene Punkte, `on_line` = ein Punkt auf der Masslinie (legt Seite und Abstand fest),
/// `text_at` = freie Lage der Masszahl (Mitte), sonst Standardlage. `None` bei entarteten Eingaben
/// (NaN, Länge 0, ungültiger Stil).
pub fn build_aligned(
style: &DimStyleDef,
block_name: &str,
layer: &str,
p1: [f64; 2],
p2: [f64; 2],
on_line: [f64; 2],
text_at: Option<[f64; 2]>,
) -> Option<BuiltDimension> {
if !style.is_valid() {
return None;
}
let all = [p1[0], p1[1], p2[0], p2[1], on_line[0], on_line[1]];
if !all.iter().all(|v| v.is_finite()) {
return None;
}
if let Some(t) = text_at {
if !t.iter().all(|v| v.is_finite()) {
return None;
}
}
let (dx, dy) = (p2[0] - p1[0], p2[1] - p1[1]);
let len = dx.hypot(dy);
if len < 1e-9 {
return None;
}
let (ux, uy) = (dx / len, dy / len);
let (nx, ny) = (-uy, ux); // linke Normale wie im Dossier-Plan
let offset = (on_line[0] - p1[0]) * nx + (on_line[1] - p1[1]) * ny;
let sign = if offset >= 0.0 { 1.0 } else { -1.0 };
let s = style.scale;
let dim_a = [p1[0] + nx * offset, p1[1] + ny * offset];
let dim_b = [p2[0] + nx * offset, p2[1] + ny * offset];
// Lesewinkel der Masszahl: nie kopfüber.
let mut angle = uy.atan2(ux);
if angle.cos() < 0.0 {
angle += std::f64::consts::PI;
}
angle = angle.rem_euclid(2.0 * std::f64::consts::PI);
let (up_x, up_y) = (-angle.sin(), angle.cos());
let h = style.txt * s;
let mid = [(dim_a[0] + dim_b[0]) / 2.0, (dim_a[1] + dim_b[1]) / 2.0];
// Mitte der Zahl: Unterkante `gap` über der Masslinie.
let default_mid = [mid[0] + up_x * (style.gap * s + h / 2.0), mid[1] + up_y * (style.gap * s + h / 2.0)];
let text_mid = text_at.unwrap_or(default_mid);
let mut ents: Vec<EntityType> = Vec::new();
let line = |a: [f64; 2], b: [f64; 2]| EntityType::Line(Line::from_coords(a[0], a[1], 0.0, b[0], b[1], 0.0));
let exo = style.exo * s * sign;
let exe = style.exe * s * sign;
// Masshilfslinien: Abstand `exo` zum Punkt bis `exe` über die Masslinie hinaus.
ents.push(line([p1[0] + nx * exo, p1[1] + ny * exo], [dim_a[0] + nx * exe, dim_a[1] + ny * exe]));
ents.push(line([p2[0] + nx * exo, p2[1] + ny * exo], [dim_b[0] + nx * exe, dim_b[1] + ny * exe]));
ents.push(line(dim_a, dim_b)); // Masslinie
// Architekturstriche: 45°-Diagonale (Winkelhalbierende von Linienrichtung und Normale), an beiden
// Enden parallel.
if style.tick > 0.0 {
let (tx, ty) = ((ux + nx) / std::f64::consts::SQRT_2, (uy + ny) / std::f64::consts::SQRT_2);
let half = style.tick * s / 2.0;
for p in [dim_a, dim_b] {
ents.push(line([p[0] - tx * half, p[1] - ty * half], [p[0] + tx * half, p[1] + ty * half]));
}
}
let value = format_measurement(style, len);
let mut txt = Text::with_value(value, Vector3::new(text_mid[0], text_mid[1], 0.0)).with_height(h).with_rotation(angle);
txt.horizontal_alignment = TextHorizontalAlignment::Middle;
txt.alignment_point = Some(Vector3::new(text_mid[0], text_mid[1], 0.0));
txt.style = style.text_style.clone();
ents.push(EntityType::Text(txt));
for e in &mut ents {
e.common_mut().layer = layer.to_string();
}
let mut dim = DimensionAligned::new(Vector3::new(p1[0], p1[1], 0.0), Vector3::new(p2[0], p2[1], 0.0));
dim.definition_point = Vector3::new(dim_b[0], dim_b[1], 0.0);
dim.base.definition_point = dim.definition_point;
dim.base.text_middle_point = Vector3::new(text_mid[0], text_mid[1], 0.0);
dim.base.attachment_point = AttachmentPointType::MiddleCenter;
dim.base.style_name = style.name.clone();
dim.base.block_name = block_name.to_string();
dim.base.actual_measurement = len;
dim.base.common.layer = layer.to_string();
if text_at.is_some() {
dim.base.text_user_positioned = true;
dim.base.dwg_flags_byte = 0x00;
}
Some(BuiltDimension { entity: dim, block_entities: ents })
}
/// Wrapper für den Dokument-Aufbau.
pub fn into_entity(d: DimensionAligned) -> EntityType {
EntityType::Dimension(Box::new(Dimension::Aligned(d)))
}
#[cfg(test)]
mod tests {
use super::*;
fn style() -> DimStyleDef {
DimStyleDef {
name: "DOSSIER_1-100".into(),
text_style: "DOSSIER".into(),
scale: 100.0,
txt: 0.004,
tick: 0.003,
exo: 0.001,
exe: 0.001,
gap: 0.0024,
dec: 2,
lfac: 1.0,
post: String::new(),
}
}
#[test]
fn messzahl_formatierung() {
let mut s = style();
assert_eq!(format_measurement(&s, 3.254), "3.25");
s.lfac = 100.0;
s.dec = 0;
s.post = "<> cm".into();
assert_eq!(format_measurement(&s, 3.254), "325 cm");
}
#[test]
fn block_hat_hilfslinien_masslinie_striche_und_text() {
let b = build_aligned(&style(), "*D1", "BEM", [10.0, 5.0], [14.0, 5.0], [10.0, 6.0], None).unwrap();
assert_eq!(b.block_entities.len(), 2 + 1 + 2 + 1);
assert_eq!(b.entity.base.block_name, "*D1");
assert!((b.entity.base.actual_measurement - 4.0).abs() < 1e-12);
// Masslinie 1 m über den Punkten.
let EntityType::Line(l) = &b.block_entities[2] else { panic!() };
assert!((l.start.y - 6.0).abs() < 1e-12 && (l.end.x - 14.0).abs() < 1e-12);
// Masshilfslinie: 0.1 m Abstand, reicht 0.1 m über die Masslinie.
let EntityType::Line(e) = &b.block_entities[0] else { panic!() };
assert!((e.start.y - 5.1).abs() < 1e-9 && (e.end.y - 6.1).abs() < 1e-9);
// Text: Höhe 0.4 m, Wert 4.00, über der Linie, Lesewinkel 0.
let EntityType::Text(t) = b.block_entities.last().unwrap() else { panic!() };
assert_eq!(t.value, "4.00");
assert!((t.height - 0.4).abs() < 1e-12 && t.rotation.abs() < 1e-12);
assert!(t.insertion_point.y > 6.0);
}
#[test]
fn text_nie_kopfueber_und_seite_folgt_dem_vorzeichen() {
// Kette von rechts nach links: Lesewinkel wieder nach rechts (0), nicht π.
let b = build_aligned(&style(), "*D2", "0", [14.0, 5.0], [10.0, 5.0], [14.0, 4.0], None).unwrap();
let EntityType::Text(t) = b.block_entities.last().unwrap() else { panic!() };
assert!(t.rotation.sin().abs() < 1e-12 && t.rotation.cos() > 0.0);
// Linke Normale von (−1, 0) ist (0, −1): Offset −1 m liegt bei y = 6, die Linie also über den Punkten.
let b = build_aligned(&style(), "*D3", "0", [10.0, 5.0], [14.0, 5.0], [10.0, 4.0], None).unwrap();
let EntityType::Line(l) = &b.block_entities[2] else { panic!() };
assert!((l.start.y - 4.0).abs() < 1e-12);
}
#[test]
fn entartete_eingaben_ergeben_none() {
assert!(build_aligned(&style(), "*D1", "0", [0.0, 0.0], [0.0, 0.0], [0.0, 1.0], None).is_none());
assert!(build_aligned(&style(), "*D1", "0", [f64::NAN, 0.0], [1.0, 0.0], [0.0, 1.0], None).is_none());
let mut s = style();
s.scale = 0.0;
assert!(build_aligned(&s, "*D1", "0", [0.0, 0.0], [1.0, 0.0], [0.0, 1.0], None).is_none());
s = style();
s.dec = 99;
assert!(!s.is_valid());
}
}
+1
View File
@@ -11,6 +11,7 @@
// acadrust: `DxfReader::from_reader(Cursor<Vec<u8>>)` (Read + Seek + 'static) — ohne Dateisystem, WASM-tauglich.
pub mod export;
pub mod export_dim;
pub mod common;
pub mod import;
pub mod split;
+1
View File
@@ -4001,6 +4001,7 @@ export default function App() {
{exportDxfOpen && (
<ExportDxfDialog
planTitle={activeLevel.name}
initialScale={scaleDenominator}
selectionCount={selectionLockIds.length}
onExport={onExportDxf}
onClose={() => setExportDxfOpen(false)}
+7 -4
View File
@@ -9,7 +9,7 @@
// json = render2d-Szene (planToRenderScene)
// dossier-cli <projekt.obp> section <Name> [--out schnitt.svg] (braucht render3d-WASM)
// dossier-cli <projekt.obp> elevation <Name> [--out ansicht.svg]
// dossier-cli <projekt.obp> dxf [--binary]|dwg|ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun [--level EG] [--out datei]
// dossier-cli <projekt.obp> dxf [--binary] [--scale 100] [--dim-unit cm] [--layout]|dwg|ifc|step|obj|stl|glb|gltf|schedule|kennzahlen|sun [--level EG] [--out datei]
// glb/gltf = glTF 2.0 (Y-up, Meter, Geschoss als Eltern; --flat ohne Geschoss-Knoten)
// dossier-cli convert <eingabe> <ausgabe> [--cmd "befehl"]… Format nach Endung: dxf/dwg/ifc/obp → obp-Import,
// obp → dxf/dwg/ifc/obj/stl/glb/gltf/step; --cmd: weitere Befehle
@@ -578,9 +578,12 @@ async function execute(project: Project, file: string, command: string, rest: st
const world = projectToWorldCoords(project);
const plan = generatePlan(world, lvl.id, allCodes);
await loadFileio();
if (command === "dxf" && args.flags.has("binary")) out(args, buildPlanDxfBinary(plan, world), `${lvl.name}.dxf`);
else if (command === "dxf") out(args, buildPlanDxf(plan, world), `${lvl.name}.dxf`);
else out(args, buildPlanDwg(plan, world), `${lvl.name}.dwg`);
// --scale N (Massstabsnenner, Default 100): Bemassungsstil, Linientypen, Raumstempel, Ansichtsfenster.
// --dim-unit cm: Masszahlen in Zentimetern; --layout: zusätzlich Papierbereich mit Ansichtsfenster.
const cad = { scaleDenominator: scale, dimUnit: args.flags.get("dim-unit") === "cm" ? ("cm" as const) : ("m" as const), paperLayout: args.flags.has("layout") };
if (command === "dxf" && args.flags.has("binary")) out(args, buildPlanDxfBinary(plan, world, cad), `${lvl.name}.dxf`);
else if (command === "dxf") out(args, buildPlanDxf(plan, world, cad), `${lvl.name}.dxf`);
else out(args, buildPlanDwg(plan, world, cad), `${lvl.name}.dwg`);
return 0;
}
case "ifc":
+76
View File
@@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import { dashToLtypeMeters, fontNameOf, ltypeNameFor, paperFor, primitiveToLocal, roundKey } from "./dxfCadParts";
import type { LineStyle } from "../model/types";
import type { Primitive } from "../plan/generatePlan";
describe("fontNameOf", () => {
it("erste echte Familie, ohne Anführungszeichen; generische/Variablen übersprungen", () => {
expect(fontNameOf('"Helvetica Neue", Arial, sans-serif')).toBe("Helvetica Neue");
expect(fontNameOf("var(--font-ui, sans-serif)")).toBeNull();
expect(fontNameOf("sans-serif, Arial")).toBe("Arial");
expect(fontNameOf("'Source Sans 3'")).toBe("Source Sans 3");
expect(fontNameOf(undefined)).toBeNull();
expect(fontNameOf("")).toBeNull();
});
});
describe("Linientypen", () => {
it("Papier-mm × Massstab → Meter (Strich +, Lücke −); ungerade Muster werden verdoppelt", () => {
expect(dashToLtypeMeters([3, 1], 100)!.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.3, -0.1]);
expect(dashToLtypeMeters([2, 1, 0.5], 50)!.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.1, -0.05, 0.025, -0.1, 0.05, -0.025]);
expect(dashToLtypeMeters([], 100)).toBeNull();
expect(dashToLtypeMeters([0, 0], 100)).toBeNull();
// Punkt (Strich 0) bleibt 0, Lücke nie 0
const dot = dashToLtypeMeters([0, 0], 100);
expect(dot).toBeNull();
expect(dashToLtypeMeters([0, 1], 100)![0]).toBe(0);
});
it("Name: Projekt-Linienstil mit gleichem Muster, sonst DOSSIER_STRICH_…", () => {
const styles = [{ id: "a", name: " Strichlinie ", weight: 0.1, color: "#000", dash: [3, 1] }] as LineStyle[];
expect(ltypeNameFor([3, 1], styles)).toBe("Strichlinie");
expect(ltypeNameFor([2, 0.5], styles)).toBe("DOSSIER_STRICH_2_0.5");
});
});
describe("Papierbereich", () => {
it("kleinstes Format, das den Ausschnitt samt Rand aufnimmt", () => {
// 20 m × 12 m bei 1:100 = 200 × 120 mm + 20 mm Rand → A4 quer
expect(paperFor(20, 12, 100)).toMatchObject({ name: "A4", paperW: 297, paperH: 210, vpW: 277, vpH: 190 });
// 30 m × 18 m bei 1:100 → 300 × 180 (+20): A3
expect(paperFor(30, 18, 100).name).toBe("A3");
// Hochformat, wenn nur so passend
expect(paperFor(12, 20, 100)).toMatchObject({ name: "A4", paperW: 210, paperH: 297 });
// grösser als A0: Sonderformat in 10-mm-Schritten
const big = paperFor(200, 100, 50);
expect(big.name).toBe("Sonder");
expect(big.paperW % 10).toBe(0);
});
});
describe("primitiveToLocal", () => {
const frame = { origin: { x: 10, y: 5 }, rot: Math.PI / 2, scale: 2 };
it("Linie, Bogen, Kreis, Text: verschoben, gedreht, skaliert", () => {
const line = { kind: "line", a: { x: 10, y: 5 }, b: { x: 10, y: 9 }, cls: "x", weightMm: 0.1 } as Primitive;
const l = primitiveToLocal(line, frame) as Extract<Primitive, { kind: "line" }>;
expect(l.a.x).toBeCloseTo(0, 12);
expect(l.a.y).toBeCloseTo(0, 12);
expect(l.b.x).toBeCloseTo(2, 12); // 4 m in Richtung +y = lokale +x, durch Skalierung 2
expect(l.b.y).toBeCloseTo(0, 12);
const text = { kind: "drawingText", at: { x: 10, y: 5 }, text: "a", heightM: 0.4, angle: Math.PI / 2, color: "#000" } as Primitive;
const t = primitiveToLocal(text, frame) as Extract<Primitive, { kind: "drawingText" }>;
expect(t.heightM).toBeCloseTo(0.2, 12);
expect(t.angle).toBeCloseTo(0, 12);
const circle = { kind: "drawingCircle", center: { x: 10, y: 7 }, r: 1, fill: "none", stroke: "#000", weightMm: 0.1 } as Primitive;
const c = primitiveToLocal(circle, frame) as Extract<Primitive, { kind: "drawingCircle" }>;
expect(c.r).toBeCloseTo(0.5, 12);
expect(c.center.x).toBeCloseTo(1, 12);
});
it("andere Primitivarten (Raumstempel, Bild) gehören nicht in Blöcke", () => {
expect(primitiveToLocal({ kind: "drawingImage" } as Primitive, frame)).toBeNull();
});
it("roundKey: auf 1 mm gerundet", () => {
expect(roundKey([1.0001, 2])).toBe(roundKey([1.0004, 2]));
expect(roundKey([1.0001, 2])).not.toBe(roundKey([1.002, 2]));
});
});
+129
View File
@@ -0,0 +1,129 @@
// Bausteine des Fachplaner-Exports ([C2], 28.10.): reine Hilfsfunktionen für `exportDxf.ts` —
// Schriftname aus CSS-Familie, Linientyp-Namen aus Strichmustern, Umrechnung von Plan-Primitiven in ein
// lokales Koordinatensystem (für Blöcke) und Papierformate. Keine Abhängigkeit vom Writer.
import type { Primitive } from "../plan/generatePlan";
import type { LineStyle, Vec2 } from "../model/types";
/** Erste Schriftfamilie aus einem CSS-`font-family`-Wert ohne Anführungszeichen; generische Familien/CSS-Variablen → null. */
export function fontNameOf(css: string | undefined | null): string | null {
if (!css) return null;
// `var(--font-ui, sans-serif)` enthält selbst ein Komma: vor dem Teilen entfernen.
for (const raw of css.replace(/var\([^)]*\)/g, "").split(",")) {
const name = raw.trim().replace(/^["']|["']$/g, "").trim();
if (!name) continue;
if (/^(sans-serif|serif|monospace|cursive|fantasy|system-ui|ui-sans-serif|inherit|initial)$/i.test(name)) continue;
return name;
}
return null;
}
/** Strichmuster (Papier-mm, an/aus/…) → DXF-Linientyp-Elemente in Modell-Metern (Strich +, Lücke −, Punkt 0). */
export function dashToLtypeMeters(dashMm: number[], scaleDenominator: number): number[] | null {
let pat = dashMm.map((d) => (Number.isFinite(d) ? Math.max(0, d) : 0));
if (pat.length === 0 || pat.every((d) => d === 0)) return null;
if (pat.length % 2 === 1) pat = pat.concat(pat);
const k = scaleDenominator / 1000;
const out: number[] = [];
for (let i = 0; i < pat.length; i++) {
const len = pat[i] * k;
out.push(i % 2 === 0 ? len : -Math.max(len, 1e-6));
}
// Eine Lücke von 0 ergäbe ein Muster ohne Unterbrechung; mindestens 1 µm.
return out;
}
/** Zahl für Namen: höchstens 2 Nachkommastellen, ohne Nullen am Ende. */
function n2(v: number): string {
return String(Math.round(v * 100) / 100);
}
/**
* Name des Linientyps zu einem Strichmuster: der Name des Projekt-Linienstils mit demselben Muster, sonst
* `DOSSIER_STRICH_<an>_<aus>…` (Papier-mm).
*/
export function ltypeNameFor(dashMm: number[], styles: readonly LineStyle[]): string {
const same = (a: number[], b: number[]) => a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) < 1e-9);
const hit = styles.find((s) => s.dash && s.dash.length > 0 && (s.kind ?? "dash") === "dash" && same(s.dash, dashMm));
if (hit && hit.name.trim()) return hit.name.trim();
return `DOSSIER_STRICH_${dashMm.map(n2).join("_")}`;
}
// ── Lokales Koordinatensystem (Blöcke) ────────────────────────────────────────
/** Abbildung Modell → blocklokal: Verschiebung `-origin`, Drehung `-rot`, Skalierung `1/scale`. */
export interface LocalFrame {
origin: Vec2;
/** Drehung des Blocks im Modell (Radiant). */
rot: number;
scale: number;
}
function toLocal(f: LocalFrame, p: Vec2): Vec2 {
const c = Math.cos(f.rot);
const s = Math.sin(f.rot);
const dx = p.x - f.origin.x;
const dy = p.y - f.origin.y;
return { x: (dx * c + dy * s) / f.scale, y: (-dx * s + dy * c) / f.scale };
}
/** Primitive im lokalen System des Blocks (nur Geometrie-Arten, die in Blöcken vorkommen); andere → null. */
export function primitiveToLocal(p: Primitive, f: LocalFrame): Primitive | null {
const rotDeg = (f.rot * 180) / Math.PI;
switch (p.kind) {
case "line":
return { ...p, a: toLocal(f, p.a), b: toLocal(f, p.b), motif: undefined, zigzag: p.zigzag && { amplitude: p.zigzag.amplitude / f.scale, wavelength: p.zigzag.wavelength / f.scale } };
case "arc":
return { ...p, center: toLocal(f, p.center), from: toLocal(f, p.from), to: toLocal(f, p.to), r: p.r / f.scale };
case "polygon":
return { ...p, pts: p.pts.map((q) => toLocal(f, q)), hatch: { ...p.hatch, angle: p.hatch.angle - rotDeg } };
case "drawingCircle":
return { ...p, center: toLocal(f, p.center), r: p.r / f.scale };
case "drawingArc":
return { ...p, center: toLocal(f, p.center), r: p.r / f.scale, a0: p.a0 - f.rot, a1: p.a1 - f.rot };
case "drawingText":
return { ...p, at: toLocal(f, p.at), heightM: p.heightM / f.scale, angle: p.angle - f.rot, wrapWidth: p.wrapWidth && p.wrapWidth / f.scale };
default:
return null;
}
}
/** Schlüssel gleicher lokaler Geometrie: Zahlen auf 1 mm gerundet (Blöcke teilen sich nur identische Inhalte). */
export function roundKey(nums: readonly number[]): string {
let out = "";
for (const v of nums) out += `${Math.round(v * 1000)},`;
return out;
}
// ── Papierbereich ────────────────────────────────────────────────────────────
/** Papierformate (mm, quer) in aufsteigender Grösse. */
const PAPER_SIZES: [string, number, number][] = [
["A4", 297, 210],
["A3", 420, 297],
["A2", 594, 420],
["A1", 841, 594],
["A0", 1189, 841],
];
/**
* Papier und Ansichtsfenster für einen Ausschnitt der Grösse `w` × `h` Meter im Massstab 1:`scale`:
* kleinstes A-Format (quer, sonst hoch), das den Ausschnitt mit `margin` mm Rand aufnimmt; ist keines
* gross genug, ein Sonderformat in Vielfachen von 10 mm. Das Fenster füllt das Papier abzüglich Rand.
*/
export function paperFor(
w: number,
h: number,
scale: number,
margin = 10,
): { paperW: number; paperH: number; vpW: number; vpH: number; name: string } {
const needW = (w * 1000) / scale + 2 * margin;
const needH = (h * 1000) / scale + 2 * margin;
for (const [name, pw, ph] of PAPER_SIZES) {
if (needW <= pw && needH <= ph) return { paperW: pw, paperH: ph, vpW: pw - 2 * margin, vpH: ph - 2 * margin, name };
if (needW <= ph && needH <= pw) return { paperW: ph, paperH: pw, vpW: ph - 2 * margin, vpH: pw - 2 * margin, name };
}
const pw = Math.ceil(needW / 10) * 10;
const ph = Math.ceil(needH / 10) * 10;
return { paperW: pw, paperH: ph, vpW: pw - 2 * margin, vpH: ph - 2 * margin, name: "Sonder" };
}
+251
View File
@@ -0,0 +1,251 @@
// Fachplaner-Export ([C2], 28.10.): DIMENSION mit Anonymblock und DIMSTYLE, BLOCK/INSERT/ATTRIB für Türen,
// Fenster und Möbelblöcke, Linientypen, Textstile, Papierbereich — gegengelesen mit ezdxf (Auditor, wie
// ein CAD-Programm die Datei sieht), libredwg (DWG) und dem eigenen DXF-Import. ezdxf-Teile werden ohne
// `pip install ezdxf` übersprungen (Muster `exportDxf.ezdxf.test.ts`).
import "../engine/fileioWasm.setup";
import { describe, expect, it } from "vitest";
import { spawnSync } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildPlanDwg, buildPlanDxf, buildPlanDxfBinary, collectPlanDrawing } from "./exportDxf";
import { countByType, libreDwgReader, readDxf } from "./cadReadBack.testutil";
import { parseDxf } from "../io/dxfParser";
import { sampleProject } from "../model/sampleProject";
import { generatePlan } from "../plan/generatePlan";
import { flattenCategories } from "../model/types";
import type { Drawing2D, Project } from "../model/types";
const hasEzdxf = spawnSync("python3", ["-c", "import ezdxf"]).status === 0;
const allCodes = (p: Project) => new Set(flattenCategories(p.layers).map((l) => l.code));
/** Demo-Haus plus Bemassungskette, gestrichelte Linie, Möbelblock (2 Instanzen), Text mit Schrift. */
function cadProject(): Project {
const code = "90";
const d = (id: string, geom: Drawing2D["geom"], extra: Partial<Drawing2D> = {}): Drawing2D =>
({ id, type: "drawing2d", levelId: "eg", categoryCode: code, geom, ...extra }) as Drawing2D;
return {
...sampleProject,
lineStyles: [...sampleProject.lineStyles, { id: "ls-dash", name: "Strichlinie 0.3/0.1", weight: 0.13, color: "#000000", dash: [3, 1] }],
textStyles: [{ id: "body", label: "Text", marks: { font: '"Helvetica Neue", Arial, sans-serif' } }],
blockDefs: [
{
id: "bd-sofa",
name: "Sofa",
geom2d: [
{ shape: "rect", min: { x: -0.9, y: -0.4 }, max: { x: 0.9, y: 0.4 } },
{ shape: "line", a: { x: -0.9, y: 0.2 }, b: { x: 0.9, y: 0.2 } },
],
},
],
drawings2d: [
d("dim1", { shape: "dimension", pts: [{ x: 0, y: -1 }, { x: 2, y: -1 }, { x: 5, y: -1 }], offset: -0.8 }),
d("dash1", { shape: "line", a: { x: 0, y: -2 }, b: { x: 4, y: -2 } }, { lineStyleId: "ls-dash" }),
d("sofa1", { shape: "block", blockDefId: "bd-sofa", at: { x: 1.5, y: 1 }, rotation: 0 }),
d("sofa2", { shape: "block", blockDefId: "bd-sofa", at: { x: 3.5, y: 2.5 }, rotation: Math.PI / 2, scale: 1.5 }),
d("txt1", { shape: "text", at: { x: 1, y: 4 }, text: "Müller & Söhne", height: 0.2, angle: 0 }),
],
};
}
interface Ez {
version: string;
errors: string[];
entities: Array<Record<string, unknown> & { type: string; layer: string }>;
blocks: Record<string, { entities: Record<string, number>; anonymous: boolean }>;
styles: Record<string, string | null>;
fonts: Record<string, string>;
linetypes: Record<string, number[]>;
dimstyles: Record<string, Record<string, unknown>>;
layouts: Record<string, { viewports: Array<{ id: number; center: number[]; size: number[]; view_center: number[]; view_height: number }>; paper: number[] | null }>;
}
function ezdxf(name: string, data: string | Uint8Array): { status: number | null; r: Ez; err: string } {
const dir = mkdtempSync(join(tmpdir(), "dossier-cad-"));
const file = join(dir, `${name}.dxf`);
writeFileSync(file, data);
const p = spawnSync("python3", ["scripts/validate-dxf.py", file], { encoding: "utf8", timeout: 60_000 });
let r = null as unknown as Ez;
try {
r = JSON.parse(p.stdout) as Ez;
} catch {
/* Fehlertext unten */
}
return { status: p.status, r, err: `${p.stdout}\n${p.stderr}` };
}
describe("Fachplaner-Export: Sammler", () => {
const project = cadProject();
const plan = generatePlan(project, "eg", allCodes(project));
it("Bemassung, Blöcke und Öffnungen werden zu CAD-Objekten statt zu losen Linien", () => {
const { model, blocks } = collectPlanDrawing(plan, project).stats();
expect(model.DIMENSION).toBe(2); // zwei Segmente der Kette
expect(model.INSERT).toBe(3 + 2); // Tür + 2 Fenster des Demo-Hauses, 2 Sofas
expect(blocks.LINE).toBeGreaterThan(0);
// Bemassung: ihre Linien/Texte stehen nicht zusätzlich lose im Modellbereich.
const dimPrims = plan.primitives.filter((p) => "drawingId" in p && p.drawingId === "dim1").length;
expect(dimPrims).toBeGreaterThan(0);
const loose = collectPlanDrawing({ ...plan, primitives: plan.primitives.filter((p) => !("drawingId" in p && p.drawingId === "dim1")) }, project).stats();
expect(loose.model.LINE).toBe(model.LINE);
expect(loose.model.TEXT).toBe(model.TEXT);
});
it("Massstab und Einheit wirken auf Stil und Masszahl", () => {
const [flat] = collectPlanDrawing(plan, project, { scaleDenominator: 50, dimUnit: "cm" }).args();
expect(flat.length).toBeGreaterThan(0);
const dxf = readDxf(buildPlanDxf(plan, project, { scaleDenominator: 50, dimUnit: "cm" }));
expect(dxf.entities.filter((e) => e.type === "DIMENSION").length).toBe(2);
});
});
describe.skipIf(!hasEzdxf)("Fachplaner-Export gegen ezdxf", { timeout: 60_000 }, () => {
const project = cadProject();
const plan = generatePlan(project, "eg", allCodes(project));
const read = (opts = {}) => {
const x = ezdxf("cad", buildPlanDxf(plan, project, opts));
expect(x.r, x.err).not.toBeNull();
expect(x.r.errors).toEqual([]);
expect(x.status).toBe(0);
return x.r;
};
it("DIMENSION: ausgerichtet, mit *D-Block (Hilfslinien, Masslinie, 2 Striche, Zahl) und Stil 1:100", () => {
const r = read();
const dims = r.entities.filter((e) => e.type === "DIMENSION");
expect(dims.map((d) => d.measurement as number)).toEqual([expect.closeTo(2, 9), expect.closeTo(3, 9)]);
for (const d of dims) {
expect((d.dimtype as number) & 7).toBe(1); // ausgerichtet
expect(d.dimstyle).toBe("DOSSIER_1-100");
const block = r.blocks[d.block as string];
expect(block?.anonymous, String(d.block)).toBe(true);
expect(block.entities).toEqual({ LINE: 5, TEXT: 1 });
}
const st = r.dimstyles["DOSSIER_1-100"];
expect(st).toMatchObject({ dimscale: 100, dimtad: 1, dimdec: 2, dimlfac: 1, dimtxsty: "DOSSIER" });
expect(st.dimtxt as number).toBeCloseTo(0.004, 9); // 4 mm Papier
expect(st.dimtsz as number).toBeCloseTo(0.0015, 9); // Architekturstrich 3 mm
});
it("Bemassungsstil im Massstab 1:50 und in cm", () => {
const r = read({ scaleDenominator: 50, dimUnit: "cm" });
const st = r.dimstyles["DOSSIER_1-50_cm"];
expect(st).toMatchObject({ dimscale: 50, dimdec: 0, dimlfac: 100 });
const block = r.blocks[r.entities.find((e) => e.type === "DIMENSION")!.block as string];
expect(block.entities.TEXT).toBe(1);
});
it("Türen/Fenster: INSERT in Wandrichtung mit Attributen, Block mit Geometrie", () => {
const r = read();
const ins = r.entities.filter((e) => e.type === "INSERT" && !(e.name as string).startsWith("Sofa"));
expect(ins.length).toBe(3);
const door = ins.find((i) => (i.attribs as Record<string, string>).TYP === "Tür")!;
expect(door.name).toBe("Tuer_90x210");
expect(door.attribs).toMatchObject({ ID: "D1", BREITE_M: "0.90", HOEHE_M: "2.10", TYPENAME: expect.any(String) });
expect(door.layer).toMatch(/^21_/); // Ebene der Kategorie „Türen/Fenster“
expect(r.blocks[door.name as string].entities.LINE).toBeGreaterThan(0);
const win = ins.find((i) => (i.attribs as Record<string, string>).TYP === "Fenster")!;
expect(win.attribs).toMatchObject({ BRUESTUNG_M: "0.90" });
});
it("Möbelblock: ein BLOCK je Definition, zwei INSERTs mit Drehung und Skalierung", () => {
const r = read();
const sofas = r.entities.filter((e) => e.type === "INSERT" && e.name === "Sofa");
expect(sofas.length).toBe(2);
expect(sofas[0].at).toEqual([1.5, 1]);
expect(sofas[1].rotation as number).toBeCloseTo(90, 9);
expect(sofas[1].scale).toEqual([1.5, 1.5]);
expect(r.blocks.Sofa.entities).toEqual({ LINE: 5 }); // Rechteck = 4 Linien + 1 Linie, lokal
// Geometrie lokal um den Einfügepunkt (Rechteck −0.9…0.9), nicht an der Weltlage
const sofaLines = r.entities.filter((e) => e.type === "LINE" && Math.abs((e.pts as number[][])[0][0] - 1.5) < 1.0 && Math.abs((e.pts as number[][])[0][1] - 1) < 0.5 && e.layer.startsWith("90_"));
expect(sofaLines.length).toBe(0); // keine losen Linien an der Weltlage
});
it("Strichmuster → Linientyp mit dem Namen des Projekt-Linienstils (Papier-mm × Massstab)", () => {
const r = read();
const lt = r.linetypes["Strichlinie_0.3_0.1"];
expect(lt).toBeDefined();
expect(lt.map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.3, -0.1]); // 3 mm / 1 mm Papier bei 1:100
const line = r.entities.find((e) => e.type === "LINE" && e.linetype === "Strichlinie_0.3_0.1");
expect(line).toBeDefined();
// 1:50 halbiert die Längen
const r50 = read({ scaleDenominator: 50 });
expect(r50.linetypes["Strichlinie_0.3_0.1"].map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0.15, -0.05]);
});
it("Textstile: Schriftname aus dem Projekt, Fallback Arial; Umlaute", () => {
const r = read();
expect(r.fonts.DOSSIER).toBe("Helvetica Neue");
const text = r.entities.find((e) => e.type === "TEXT" && e.text === "Müller & Söhne")!;
expect(text).toBeDefined();
expect(text.style).toBe("DOSSIER");
expect(text.halign).toBe(0);
const noFont = ezdxf("cad2", buildPlanDxf(plan, { ...project, textStyles: [] }));
expect(noFont.status, noFont.err).toBe(0);
expect(noFont.r.fonts.DOSSIER).toBe("Arial");
});
it("Raumstempel: Name und Fläche als zentrierte TEXTe im Massstab (Punkt → Meter)", () => {
const r = read();
const stamps = r.entities.filter((e) => e.type === "TEXT" && e.halign === 1);
expect(stamps.length).toBeGreaterThan(0);
const texts = stamps.map((e) => e.text as string);
expect(texts.some((t) => /m²/.test(t))).toBe(true);
for (const s of stamps) expect(s.height as number).toBeGreaterThan(0.2); // 10 pt bei 1:100 ≈ 0.35 m
});
it("Papierbereich: Layout mit Ansichtsfenster im Planmassstab", () => {
const r = read({ paperLayout: true });
const name = Object.keys(r.layouts).find((n) => n.startsWith("Plan_1-100"))!;
expect(name).toBeDefined();
const vp = r.layouts[name].viewports.find((v) => v.id === 2)!;
expect(vp).toBeDefined();
const [pw, ph] = r.layouts[name].paper!;
expect(vp.center[0]).toBeCloseTo(pw / 2, 6);
// Ausschnitt in Metern = Fenstergrösse (mm) / 10 (1:100)
expect(vp.view_height).toBeCloseTo(vp.size[1] / 10, 6);
expect(ph).toBeGreaterThan(0);
});
it("Binär-DXF trägt dieselben Objekte", () => {
const asc = ezdxf("asc", buildPlanDxf(plan, project));
const bin = ezdxf("bin", buildPlanDxfBinary(plan, project));
expect(bin.r.errors).toEqual([]);
expect(bin.status, bin.err).toBe(0);
expect(bin.r.entities).toEqual(asc.r.entities);
expect(Object.keys(bin.r.blocks)).toEqual(Object.keys(asc.r.blocks));
});
});
describe("Fachplaner-Export: DWG (libredwg) und eigener Import", () => {
const project = cadProject();
const plan = generatePlan(project, "eg", allCodes(project));
it("DWG R2018: DIMENSION, INSERT, Blöcke und Umlaute kommen an", async () => {
const db = (await libreDwgReader())(buildPlanDwg(plan, project, { paperLayout: true }));
const counts = countByType(db.entities);
expect(counts.DIMENSION).toBe(2);
expect(counts.INSERT).toBeGreaterThanOrEqual(5);
const text = db.entities.find((e) => e.type === "TEXT" && e.text?.startsWith("Müller"));
expect(text?.text).toBe("Müller & Söhne");
});
it("DXF-Import: Masszahlen, Möbelgeometrie und Türgeometrie kommen wieder an", () => {
const imp = parseDxf(buildPlanDxf(plan, project));
const texts = (imp.texts ?? []).map((t) => t.text);
expect(texts).toContain("2.00");
expect(texts).toContain("3.00");
expect(texts).toContain("Müller & Söhne");
// Möbel + Türen/Fenster sind als Geometrie vorhanden (Blöcke werden aufgelöst)
const lineCount = imp.contours.reduce((n, c) => n + c.contours.length, 0);
expect(lineCount).toBeGreaterThan(50);
expect(imp.diagnostics?.entityCounts.DIMENSION ?? imp.diagnostics?.entityCounts.INSERT).toBeDefined();
});
it("DXF-Import: Papierbereich wird als Layout erkannt", () => {
// Das Layout hat nur ein Ansichtsfenster (kein eigener Inhalt) und steht darum nicht in der Liste, ist aber lesbar.
const dxf = buildPlanDxf(plan, project, { paperLayout: true });
expect(() => parseDxf(dxf, "", "Plan_1-100")).not.toThrow();
});
});
+5 -1
View File
@@ -66,7 +66,11 @@ describe.skipIf(!hasEzdxf)("DXF-Export gegen ezdxf", { timeout: 60_000 }, () =>
expect(r.status).toBe(0);
expect(r.result!.version).toBe("AC1032");
expect(r.result!.insunits).toBe(6);
const polys = plan.primitives.filter((p): p is Extract<Plan["primitives"][number], { kind: "polygon" }> => p.kind === "polygon");
// Ohne unsichtbare Pick-Bänder und ohne Öffnungs-Polygone (Fensterrahmen liegen im Block, nicht im Modellbereich).
const polys = plan.primitives.filter(
(p): p is Extract<Plan["primitives"][number], { kind: "polygon" }> =>
p.kind === "polygon" && !p.openingId && !(p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none"),
);
const ezPolys = r.result!.entities.filter((e) => e.type === "LWPOLYLINE");
expect(ezPolys.length).toBe(polys.length);
for (let i = 0; i < polys.length; i++) {
+12 -25
View File
@@ -21,32 +21,15 @@ import { projectToWorldCoords } from "../model/geoRebase";
const allCodes = (p: Project) => new Set(flattenCategories(p.layers).map((l) => l.code));
/** Was die flache Zeichnung an Entitäten trägt (Zählung je Typ, aus dem Puffer). */
/** Was die flache Zeichnung an Entitäten im Modellbereich trägt (Zählung je Typ, im Sammler mitgeführt). */
function flatCounts(plan: Plan, project: Project): Record<string, number> {
const [flat] = collectPlanDrawing(plan, project).args();
const names: Record<number, [string, (i: number) => number]> = {
1: ["", () => 4],
2: ["LINE", () => 6],
3: ["LWPOLYLINE", (i) => 4 + 2 * flat[i + 3]],
4: ["ARC", () => 7],
5: ["CIRCLE", () => 5],
6: ["TEXT", () => 7],
// HATCH: tag, layer, mode, rgb, n_dash, dash…, n_fam, (angle, spacing)…, n, pts…
7: ["HATCH", (i) => {
const nd = flat[i + 4];
const nf = flat[i + 5 + nd];
return 5 + nd + 1 + 2 * nf + 1 + 2 * flat[i + 5 + nd + 1 + 2 * nf];
}],
};
const out: Record<string, number> = {};
for (let i = 1; i < flat.length; ) {
const [name, len] = names[flat[i]];
if (name) out[name] = (out[name] ?? 0) + 1;
i += len(i);
}
return out;
return collectPlanDrawing(plan, project).stats().model;
}
/** Polygone, die der Export schreibt: unsichtbare Pick-Bänder (weder Füllung noch Umriss noch Schraffur) entfallen. */
const visiblePolys = (polys: Extract<Plan["primitives"][number], { kind: "polygon" }>[]) =>
polys.filter((p) => !p.openingId && !(p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none" && p.hatch.kind !== "gradient"));
describe("DXF-Export (R2018 über acadrust)", () => {
const plan = generatePlan(sampleProject, "eg", allCodes(sampleProject));
@@ -66,7 +49,11 @@ describe("DXF-Export (R2018 über acadrust)", () => {
it("jede übergebene Entität kommt an (Typ, Anzahl, Reihenfolge der Ebenen)", () => {
const dxf = readDxf(buildPlanDxf(plan, sampleProject));
expect(countByType(dxf.entities)).toEqual(flatCounts(plan, sampleProject));
// ATTRIB/SEQEND hängen an den INSERTs (Türen/Fenster) und zählen nicht als eigene Entitäten des Plans.
const { ATTRIB, SEQEND, ...entities } = countByType(dxf.entities);
expect(ATTRIB ?? 0).toBeGreaterThanOrEqual(entities.INSERT ?? 0); // jede Tür/jedes Fenster trägt Attribute
expect(SEQEND ?? 0).toBe(entities.INSERT ?? 0);
expect(entities).toEqual(flatCounts(plan, sampleProject));
expect(dxf.entities.every((e) => dxf.layers.has(e.layer))).toBe(true);
});
@@ -104,7 +91,7 @@ describe("Georeferenz (LV95)", () => {
};
const world = projectToWorldCoords(anchored);
const plan = generatePlan(world, "eg", allCodes(world));
const polys = plan.primitives.filter((p): p is Extract<Plan["primitives"][number], { kind: "polygon" }> => p.kind === "polygon");
const polys = visiblePolys(plan.primitives.filter((p): p is Extract<Plan["primitives"][number], { kind: "polygon" }> => p.kind === "polygon"));
it("DXF: Polylinien-Koordinaten bitgleich zum Plan (f64, keine Rundung)", () => {
const ents = readDxf(buildPlanDxf(plan, world)).entities.filter((e) => e.type === "LWPOLYLINE");
+591 -26
View File
@@ -14,13 +14,29 @@
// DWG = R2018 — Begründung im Kopf von export.rs. Der frühere TS-Text-Writer
// (`dxfWriter.ts`) ist gelöscht. Das Format-Modul wird nachgeladen: vor `buildPlanDxf`/
// `buildPlanDwg` einmal `await loadFileio()` (savePlanDxf und die CLI tun das).
//
// Fachplaner-Export (28.10., [C2]): damit in AutoCAD/BricsCAD weitergearbeitet werden kann, entstehen
// statt loser Linien dort, wo das Modell die Information trägt, CAD-Objekte:
// - Bemassungen (`Drawing2D {shape:"dimension"}`) → je Segment eine DIMENSION samt Anonymblock `*D…` und
// Bemassungsstil (DIMSTYLE: Texthöhe/Strich/Abstände in Papier-mm, DIMSCALE = Massstab);
// - Türen/Fenster (Primitive mit `openingId`) → BLOCK + INSERT in der Wandrichtung, gleiche Geometrie
// teilt sich einen Block, ATTRIBs (Breite, Höhe, Typ, ID);
// - Blockinstanzen (`Drawing2D {shape:"block"}`, Möbel/Symbole/Nordpfeil) → BLOCK je Definition + INSERT;
// - Strichmuster → Linientypen (Name des Projekt-Linienstils), Texte → Textstile mit Schriftname und
// Ausrichtung (Raumstempel mit Fläche als TEXT, links/Mitte/rechts), optional Papierbereich.
// Alles andere (Wände, Umrisse, Schraffuren) bleibt wie bisher Linie/Polylinie/HATCH.
import type { Plan, Primitive } from "../plan/generatePlan";
import type { LayerCategory, Project, Vec2 } from "../model/types";
import type { Drawing2D, LayerCategory, Opening, Project, Vec2 } from "../model/types";
import type { Marks } from "../text/richText";
import { flattenCategories } from "../model/types";
import { DEFAULT_SCALE_DENOMINATOR, DIM_DEFAULTS_MM, dimTextFrame, dimTextPos, mmToModel } from "../model/dimension";
import { buildRandomHatchRuns, zigzagPoints, motifPoints } from "../plan/glPlan/glPlanHatch";
import { plainText } from "../text/richText";
import { docToLines } from "../text/renderHtml";
import { fileio, loadFileio } from "../engine/fileioWasm";
import { dashToLtypeMeters, fontNameOf, ltypeNameFor, paperFor, primitiveToLocal, roundKey } from "./dxfCadParts";
import type { LocalFrame } from "./dxfCadParts";
export interface ExportDxfOptions {
/** Titel/Geschossname (nur als Kommentar-freundlicher Dateiname genutzt). */
@@ -29,6 +45,16 @@ export interface ExportDxfOptions {
includeHatches?: boolean;
/** Dateiname des Downloads (mit/ohne Endung). */
fileName?: string;
/**
* Massstabsnenner (100 = 1:100): macht aus Papier-Millimetern Modell-Meter — Texthöhe/Striche der
* Bemassung, Strichmuster der Linientypen, Schriftgrösse der Raumstempel, Massstab des Ansichtsfensters.
* Default 1:100 (wie `generatePlan`).
*/
scaleDenominator?: number;
/** Einheit der Masszahl: Meter (Default, wie im Plan „3.25") oder Zentimeter („325"). */
dimUnit?: "m" | "cm";
/** Zusätzlich ein Layout (Papierbereich) mit Ansichtsfenster im Planmassstab anlegen. */
paperLayout?: boolean;
}
/** Ausgabeformat des Modell-Space-Exports. */
@@ -44,10 +70,14 @@ const LAYER_HATCH = "HATCH";
const LAYER_SYMBOLS = "SYMBOLS";
const LAYER_CONTEXT = "CONTEXT";
const LAYER_DEFAULT = "PLAN";
/** Schnittführungs-Symbole (Primitive mit `cls === "section-line"`). */
const LAYER_SECTIONS = "SECTIONS";
/** Sammel-Layer für Extrusions-Footprints (truck-Integration) — die Quell-
* Drawing2D wird beim Extrudieren entfernt, es gibt also keine categoryCode
* mehr nachzuschlagen; eigener Layer statt Absturz in LAYER_DEFAULT. */
const LAYER_EXTRUSION = "EXTRUSION";
/** Ebene „0": Inhalt von Blöcken (erbt die Ebene des INSERT). */
const LAYER_ZERO = "0";
// ── Flache Zeichnung (Gegenstück zu src-tauri/fileio/src/export.rs) ─────────
@@ -60,60 +90,180 @@ const REC_CIRCLE = 5;
const REC_TEXT = 6;
const REC_HATCH = 7;
const REC_GRADIENT = 8;
const REC_LTYPE = 9;
const REC_LAYER_LTYPE = 10;
const REC_PEN = 11;
const REC_STYLE = 12;
const REC_TEXT2 = 13;
const REC_DIMSTYLE = 14;
const REC_DIM = 15;
const REC_BLOCK = 16;
const REC_BLOCK_END = 17;
const REC_INSERT = 18;
const REC_LAYOUT = 19;
/** Zustand, den eine Zeichnung und die Blockinhalte, die in sie hineingespleisst werden, teilen. */
interface FlatShared {
/** Der Zahlenpuffer der Hauptzeichnung: Definitionen (Ebenen, Linientypen, Stile) landen immer hier, in Reihenfolge ihrer Indizes. */
root: number[];
strings: string[];
strIdx: Map<string, number>;
layers: Map<string, number>;
ltypes: Map<string, number>;
styles: Map<string, number>;
dimStyles: Map<string, number>;
blocks: Set<string>;
/** Entitäten in Blockdefinitionen (Zählung für Tests). */
blockCounts: Record<string, number>;
}
/** Eine Textzeile der Raumstempel/Textfelder für `addText2`. */
export interface TextAlignOpts {
/** 0 links, 1 Mitte, 2 rechts (Anker = Einfügepunkt). */
halign?: 0 | 1 | 2;
/** Textstil-Index aus {@link FlatDrawing.addTextStyle}; −1 = Standard. */
style?: number;
}
/**
* Sammelt Ebenen und Entitäten als flachen Zahlenpuffer + Zeichenkettenliste. Ebenen sind
* idempotent über den Namen; eine unbekannte Ebene wird mit Standardwerten (ACI 7, 0.25 mm)
* angelegt — wie beim früheren Writer. Namen bereinigt Rust (`sanitize_layer_name`).
*
* `new FlatDrawing(parent)` ist ein Blockinhalt: er teilt Ebenen, Linientypen, Stile und Zeichenketten
* (dedupliziert, gleiche Eingabe ⇒ gleiche Indizes) mit der Hauptzeichnung, hat aber einen eigenen
* Entitätspuffer, der mit {@link defineBlock} an die Stelle der Blockdefinition kommt.
*/
export class FlatDrawing {
private nums: number[] = [FLAT_VERSION];
private strings: string[] = [];
private layers = new Map<string, number>();
private sh: FlatShared;
private nums: number[];
/** Aktueller Linientyp (PEN) dieses Puffers; −1 = nach Ebene. */
private pen = -1;
/** Entitäten dieses Puffers je Typ (Tests). */
private counts: Record<string, number> = {};
constructor(parent?: FlatDrawing) {
if (parent) {
this.sh = parent.sh;
this.nums = [];
} else {
this.nums = [FLAT_VERSION];
this.sh = {
root: this.nums,
strings: [],
strIdx: new Map(),
layers: new Map(),
ltypes: new Map(),
styles: new Map(),
dimStyles: new Map(),
blocks: new Set(),
blockCounts: {},
};
}
}
private str(s: string): number {
this.strings.push(s.replace(/\0/g, ""));
return this.strings.length - 1;
const clean = s.replace(/\0/g, "");
const known = this.sh.strIdx.get(clean);
if (known !== undefined) return known;
this.sh.strings.push(clean);
this.sh.strIdx.set(clean, this.sh.strings.length - 1);
return this.sh.strings.length - 1;
}
private bump(kind: string): void {
this.counts[kind] = (this.counts[kind] ?? 0) + 1;
}
/** Anzahl Entitäten im Modellbereich je Typ (INSERT/DIMENSION zählen je als eine) und in Blöcken (Summe je Typ). */
stats(): { model: Record<string, number>; blocks: Record<string, number> } {
return { model: { ...this.counts }, blocks: { ...this.sh.blockCounts } };
}
/** Legt eine Ebene an (`rgb` 0xRRGGBB oder null = ACI 7, `lineWeight` in 1/100 mm). */
addLayer(name: string, rgb: number | null, lineWeight: number): number {
const known = this.layers.get(name);
const known = this.sh.layers.get(name);
if (known !== undefined) return known;
const idx = this.layers.size;
this.layers.set(name, idx);
this.nums.push(REC_LAYER, this.str(name), rgb ?? -1, lineWeight);
const idx = this.sh.layers.size;
this.sh.layers.set(name, idx);
this.sh.root.push(REC_LAYER, this.str(name), rgb ?? -1, lineWeight);
return idx;
}
private layer(name: string): number {
return this.layers.get(name) ?? this.addLayer(name, null, 25);
return this.sh.layers.get(name) ?? this.addLayer(name, null, 25);
}
/**
* Linientyp (Elemente in Metern: Strich +, Lücke −, Punkt 0; mindestens zwei Elemente), idempotent
* über den Namen. Gibt den Index für {@link setPen}/{@link setLayerLinetype} zurück.
*/
addLinetype(name: string, elements: number[]): number {
const known = this.sh.ltypes.get(name);
if (known !== undefined) return known;
const idx = this.sh.ltypes.size;
this.sh.ltypes.set(name, idx);
this.sh.root.push(REC_LTYPE, this.str(name), elements.length, ...elements);
return idx;
}
/** Standard-Linientyp einer bereits angelegten Ebene. */
setLayerLinetype(layerName: string, ltype: number): void {
this.sh.root.push(REC_LAYER_LTYPE, this.layer(layerName), ltype);
}
/** Linientyp für die folgenden Linien/Bögen/Kreise/Polylinien (−1 = nach Ebene). Schreibt nur bei Änderung. */
setPen(ltype: number): void {
if (ltype === this.pen) return;
this.pen = ltype;
this.nums.push(REC_PEN, ltype);
}
/** Textstil mit TrueType-Schriftname (CAD löst ihn über das Betriebssystem auf), idempotent über den Namen. */
addTextStyle(name: string, font: string, bold = false, italic = false): number {
const known = this.sh.styles.get(name);
if (known !== undefined) return known;
const idx = this.sh.styles.size;
this.sh.styles.set(name, idx);
this.sh.root.push(REC_STYLE, this.str(name), this.str(font), bold ? 1 : 0, italic ? 1 : 0, 1);
return idx;
}
addLine(layer: string, a: Vec2, b: Vec2): void {
this.bump("LINE");
this.nums.push(REC_LINE, this.layer(layer), a.x, a.y, b.x, b.y);
}
addPolyline(layer: string, pts: Vec2[], closed: boolean): void {
if (pts.length < 2) return;
this.bump("LWPOLYLINE");
this.nums.push(REC_POLYLINE, this.layer(layer), closed ? 1 : 0, pts.length);
for (const p of pts) this.nums.push(p.x, p.y);
}
/** Bogen gegen den Uhrzeigersinn von `start` nach `end` (Radiant). */
addArc(layer: string, center: Vec2, r: number, start: number, end: number): void {
this.bump("ARC");
this.nums.push(REC_ARC, this.layer(layer), center.x, center.y, r, start, end);
}
addCircle(layer: string, center: Vec2, r: number): void {
this.bump("CIRCLE");
this.nums.push(REC_CIRCLE, this.layer(layer), center.x, center.y, r);
}
/** Einzeiliger Text (Höhe in Metern, Drehung in Radiant). */
addText(layer: string, at: Vec2, height: number, rotation: number, value: string): void {
this.bump("TEXT");
this.nums.push(REC_TEXT, this.layer(layer), this.str(value), at.x, at.y, height, rotation);
}
/** Einzeiliger Text mit Ausrichtung (Anker = Einfügepunkt, Grundlinie) und Textstil. */
addText2(layer: string, at: Vec2, height: number, rotation: number, value: string, o: TextAlignOpts = {}): void {
this.bump("TEXT");
this.nums.push(REC_TEXT2, this.layer(layer), this.str(value), at.x, at.y, height, rotation, o.halign ?? 0, o.style ?? -1);
}
/**
* Schraffur als echte HATCH-Entität (äusserer Rand `pts`, geschlossen). `solid` = Vollfüllung;
* sonst Linienmuster aus `families` (Winkel in Radiant, Linienabstand in Metern; je Schar eine
@@ -126,6 +276,7 @@ export class FlatDrawing {
opts: { solid: boolean; rgb: number | null; families?: { angle: number; spacing: number }[]; dashes?: number[] },
): void {
if (pts.length < 3) return;
this.bump("HATCH");
const families = opts.solid ? [] : (opts.families ?? []);
const dashes = opts.solid ? [] : (opts.dashes ?? []);
this.nums.push(REC_HATCH, this.layer(layer), opts.solid ? 0 : 1, opts.rgb ?? -1, dashes.length, ...dashes, families.length);
@@ -141,16 +292,117 @@ export class FlatDrawing {
*/
addGradient(layer: string, pts: Vec2[], g: { rgb1: number; rgb2: number; angle: number; radial: boolean }): void {
if (pts.length < 3) return;
this.bump("HATCH");
this.nums.push(REC_GRADIENT, this.layer(layer), g.rgb1, g.rgb2, g.angle, g.radial ? 1 : 0, pts.length);
for (const p of pts) this.nums.push(p.x, p.y);
}
/**
* Bemassungsstil (Papier-Meter, s. `export_dim.rs`), idempotent über `name`. `textStyle` = Index aus
* {@link addTextStyle} oder −1; `post` = Format mit `<>` als Platzhalter der Zahl (oder leer).
*/
addDimStyle(
name: string,
d: { textStyle: number; scale: number; txt: number; tick: number; exo: number; exe: number; gap: number; dec: number; lfac: number; post?: string },
): number {
const known = this.sh.dimStyles.get(name);
if (known !== undefined) return known;
const idx = this.sh.dimStyles.size;
this.sh.dimStyles.set(name, idx);
this.sh.root.push(
REC_DIMSTYLE, this.str(name), d.textStyle, d.scale, d.txt, d.tick, d.exo, d.exe, d.gap, d.dec, d.lfac,
d.post ? this.str(d.post) : -1,
);
return idx;
}
/**
* Ausgerichtete Bemassung (DIMENSION + Anonymblock `*D…`) zwischen `p1` und `p2`; `onLine` = ein Punkt
* auf der Masslinie (legt Seite und Abstand fest), `textAt` = freie Lage der Masszahl (Mitte).
*/
addDimension(layer: string, dimStyle: number, p1: Vec2, p2: Vec2, onLine: Vec2, textAt?: Vec2): void {
this.bump("DIMENSION");
this.nums.push(REC_DIM, this.layer(layer), dimStyle, p1.x, p1.y, p2.x, p2.y, onLine.x, onLine.y, textAt ? 1 : 0, textAt?.x ?? 0, textAt?.y ?? 0);
}
/** Ob ein Block dieses Namens schon definiert ist. */
hasBlock(name: string): boolean {
return this.sh.blocks.has(name);
}
/**
* Blockdefinition: der Inhalt `content` (ein `new FlatDrawing(this)`) kommt mit blocklokalen Koordinaten
* an diese Stelle. `atts` = Attributdefinitionen (unsichtbar; Wert je INSERT).
*/
defineBlock(name: string, description: string, atts: { tag: string; prompt: string; def: string }[], content: FlatDrawing): void {
if (this.sh.blocks.has(name)) return;
this.sh.blocks.add(name);
this.nums.push(REC_BLOCK, this.str(name), description ? this.str(description) : -1, atts.length);
for (const a of atts) this.nums.push(this.str(a.tag), this.str(a.prompt), this.str(a.def), 0, 0, 0.1);
// Der Block beginnt mit „nach Ebene“; danach gilt der Linientyp, mit dem sein Inhalt endete.
this.nums.push(REC_PEN, -1);
for (const v of content.nums) this.nums.push(v);
this.nums.push(REC_BLOCK_END);
this.pen = content.pen;
for (const [k, n] of Object.entries(content.counts)) this.sh.blockCounts[k] = (this.sh.blockCounts[k] ?? 0) + n;
}
/** Inhalt eines Blocks als Schlüssel: gleiche Zahlen (auf 1 mm gerundet) ⇒ gleicher Block. */
contentKey(): string {
return roundKey(this.nums);
}
/** Blockeinfügung mit Attributwerten (`tag` → Wert). */
addInsert(layer: string, name: string, at: Vec2, rotation: number, scale: number, values: { tag: string; value: string }[] = []): void {
this.bump("INSERT");
this.nums.push(REC_INSERT, this.layer(layer), this.str(name), at.x, at.y, rotation, scale, scale, values.length);
for (const v of values) this.nums.push(this.str(v.tag), this.str(v.value));
}
/**
* Papierbereich: Layout `name` (Papier in mm) mit einem Ansichtsfenster auf den Modellbereich.
* `vp` = Mittelpunkt und Grösse des Fensters auf dem Papier (mm), `view` = Mittelpunkt des Ausschnitts im Modell.
*/
addLayout(name: string, paperW: number, paperH: number, vp: { cx: number; cy: number; w: number; h: number }, view: Vec2, scaleDenominator: number): void {
this.nums.push(REC_LAYOUT, this.str(name), paperW, paperH, vp.cx, vp.cy, vp.w, vp.h, view.x, view.y, scaleDenominator);
}
/** Argumente für die Rust-Bindungen. */
args(): [Float64Array, string] {
return [Float64Array.from(this.nums), this.strings.join("\0")];
return [Float64Array.from(this.nums), this.sh.strings.join("\0")];
}
}
// ── Plan → flache Zeichnung ─────────────────────────────────────────────────
/** Gemeinsamer Zustand beim Sammeln eines Plans. */
interface Ctx {
project: Project;
scale: number;
includeHatches: boolean;
dimUnit: "m" | "cm";
/** Ebenenname je Kategorie-Code. */
layerNameByCode: Map<string, string>;
/** Kategorie-Code je Zeichen-Element / Raum (für Ebenen). */
codeByDrawing: Map<string, string>;
codeByRoom: Map<string, string>;
/** Linientyp-Index zu einem Strichmuster (−1 = durchgezogen). */
ltypeOf: (dxf: FlatDrawing, dash: number[] | null | undefined) => number;
/** Textstil-Index zu einer Formatierung. */
styleOf: (dxf: FlatDrawing, marks?: Marks) => number;
}
/** Eine Zeile einer (Rich-)Text-Ausgabe. */
interface OutLine {
text: string;
/** Schrifthöhe (Meter). */
height: number;
align: 0 | 1 | 2;
marks?: Marks;
/** Versatz der Grundlinie vom Anker nach unten (Meter, ≥ 0 für spätere Zeilen). */
down: number;
}
/**
* Baut aus einem Plan + Projekt die flache Zeichnung (Meter-Modell-Space).
* Reihenfolge der Primitive bleibt erhalten.
@@ -161,6 +413,7 @@ export function collectPlanDrawing(
opts: ExportDxfOptions = {},
): FlatDrawing {
const includeHatches = opts.includeHatches ?? true;
const scale = opts.scaleDenominator && Number.isFinite(opts.scaleDenominator) && opts.scaleDenominator > 0 ? opts.scaleDenominator : DEFAULT_SCALE_DENOMINATOR;
const dxf = new FlatDrawing();
// 1) Layer aus den Kategorie-Ebenen anlegen (Code+Name als Layer-Name, Farbe,
@@ -177,8 +430,10 @@ export function collectPlanDrawing(
dxf.addLayer(LAYER_HATCH, 0x888888, 13);
dxf.addLayer(LAYER_CONTEXT, 0x9aa3ad, 10);
dxf.addLayer(LAYER_DEFAULT, 0x111111, 18);
dxf.addLayer(LAYER_SECTIONS, 0x111111, 18);
// Warmes Orange, identisch zum 3D-/Grundriss-Footprint der Extrusionen (EXTRUSION_STROKE/EXTRUSION_RGB).
dxf.addLayer(LAYER_EXTRUSION, rgbFromHex("#d98c40"), 13);
dxf.addLayer(LAYER_ZERO, null, 25); // Blockinhalt; „0" gibt es in jeder Datei, der Eintrag legt nur den Index fest
// 2) Rückverweise Primitiv → Kategorie: Wände/2D-Elemente tragen nur ihre ID im
// Plan; die Kategorie liegt am Projekt-Objekt. Damit landet jede Wand-/Drawing-
@@ -189,6 +444,8 @@ export function collectPlanDrawing(
for (const d of project.drawings2d) codeByDrawing.set(d.id, d.categoryCode);
const codeByColumn = new Map<string, string>();
for (const c of project.columns ?? []) codeByColumn.set(c.id, c.categoryCode);
const codeByRoom = new Map<string, string>();
for (const r of project.rooms ?? []) codeByRoom.set(r.id, r.categoryCode);
const drawingLayer = (id: string | undefined, fallback: string): string =>
id ? (layerNameByCode.get(codeByDrawing.get(id) ?? "") ?? LAYER_DEFAULT) : fallback;
@@ -202,22 +459,250 @@ export function collectPlanDrawing(
}
if (p.kind === "line") {
if (p.cls === "context-line") return LAYER_CONTEXT;
if (p.cls === "section-line") return LAYER_SECTIONS;
// Tür-Blatt/-Rahmen und Wand-Achsen: Symbol-Sammellayer.
return drawingLayer(p.drawingId, LAYER_SYMBOLS);
}
// Texte von 2D-Elementen: Ebene ihrer Kategorie.
if (p.kind === "drawingText") return drawingLayer(p.drawingId, LAYER_SYMBOLS);
if (p.kind === "text") return p.roomId ? (layerNameByCode.get(codeByRoom.get(p.roomId) ?? "") ?? LAYER_SYMBOLS) : LAYER_SYMBOLS;
// Bögen: Tür-Schwenkbogen → Symbole.
return LAYER_SYMBOLS;
};
// 3) Jedes Primitiv in Entities übersetzen.
for (const p of plan.primitives) {
emitPrimitive(dxf, p, layerFor(p), includeHatches);
// Standard-Schrift: erste im Projekt hinterlegte Schrift der Textstile, sonst Arial.
const defaultFont = (project.textStyles ?? []).map((s) => fontNameOf(s.marks.font)).find((f) => f) ?? "Arial";
const ctx: Ctx = {
project,
scale,
includeHatches,
dimUnit: opts.dimUnit ?? "m",
layerNameByCode,
codeByDrawing,
codeByRoom,
ltypeOf: (d, dash) => {
if (!dash || dash.length === 0) return -1;
const el = dashToLtypeMeters(dash, scale);
return el ? d.addLinetype(ltypeNameFor(dash, project.lineStyles), el) : -1;
},
styleOf: (d, marks) => {
const family = fontNameOf(marks?.font) ?? defaultFont;
const bold = !!marks?.bold;
const italic = !!marks?.italic;
const plain = family === defaultFont && !bold && !italic;
const name = plain ? "DOSSIER" : `DOSSIER_${family}${bold ? "_B" : ""}${italic ? "_I" : ""}`;
return d.addTextStyle(name, family, bold, italic);
},
};
// 3) Gruppen: Bemassungen, Blockinstanzen und Öffnungen werden zu CAD-Objekten statt zu losen Primitiven.
const dimById = new Map<string, Drawing2D>();
const blockById = new Map<string, Drawing2D>();
for (const d of project.drawings2d) {
if (d.geom?.shape === "dimension") dimById.set(d.id, d);
else if (d.geom?.shape === "block") blockById.set(d.id, d);
}
const openingById = new Map<string, Opening>();
for (const o of project.openings ?? []) openingById.set(o.id, o);
const groupKeyOf = (p: Primitive): string | null => {
const did = "drawingId" in p ? p.drawingId : undefined;
if (did && dimById.has(did)) return `d:${did}`;
if (did && blockById.has(did)) return `b:${did}`;
const oid = "openingId" in p ? p.openingId : undefined;
if (oid && openingById.has(oid)) return `o:${oid}`;
return null;
};
const groups = new Map<string, Primitive[]>();
for (const p of plan.primitives) {
const k = groupKeyOf(p);
if (!k) continue;
const g = groups.get(k);
if (g) g.push(p);
else groups.set(k, [p]);
}
const blockNames = new BlockNames();
const doneGroups = new Set<string>();
// 4) Jedes Primitiv in Entities übersetzen.
for (const p of plan.primitives) {
const key = groupKeyOf(p);
if (key) {
if (doneGroups.has(key)) continue;
doneGroups.add(key);
const prims = groups.get(key) ?? [];
if (key.startsWith("d:")) emitDimensions(dxf, ctx, dimById.get(key.slice(2))!, drawingLayer(key.slice(2), LAYER_DEFAULT));
else if (key.startsWith("b:")) {
const d = blockById.get(key.slice(2))!;
if (!emitBlockInstance(dxf, ctx, d, prims, drawingLayer(d.id, LAYER_DEFAULT), blockNames)) for (const q of prims) emitPrimitive(dxf, ctx, q, layerFor(q), LAYER_HATCH);
} else {
const o = openingById.get(key.slice(2))!;
if (!emitOpening(dxf, ctx, o, prims, layerNameByCode.get(o.categoryCode) ?? LAYER_SYMBOLS, blockNames)) for (const q of prims) emitPrimitive(dxf, ctx, q, layerFor(q), LAYER_HATCH);
}
continue;
}
emitPrimitive(dxf, ctx, p, layerFor(p), LAYER_HATCH);
}
dxf.setPen(-1);
// 5) Papierbereich (optional): ein Layout mit Ansichtsfenster im Planmassstab auf die Plan-Ausdehnung.
if (opts.paperLayout) addPaperLayout(dxf, plan, scale);
return dxf;
}
/** Eindeutige Blocknamen: gleiche Schlüssel teilen sich einen Namen, verschiedene Inhalte mit gleichem Wunschnamen werden nummeriert. */
class BlockNames {
private byKey = new Map<string, string>();
private used = new Set<string>();
/** Name zum Schlüssel; `fresh` = der Block muss noch definiert werden. */
name(key: string, wish: string): { name: string; fresh: boolean } {
const known = this.byKey.get(key);
if (known) return { name: known, fresh: false };
let name = wish;
for (let i = 2; this.used.has(name.toLowerCase()); i++) name = `${wish}_${i}`;
this.used.add(name.toLowerCase());
this.byKey.set(key, name);
return { name, fresh: true };
}
}
/** Papierbereich auf die Ausdehnung des Plans (Meter) im Massstab `scale`. */
function addPaperLayout(dxf: FlatDrawing, plan: Plan, scale: number): void {
const b = plan.bounds;
const w = b.maxX - b.minX;
const h = b.maxY - b.minY;
if (![b.minX, b.minY, b.maxX, b.maxY].every(Number.isFinite) || w <= 0 || h <= 0) return;
const margin = 10;
const paper = paperFor(w, h, scale, margin);
dxf.addLayout(
`Plan 1-${scale}`,
paper.paperW,
paper.paperH,
{ cx: paper.paperW / 2, cy: paper.paperH / 2, w: paper.vpW, h: paper.vpH },
{ x: (b.minX + b.maxX) / 2, y: (b.minY + b.maxY) / 2 },
scale,
);
}
/** Format einer Länge für Attribute: Meter, 2 Nachkommastellen. */
function m2(v: number): string {
return Number.isFinite(v) ? v.toFixed(2) : "";
}
/** Bemassungskette → je Segment eine DIMENSION; Stil aus den Papier-mm-Feinheiten und dem Massstab. */
function emitDimensions(dxf: FlatDrawing, ctx: Ctx, d: Drawing2D, layer: string): void {
const g = d.geom;
if (g.shape !== "dimension") return;
const th = g.textHeightMm ?? DIM_DEFAULTS_MM.textHeight;
const tick = g.tickLenMm ?? DIM_DEFAULTS_MM.tickLen;
const gap = g.gapMm ?? DIM_DEFAULTS_MM.gap;
const over = g.overshootMm ?? DIM_DEFAULTS_MM.overshoot;
if (![th, tick, gap, over].every((v) => Number.isFinite(v) && v >= 0) || th <= 0) return;
const cm = ctx.dimUnit === "cm";
const isDefault = th === DIM_DEFAULTS_MM.textHeight && tick === DIM_DEFAULTS_MM.tickLen && gap === DIM_DEFAULTS_MM.gap && over === DIM_DEFAULTS_MM.overshoot;
const variant = isDefault ? "" : `_${th}-${tick}-${gap}-${over}`.replace(/\./g, ",");
const name = `DOSSIER_1-${ctx.scale}${cm ? "_cm" : ""}${variant}`;
const style = dxf.addDimStyle(name, {
textStyle: ctx.styleOf(dxf),
scale: ctx.scale,
txt: th / 1000,
tick: tick / 1000,
exo: gap / 1000,
exe: over / 1000,
gap: (th * 0.6) / 1000, // Unterkante der Zahl 0.6 × Texthöhe über der Masslinie, wie im Plan
dec: cm ? 0 : 2,
lfac: cm ? 100 : 1,
});
const mm = (v: number) => mmToModel(v, ctx.scale);
const textH = mm(th);
for (let i = 0; i + 1 < g.pts.length; i++) {
const a = g.pts[i];
const b = g.pts[i + 1];
const len = Math.hypot(b.x - a.x, b.y - a.y);
if (len < 1e-6) continue;
const nx = -(b.y - a.y) / len;
const ny = (b.x - a.x) / len;
const onLine = { x: a.x + nx * g.offset, y: a.y + ny * g.offset };
// Von Hand verschobene Masszahl: Mitte = Grundlinienpunkt des Plans + halbe Texthöhe quer zur Linie.
const o = g.textOffsetsMm?.[i];
let textAt: Vec2 | undefined;
if (o && (o.along !== 0 || o.perp !== 0)) {
const base = dimTextPos(a, b, g.offset, textH, { along: mm(o.along), perp: mm(o.perp) });
const up = dimTextFrame(a, b, g.offset, textH).up;
textAt = { x: base.x + up.x * (textH / 2), y: base.y + up.y * (textH / 2) };
}
dxf.addDimension(layer, style, a, b, onLine, textAt);
}
}
/** Blockinstanz (`Drawing2D {shape:"block"}`) → BLOCK je Definition (lokale Geometrie) + INSERT. */
function emitBlockInstance(dxf: FlatDrawing, ctx: Ctx, d: Drawing2D, prims: Primitive[], layer: string, names: BlockNames): boolean {
const g = d.geom;
if (g.shape !== "block") return false;
const def = ctx.project.blockDefs?.find((b) => b.id === g.blockDefId);
const s = g.scale ?? 1;
if (!def || !(s > 0) || !Number.isFinite(s) || !Number.isFinite(g.rotation) || !Number.isFinite(g.at.x) || !Number.isFinite(g.at.y)) return false;
const { name, fresh } = names.name(`blockdef:${def.id}`, def.name.trim() || "Block");
if (fresh) {
const frame: LocalFrame = { origin: g.at, rot: g.rotation, scale: s };
const content = new FlatDrawing(dxf);
for (const p of prims) {
const lp = primitiveToLocal(p, frame);
if (lp) emitPrimitive(content, ctx, lp, LAYER_ZERO, LAYER_ZERO);
}
content.setPen(-1);
dxf.defineBlock(name, def.name, [], content);
}
dxf.addInsert(layer, name, g.at, g.rotation, s);
return true;
}
/** Tür/Fenster → BLOCK (Geometrie in der Wandrichtung, am ersten Pfosten verankert) + INSERT mit Attributen. */
function emitOpening(dxf: FlatDrawing, ctx: Ctx, o: Opening, prims: Primitive[], layer: string, names: BlockNames): boolean {
const wall = ctx.project.walls.find((w) => w.id === o.hostWallId);
if (!wall) return false;
const len = Math.hypot(wall.end.x - wall.start.x, wall.end.y - wall.start.y);
if (len < 1e-6 || !Number.isFinite(o.position)) return false;
const ux = (wall.end.x - wall.start.x) / len;
const uy = (wall.end.y - wall.start.y) / len;
const origin = { x: wall.start.x + ux * o.position, y: wall.start.y + uy * o.position };
const rot = Math.atan2(uy, ux);
const frame: LocalFrame = { origin, rot, scale: 1 };
const content = new FlatDrawing(dxf);
for (const p of prims) {
const lp = primitiveToLocal(p, frame);
if (lp) emitPrimitive(content, ctx, lp, LAYER_ZERO, LAYER_ZERO);
}
content.setPen(-1);
const isDoor = o.kind === "door";
const kindName = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandoeffnung" : "Tuer";
const cm = (v: number) => String(Math.round(v * 100));
const wish = `${kindName}_${cm(o.width)}x${cm(o.height)}`;
const { name, fresh } = names.name(`${kindName}:${content.contentKey()}`, wish);
const atts = [
{ tag: "ID", prompt: "Kennung", def: "" },
{ tag: "TYP", prompt: "Art", def: kindName },
{ tag: "TYPENAME", prompt: "Typ", def: "" },
{ tag: "BREITE_M", prompt: "Breite [m]", def: "" },
{ tag: "HOEHE_M", prompt: "Hoehe [m]", def: "" },
...(isDoor ? [] : [{ tag: "BRUESTUNG_M", prompt: "Bruestung [m]", def: "" }]),
];
if (fresh) {
const label = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandöffnung" : "Tür";
dxf.defineBlock(name, `${label} ${m2(o.width)} × ${m2(o.height)} m`, atts, content);
}
const typeName = (isDoor ? ctx.project.doorTypes : ctx.project.windowTypes)?.find((t) => t.id === o.typeId)?.name ?? "";
const label = !isDoor ? "Fenster" : o.doorType === "wandoeffnung" ? "Wandöffnung" : "Tür";
dxf.addInsert(layer, name, origin, rot, 1, [
{ tag: "ID", value: o.id },
{ tag: "TYP", value: label },
{ tag: "TYPENAME", value: typeName },
{ tag: "BREITE_M", value: m2(o.width) },
{ tag: "HOEHE_M", value: m2(o.height) },
...(isDoor ? [] : [{ tag: "BRUESTUNG_M", value: m2(o.sillHeight) }]),
]);
return true;
}
/**
* Baut aus einem Plan + Projekt einen vollständigen DXF-String (R2018 ASCII, Meter-Modell-Space).
* Verlangt das geladene Format-Modul (`await loadFileio()`).
@@ -270,13 +755,70 @@ function layerName(c: LayerCategory): string {
return `${c.code}_${c.name}`;
}
/** Schreibt ein Plan-Primitiv als passende Entity(en). */
/** Stempel-/Textzeilen eines Primitivs `text` (Raumstempel): Rich-Text-Doc + Live-Zeilen, vertikal um den Anker zentriert wie in der Plan-Ansicht. */
function stampLines(p: Extract<Primitive, { kind: "text" }>, scale: number): OutLine[] {
const unitPerPt = (0.0254 / 72) * scale; // 1 pt Papier in Modell-Metern
const baseFs = p.basePt * unitPerPt;
const lineGap = baseFs * 1.3;
const docLines = docToLines(p.doc, { x: 0, y: 0, lineHeight: lineGap, unitPerPt, basePt: p.basePt, color: p.color });
const lines = [
...docLines.map((l) => ({ align: l.align, lineHeight: l.lineHeight, ts: l.tspans })),
...p.extraLines.map((l) => ({ align: l.align, lineHeight: lineGap, ts: [{ text: l.text, fontSize: baseFs * 0.8, fontFamily: undefined as string | undefined, fontWeight: undefined as string | undefined, fontStyle: undefined as string | undefined }] })),
];
if (lines.length === 0) return [];
const totalH = baseFs + lines.slice(1).reduce((s, l) => s + l.lineHeight, 0);
let down = -totalH / 2 + baseFs * 0.8;
const out: OutLine[] = [];
lines.forEach((l, k) => {
if (k > 0) down += l.lineHeight;
const text = l.ts.map((t) => t.text).join("");
const first = l.ts[0];
if (!text.trim() || !first) return;
out.push({
text,
height: Math.max(...l.ts.map((t) => t.fontSize)),
align: l.align === "center" ? 1 : l.align === "right" ? 2 : 0,
marks: { font: first.fontFamily, bold: first.fontWeight === "700", italic: first.fontStyle === "italic" },
down,
});
});
return out;
}
/** Zeilen eines `drawingText`: Absätze bzw. Zeilenumbrüche, bei Spaltenbreite wortweise umbrochen; Zeilenabstand wie die Plan-Ansicht (1.25 × Höhe). */
function drawingTextLines(p: Extract<Primitive, { kind: "drawingText" }>): OutLine[] {
const paragraphs = p.doc ? plainText(p.doc).split("\n") : p.text.split(/\r?\n/);
const lines: string[] = [];
if (p.wrapWidth && p.wrapWidth > 0) {
const maxChars = Math.max(1, Math.floor(p.wrapWidth / (p.heightM * 0.55)));
for (const para of paragraphs) {
let line = "";
for (const word of para.split(/\s+/)) {
if (line === "") line = word;
else if (line.length + 1 + word.length <= maxChars) line += ` ${word}`;
else {
lines.push(line);
line = word;
}
}
lines.push(line);
}
} else {
lines.push(...paragraphs);
}
const marks = p.marks ?? p.doc?.paragraphs[0]?.runs[0]?.marks;
return lines.map((text, k) => ({ text, height: p.heightM, align: 0 as const, marks, down: k * p.heightM * 1.25 }));
}
/** Schreibt ein Plan-Primitiv als passende Entity(en). `hatchLayer` = Ebene der Schraffuren (in Blöcken „0"). */
function emitPrimitive(
dxf: FlatDrawing,
ctx: Ctx,
p: Primitive,
layer: string,
includeHatches: boolean,
hatchLayer: string,
): void {
const includeHatches = ctx.includeHatches;
switch (p.kind) {
case "line":
if (p.zigzag) {
@@ -284,40 +826,61 @@ function emitPrimitive(
// Modell-Meter über dieselbe Kopplung wie das Strichmuster unten).
const amp = p.zigzag.amplitude * DASH_MM_TO_M;
const wav = p.zigzag.wavelength * DASH_MM_TO_M;
dxf.setPen(-1);
dxf.addPolyline(layer, zigzagPoints(p.a, p.b, amp, wav), false);
} else if (p.motif) {
// Custom-Motiv → offene Polylinie (Papier-mm → Modell-Meter, wie unten).
dxf.setPen(-1);
dxf.addPolyline(layer, motifPoints(p.a, p.b, p.motif, DASH_MM_TO_M), false);
} else {
dxf.setPen(ctx.ltypeOf(dxf, p.dash));
dxf.addLine(layer, p.a, p.b);
}
break;
case "arc":
dxf.setPen(ctx.ltypeOf(dxf, p.dash));
emitArc(dxf, p, layer);
break;
// Gezeichnete Kreise/Bögen (2D-Elemente). `drawingArc` läuft per Konvention
// immer CCW von a0 nach a1 (s. planView/primitives), genau wie DXF-Bögen.
case "drawingCircle":
dxf.setPen(ctx.ltypeOf(dxf, p.dash));
dxf.addCircle(layer, p.center, p.r);
break;
case "drawingArc":
dxf.setPen(ctx.ltypeOf(dxf, p.dash));
dxf.addArc(layer, p.center, p.r, p.a0, p.a1);
break;
// 2D-Text (neu mit [C2]; der alte Writer liess Texte weg): einzeiliger TEXT,
// Ankerpunkt = Einfügepunkt, Absätze eines Rich-Text-Felds mit Leerzeichen verbunden.
// 2D-Text: TEXT mit Textstil (Schriftname aus den Formatierungen, sonst Projekt-Schrift/Arial), linksbündig an
// der Grundlinie wie in der Plan-Ansicht; mehrere Absätze/Spaltenbreite als mehrere Zeilen darunter.
case "drawingText": {
const value = p.doc ? plainText(p.doc) : p.text;
if (value.trim() && p.heightM > 0) dxf.addText(layer, p.at, p.heightM, p.angle, value);
const lines = drawingTextLines(p);
const dir = { x: Math.sin(p.angle), y: -Math.cos(p.angle) }; // „nach unten“ im gedrehten Text
for (const l of lines) {
if (!l.text.trim() || !(l.height > 0)) continue;
const at = { x: p.at.x + dir.x * l.down, y: p.at.y + dir.y * l.down };
dxf.addText2(layer, at, l.height, p.angle, l.text, { style: ctx.styleOf(dxf, l.marks) });
}
break;
}
// Raumstempel (Name, Nutzung, Fläche): je Zeile ein TEXT, links/Mitte/rechts wie im Plan, um den Anker zentriert.
case "text": {
for (const l of stampLines(p, ctx.scale)) {
dxf.addText2(layer, { x: p.at.x, y: p.at.y - l.down }, l.height, 0, l.text, { halign: l.align, style: ctx.styleOf(dxf, l.marks) });
}
break;
}
case "polygon": {
const pts = p.pts;
if (pts.length < 2) break;
// Unsichtbare Pick-Bänder (Dach-Traufe, Kontext-Hülle, Schnittlinie): weder Füllung noch Umriss noch Schraffur.
if (p.stroke === "none" && p.fill === "none" && p.hatch.pattern === "none" && p.hatch.kind !== "gradient") break;
// Schraffur ([C2], 28.10.) als echte HATCH-Entität UNTER dem Umriss (Zeichenreihenfolge der
// Datei): Vollfüllung bzw. Linienmuster (diagonal/Kreuz/Dämmung/frei, auch gestrichelt) mit dem
// Polygon als Rand und der aufgelösten Vordergrundfarbe. Verlauf-Schraffur (kind==="gradient")
@@ -331,33 +894,35 @@ function emitPrimitive(
const rgb2 = g ? rgbOrNull(g.color2) : null;
if (g && rgb1 !== null && rgb2 !== null && Number.isFinite(g.angle)) {
// Richtung wie der SVG-Verlauf der Ansicht: Vektor (cos, sin) in Plan-Koordinaten = DXF-Winkel.
dxf.addGradient(LAYER_HATCH, pts, { rgb1, rgb2, angle: (g.angle * Math.PI) / 180, radial: g.type === "radial" });
dxf.addGradient(hatchLayer, pts, { rgb1, rgb2, angle: (g.angle * Math.PI) / 180, radial: g.type === "radial" });
}
} else if (includeHatches && p.hatch.kind !== "image" && pts.length >= 3) {
const h = p.hatch;
if (h.pattern === "solid") {
dxf.addHatch(LAYER_HATCH, pts, { solid: true, rgb: rgbOrNull(h.color) });
dxf.addHatch(hatchLayer, pts, { solid: true, rgb: rgbOrNull(h.color) });
} else if (h.pattern !== "none" && h.lines === "random") {
const cycle = dashCycleMeters(h.dash);
const segs: Seg[] = buildRandomHatchRuns(pts, h)
.filter((r) => r.length >= 2)
.map((r) => ({ a: r[0], b: r[r.length - 1] }));
dxf.setPen(-1);
for (const seg of segs) {
if (cycle) {
for (const d of dashSeg(seg, cycle)) dxf.addLine(LAYER_HATCH, d.a, d.b);
for (const d of dashSeg(seg, cycle)) dxf.addLine(hatchLayer, d.a, d.b);
} else {
dxf.addLine(LAYER_HATCH, seg.a, seg.b);
dxf.addLine(hatchLayer, seg.a, seg.b);
}
}
} else if (h.pattern !== "none") {
const families = hatchFamilies(h);
if (families.length > 0) {
dxf.addHatch(LAYER_HATCH, pts, { solid: false, rgb: rgbOrNull(h.color), families, dashes: dashCycleMeters(h.dash) ?? [] });
dxf.addHatch(hatchLayer, pts, { solid: false, rgb: rgbOrNull(h.color), families, dashes: dashCycleMeters(h.dash) ?? [] });
}
}
}
// Kreis-Approximationen (viele Segmente) bleiben als geschlossene Polylinie —
// masshaltig und robust. Geschlossene Ringe bekommen das Ring-Flag.
dxf.setPen(-1);
dxf.addPolyline(layer, pts, true);
break;
}
+9
View File
@@ -1736,6 +1736,15 @@ export const de = {
"exportDxf.failed": "Export fehlgeschlagen",
"exportDxf.unitsNote":
"Modell-Space in Metern (1:1). Layer entsprechen den Ebenen des Projekts; beim Plot beliebig skalierbar.",
"exportDxf.scale": "Massstab (Bemassung, Strichmuster, Beschriftung)",
"exportDxf.dimUnit": "Masszahlen in",
"exportDxf.dimUnit.m": "Meter (3.25)",
"exportDxf.dimUnit.cm": "Zentimeter (325)",
"exportDxf.layout": "Papierbereich",
"exportDxf.layout.no": "Nur Modellbereich",
"exportDxf.layout.yes": "Zusätzlich Layout mit Ansichtsfenster im Massstab",
"exportDxf.objectsNote":
"Bemassungen als DIMENSION (mit Bemassungsstil), Türen, Fenster und Möbelblöcke als BLOCK/INSERT mit Attributen, Strichmuster als Linientypen, Texte mit Textstil.",
// ── Datei-Menü (Burger, ganz rechts der Oberleiste) ──────────────────────
"file.menu": "Datei",
+9
View File
@@ -1724,6 +1724,15 @@ export const en: Record<TranslationKey, string> = {
"exportDxf.failed": "Export failed",
"exportDxf.unitsNote":
"Model space in meters (1:1). Layers mirror the project's categories; scale freely on plot.",
"exportDxf.scale": "Scale (dimensions, dash patterns, labels)",
"exportDxf.dimUnit": "Dimension values in",
"exportDxf.dimUnit.m": "Meters (3.25)",
"exportDxf.dimUnit.cm": "Centimeters (325)",
"exportDxf.layout": "Paper space",
"exportDxf.layout.no": "Model space only",
"exportDxf.layout.yes": "Add a layout with a viewport at the scale",
"exportDxf.objectsNote":
"Dimensions as DIMENSION entities (with dimension style), doors, windows and furniture blocks as BLOCK/INSERT with attributes, dash patterns as linetypes, text with text styles.",
// File menu (burger, far right of the top bar).
"file.menu": "File",
+4 -1
View File
@@ -125,7 +125,7 @@ export function useExportHandlers(opts: {
referenceLines,
planColorMode === "mono",
true, // includeGlobal (Default)
undefined, // scaleDenominator (Default)
decision.scaleDenominator, // Export-Massstab (wie PDF): Strichstärken, Bemassung
true, // forPrint: `Drawing2D.noPrint`-Elemente ausschliessen
);
try {
@@ -133,6 +133,9 @@ export function useExportHandlers(opts: {
title: activeLevelName,
includeHatches: decision.includeHatches,
format: decision.format,
scaleDenominator: decision.scaleDenominator,
dimUnit: decision.dimUnit,
paperLayout: decision.paperLayout,
fileName: `${project.name}-${activeLevelName}`,
});
} catch (err) {
+58 -1
View File
@@ -10,6 +10,7 @@ import { useEffect, useState } from "react";
import { t } from "../i18n";
import { Dropdown } from "./Dropdown";
import type { CadExportFormat } from "../export/exportDxf";
import { SCALE_PRESETS } from "./TopBar";
/** Entscheidung, die der Dialog beim Bestätigen liefert. */
export interface ExportDxfDecision {
@@ -18,6 +19,12 @@ export interface ExportDxfDecision {
includeHatches: boolean;
/** „nur Auswahl" statt des ganzen Plans (nur relevant, wenn `selectionCount > 0`). */
selectionOnly: boolean;
/** Massstabsnenner für Bemassungsstil, Strichmuster, Raumstempel und Ansichtsfenster. */
scaleDenominator: number;
/** Einheit der Masszahlen. */
dimUnit: "m" | "cm";
/** Zusätzlich ein Layout (Papierbereich) mit Ansichtsfenster anlegen. */
paperLayout: boolean;
}
export interface ExportDxfDialogProps {
@@ -25,6 +32,8 @@ export interface ExportDxfDialogProps {
planTitle: string;
/** s. `ExportPdfDialogProps.selectionCount`. */
selectionCount?: number;
/** Massstab der aktiven Ansicht (Vorgabe, Default 1:100). */
initialScale?: number;
onExport: (decision: ExportDxfDecision) => void;
onClose: () => void;
}
@@ -32,6 +41,7 @@ export interface ExportDxfDialogProps {
export function ExportDxfDialog({
planTitle,
selectionCount = 0,
initialScale = 100,
onExport,
onClose,
}: ExportDxfDialogProps) {
@@ -46,9 +56,24 @@ export function ExportDxfDialog({
const [format, setFormat] = useState<CadExportFormat>("dxf");
const [includeHatches, setIncludeHatches] = useState(true);
const [selectionOnly, setSelectionOnly] = useState(false);
const [scale, setScale] = useState<number>(initialScale);
const [dimUnit, setDimUnit] = useState<"m" | "cm">("m");
const [paperLayout, setPaperLayout] = useState(false);
const scaleOptions = [
...(SCALE_PRESETS.includes(scale) ? [] : [{ value: String(scale), label: `1:${scale}` }]),
...SCALE_PRESETS.filter((n) => n > 1).map((n) => ({ value: String(n), label: `1:${n}` })),
];
const onConfirm = () =>
onExport({ format, includeHatches, selectionOnly: selectionCount > 0 && selectionOnly });
onExport({
format,
includeHatches,
selectionOnly: selectionCount > 0 && selectionOnly,
scaleDenominator: scale,
dimUnit,
paperLayout,
});
return (
<div className="imp-overlay" onClick={onClose}>
@@ -101,7 +126,39 @@ export function ExportDxfDialog({
/>
</section>
<section className="imp-section">
<div className="imp-section-title">{t("exportDxf.scale")}</div>
<Dropdown value={String(scale)} onChange={(v) => setScale(Number(v))} title={t("exportDxf.scale")} options={scaleOptions} />
</section>
<section className="imp-section">
<div className="imp-section-title">{t("exportDxf.dimUnit")}</div>
<Dropdown
value={dimUnit}
onChange={(v) => setDimUnit(v === "cm" ? "cm" : "m")}
title={t("exportDxf.dimUnit")}
options={[
{ value: "m", label: t("exportDxf.dimUnit.m") },
{ value: "cm", label: t("exportDxf.dimUnit.cm") },
]}
/>
</section>
<section className="imp-section">
<div className="imp-section-title">{t("exportDxf.layout")}</div>
<Dropdown
value={paperLayout ? "yes" : "no"}
onChange={(v) => setPaperLayout(v === "yes")}
title={t("exportDxf.layout")}
options={[
{ value: "no", label: t("exportDxf.layout.no") },
{ value: "yes", label: t("exportDxf.layout.yes") },
]}
/>
</section>
<div className="imp-note">{t("exportDxf.unitsNote")}</div>
<div className="imp-note">{t("exportDxf.objectsNote")}</div>
{selectionCount > 0 && (
<section className="imp-section">