diff --git a/TODO.md b/TODO.md index 9fe0cc69..01c97f94 100644 --- a/TODO.md +++ b/TODO.md @@ -59,7 +59,7 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. oben ein Test; was fehlt, wird hier als Aufgabe eingetragen. · M Umgesetzt (12.11.): `e2e/release10.spec.ts` spielt leeres Projekt → Kataster-DXF (LV95) → Baurecht → Wände/Decke/Dach → Raum + Raumprogramm → SIA 416/Kennzahlen (CSV/PDF) → 1:200 → Schnitt → Axonometrie/Schatten → Präsentationsplan A1 → Publikation PDF → DXF/IFC - → Speichern in 13 Schritten durch; fehlende Schritte als `test.fixme` ([207] [208] [211] [222]–[224]; [209], [221] und [225] seit 12.11. aktiv). Behoben: GV in der + → Speichern in 13 Schritten durch; fehlende Schritte als `test.fixme` ([207] [208] [211] [222]; [223] [224] seit 13.11. aktiv; [209], [221] und [225] seit 12.11. aktiv). Behoben: GV in der Kennzahlenleiste war ohne freie Körper 0 m³, neue Decken bekamen den Aussenwand-Aufbau statt eines Deckentyps. Offen: Durchlauf der Checkliste auf dem Mac (Maintainer); 3D-Bild headless nicht prüfbar (kein WebGPU). @@ -190,14 +190,6 @@ Kennwort, anonym) als PDF; Austausch mit Fachplanern über DXF/IFC. - ○ **[222]** Volumenstudie → Bauteile (12.11., aus [206]): gewählten Körper (Massenmodell) in Aussenwände je Geschoss, Decken und Flachdach umwandeln, Geschosse aus der Körperhöhe; heute nur Zeichnen von Wand/Decke/Dach oder GV aus Körpern. Ort: neuer Befehl, Kern `cmd_create.rs`. · M -- ○ **[223]** 3D-Bild für die Abgabe (12.11., aus [206]; Punkt „3D-Bilder für die Abgabe“ oben): Befehl/Menü „3D-Bild exportieren …“ mit - Pixelgrösse (z. B. 6000 px), Perspektive/Axonometrie mit Schatten als PNG-Download bzw. Datei. Heute gibt es `snapshotPng` nur für BCF - (`viewport/Wasm3DViewport.tsx`), keinen Export für den Menschen; nativ über `render_png`. · S -- ○ **[224]** Präsentationsplan für den Wettbewerb (12.11., aus [206]): leere Geschosse (z. B. OG ohne Bauteile) sind im Dialog vorgewählt - und geben leere Viewports; es gibt nur die vorhandenen Ansichten (leeres Projekt: nur „Ansicht Süd“) — fehlende Ansichten N/O/W aus dem - Gebäudeumriss anbieten; Massstab wählbar (heute der grösste passende, im Testgebäude auf A1 1:50 statt 1:200 für den Wettbewerb). - Ort: `ui/PresentationDialog.tsx`, `commands/cmds/presentation.ts`. · S - - ✓ **[229]** Cycles-Rendering: Streifen/Dreiecke auf der Hauptdachfläche (12.11., Maintainer, Musterhaus komplex Iso). Ursache: Das GLB hat keine UVs; der Normal-Map-Knoten (Tangentenraum) bekam je Dreieck einen anderen Tangentenrahmen und zeichnete die Gauben-Fan-Triangulierung als helle/dunkle Diagonalen. Nicht im Netz: GLB geprüft (Normalen der Dachdreiecke an der Oberseite max. 0.0002 rad neben der Flächennormalen, @@ -1144,6 +1136,16 @@ exakte Durchdringung, [61] Zuordnung per Hand, [63] Profil je Kante, [70] Fläch - **[192]** Ebenen schnell schalten (11.11.): Rechtsklick auf eine Zeile im Ebenen-Panel „Nur diese Ebene anzeigen“ / „Diese Ebene ausblenden“ / „Alle Ebenen einblenden“; im Kontextmenü von Objekt und leerer Fläche (Plan, Schnitt, Ansicht, 3D) „Ebene des Objekts isolieren/ausblenden“ und „Alle Ebenen einblenden“. Sichtbarkeit bleibt `layers[].visible` über Ops (`state/layerIsolate.ts`, ein Undo-Schritt je Aktion); Isolieren lässt Elternklassen an; „Alle einblenden“ stellt den Zustand vor dem ersten Isolieren wieder her (gemerkt je Sitzung/Projekt-Epoche), sonst alles an. Kürzel (umbelegbar): Cmd/Ctrl+Shift+L Ebene der Auswahl isolieren (Cmd+Shift+I ist Boolean-Schnitt), Cmd/Ctrl+Shift+E alle Ebenen einblenden. Test: vitest `layerIsolate.test.ts`, e2e `layerIsolate.spec.ts` (Linux-Chromium; nicht in der Tauri-App geprüft; das native Menü hat keinen Eintrag). - **[51]** Herkunft übernommenen Codes (12.11.): Inventur; `NOTICE` ergänzt um delaunator/robust-predicates (`core/delaunay.rs`), polylabel (Verfahren, `room_area.rs`), Manifold (Urheber, `solid_bool.rs`), ambientCG-Texturen (CC0), Tango-/Material-Farbwerte; Dateiköpfe `Herkunft:` in `delaunay.rs`, `solid_bool.rs`, `ifc_nurbs.rs` (csg.rs, skeleton.rs hatten ihn schon); Test `src/core/notice.test.ts` (Datei mit `Herkunft:` im Kopf muss in NOTICE stehen, NOTICE-Pfade existieren, jede Schrift hat OFL.txt). Offen/ungeklärt: Herkunft und Lizenz der App-Icons (`src-tauri/icons`) und der Website-Bilder nicht belegt; Mapbox-Copyright ohne Jahr übernommen (die LICENSE im Upstream nennt ein Jahr, das nach Vorlage aussieht); Lizenztexte der Rust-/npm-Abhängigkeiten liegen nur in den Paketen (cargo-deny prüft die Lizenzart, keine Attribution-Datei im Produkt). +- **[223]** 3D-Bild für die Abgabe (13.11.): Befehl `bild3d` (Alias `3dbild`, `bildexport`) und Menü Ansicht → „3D-Bild exportieren …“ öffnen + `ui/ImageExportDialog.tsx`: Auflösung Ansicht / Full HD / 4K / A4–A2 bei 300 dpi / eigene Grösse, transparenter Hintergrund, Kamera live + oder gespeichert ([213], `cameraToView`), Speichern als PNG oder „Ins Layout einsetzen“ (`layoutImageActions`, wie [211]). render3d + zeichnet direkt in der Zielgrösse (`useWasm3dRenderer.exportImage`, Kante begrenzt auf `IMAGE_MAX_EDGE`), mit der aktuellen + Darstellung; Transparenz aus zwei Durchgängen auf Schwarz/Weiss (`imageExport.matteFromBlackWhite`, `WebModelRenderer::set_clear_color`). + Nicht in Tauri/Metal geprüft; headless kein WebGPU-Bild → e2e (`release10.spec.ts`) prüft Dialog/Grössen/Einsetzen über `__dossierImageMock`. +- **[224]** Präsentationsplan für den Wettbewerb (13.11.): leere Geschosse nicht vorgewählt (Markierung „leer“), nur vorhandene Ansichten + (einzeln wählbar) und Schnitte, Massstab gemeinsam (Vorgabe 1:200) und je Viewport wählbar, Plakat-Vorlage ([208]) als Ziel + (eigener Rand/obere Kante unter der Kopfzeile); Kern `presentation_sheet.rs` (`choose_fixed`, `scale`/`scales`/`marginMm`/`topMm`). Fehlende + Ansichten N/O/W werden nicht automatisch erzeugt (Befehl `viewline` von Hand). e2e `release10.spec.ts` und `presentationSheet.spec.ts`. - **[221]** LV95-Projekte (12.11.): Entscheid: das Modell bleibt lokal um einen Projekt-Nullpunkt, statt Landeskoordinaten (≈ 2.6 Mio. m) im Modell zu führen — f32 in 3D/GPU (≈ 25 cm Raster bei LV95), das Ganzzahlraster der Booleans und alle Ausmass-Rechnungen vertragen das nicht. Der DXF/DWG-Import „an DXF-Koordinaten" in LV95 setzt ohne Standort-Bezug den diff --git a/doc/RELEASE-1.0.md b/doc/RELEASE-1.0.md index c5557cd6..14834c4a 100644 --- a/doc/RELEASE-1.0.md +++ b/doc/RELEASE-1.0.md @@ -91,7 +91,7 @@ E 2'600'048 / N 1'200'046 und E 2'600'060 / N 1'200'056. Raumprogramm als CSV (` |---|---|---|---| | 7.1 | Kopfleiste „Axonometrie“ | eigener Reiter „3D · Erdgeschoss“ | ✅ (Spec 9; Bild nur auf dem Mac prüfbar) | | 7.2 | Gelände → „Schatten im 3D zeigen“, Datum 21.03./21.06./21.12., Uhrzeit | Schatten im 3D und (Haken) im Grundriss | ◐ Schalter geprüft, Bild nur auf dem Mac | -| 7.3 | 3D-Bild als PNG in Abgabeauflösung | PNG-Datei, z. B. 6000 px breit | ❌ **[223]** | +| 7.3 | 3D-Bild als PNG in Abgabeauflösung | PNG-Datei, z. B. 6000 px breit | ✓ **[223]** Befehl `bild3d` (Mac: Metal-Gegenprobe offen) | | 7.4 | „Rendering …“ (Blender/Cycles) | PNG zurück, ins Layout einsetzbar | ❌ **[211]** | ## 8. Flächen und Volumen SIA 416, Kennzahlen @@ -115,7 +115,7 @@ E 2'600'048 / N 1'200'046 und E 2'600'060 / N 1'200'056. Raumprogramm als CSV (` | # | Schritt in Dossier | Erwartet | Status | |---|---|---|---| -| 10.1 | Panel **Mappe** → „Präsentationsplan erstellen“ (Befehl `praesentationsplan`), Schnitt B, A1 | Blatt mit Grundrissen, Ansicht, Schnitt, Nordpfeil, Massstabsbalken, gemeinsamer Massstab | ◐ geht (Spec 10), aber leeres OG als leerer Viewport, nur „Ansicht Süd“ → **[224]** | +| 10.1 | Panel **Mappe** → „Präsentationsplan erstellen“ (Befehl `praesentationsplan`), Schnitt B, A1 | Blatt mit Grundrissen, Ansicht, Schnitt, Nordpfeil, Massstabsbalken, gemeinsamer Massstab | ✓ geht (Spec 10) — [224] erledigt (leere Geschosse nicht vorgewählt, 1:200, Plakat als Ziel) | | 10.2 | Mappe → Publikation → + Satz, Blatt anhaken, „Publizieren“ | ein PDF (A1, 1 Seite), Index im Titelblock | ✅ (Spec 11) | | 10.3 | Plakat A0/A1 mit Raster, Kennwort-Feld, anonym (kein Büroname, PDF-Metadaten leer), Bilder im Layout | WBW-Plakat als PDF | ❌ **[208]** | diff --git a/e2e/presentationSheet.spec.ts b/e2e/presentationSheet.spec.ts index d85f7856..59d1776d 100644 --- a/e2e/presentationSheet.spec.ts +++ b/e2e/presentationSheet.spec.ts @@ -22,18 +22,22 @@ test("Präsentationsplan: Dialog erstellt Blatt mit N Viewports, Undo entfernt e await expect(dialog).toBeVisible(); const floors = dialog.locator("input[data-floor]"); - const nFloors = await floors.count(); - expect(nFloors).toBeGreaterThanOrEqual(4); - // Erstes Geschoss abwählen, Ansichten + Schnitt bleiben. + // [224] Nur vorhandene Ansichten, einzeln wählbar; leere Geschosse sind nicht vorgewählt. + const elevs = dialog.locator("input[data-testid^=presentation-elevation-]"); + expect(await elevs.count()).toBeGreaterThanOrEqual(1); + for (let i = 0; i < (await elevs.count()); i++) await elevs.nth(i).check(); + // Erstes Geschoss abwählen (falls vorgewählt), Rest bleibt. await floors.first().uncheck(); - await expect(dialog.locator("[data-testid=presentation-elevations]")).toBeChecked(); expect(await dialog.locator("[data-testid=presentation-section]").inputValue()).not.toBe(""); + let nFloors = 0; + for (let i = 0; i < (await floors.count()); i++) if (await floors.nth(i).isChecked()) nFloors++; + const nElev = await elevs.count(); await dialog.locator("[data-testid=presentation-create]").click(); await expect(dialog).toBeHidden(); - // Blatt ist offen: Grundrisse (ohne das abgewählte) + 4 Ansichten + 1 Schnitt. + // Blatt ist offen: gewählte Grundrisse + Ansichten + 1 Schnitt. const vps = page.locator("[data-viewport-id]"); - await expect(vps).toHaveCount(nFloors - 1 + 4 + 1, { timeout: 20_000 }); + await expect(vps).toHaveCount(nFloors + nElev + 1, { timeout: 20_000 }); await page.waitForTimeout(1500); const shots = process.env.DOSSIER_SHOTS; if (shots) await page.screenshot({ path: `${shots}/presentation-sheet.png` }); diff --git a/e2e/release10.spec.ts b/e2e/release10.spec.ts index b3dac986..6a87214b 100644 --- a/e2e/release10.spec.ts +++ b/e2e/release10.spec.ts @@ -9,7 +9,7 @@ // Mit DOSSIER_SHOTS= entsteht je Schritt ein Bildschirmfoto. import { readFile, writeFile } from "node:fs/promises"; import type { Page } from "@playwright/test"; -import { blurFocus, elementRows, expect, fileMenu, finishCommand, openTab, startNewProject, test, typeCommand } from "./app"; +import { blurFocus, discardIfAsked, elementRows, expect, fileMenu, finishCommand, openTab, startNewProject, test, typeCommand } from "./app"; import { KATASTER_DXF } from "./paths"; const E0 = 2_600_000; @@ -349,11 +349,63 @@ test.fixme("[222] Volumenstudie: Wände/Decken/Dach aus einem Volumen (Körper) test.fixme("[207] Situation 1:500 / Schwarzplan als Ansichtsvorlage „Situation WBW“", async () => {}); -test.fixme("[223] 3D-Bild für die Abgabe: hochaufgelöster PNG-Export (Perspektive/Axonometrie, mit Schatten)", async () => {}); +// [223] Headless liefert WebGPU kein Bild: `__dossierImageMock` (cameraBridge.captureImage) ersetzt das Offscreen-Zeichnen; +// geprüft werden Dialog, Zielgrösse, Optionen, Ergebnis und Einsetzen ins Layout — nicht die Pixel. +test("[223] 3D-Bild für die Abgabe: Auflösung wählen, exportieren, ins Layout einsetzen", async ({ page }) => { + test.setTimeout(120_000); + await startNewProject(page); + await fileMenu(page, /Musterhaus \(komplex\)/); + await discardIfAsked(page); + await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 }); + await page.evaluate(() => { + const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), (c) => c.charCodeAt(0)); + (globalThis as { __dossierImageMock?: unknown }).__dossierImageMock = async (o: { width: number; height: number; transparent: boolean }) => ({ png, width: o.width, height: o.height, transparent: o.transparent }); + }); + await typeCommand(page, "bild3d"); + const dialog = page.getByTestId("image3d-dialog"); + await expect(dialog).toBeVisible(); + // A3 bei 300 dpi. + await dialog.getByTestId("image3d-size").selectOption("a3"); + await expect(dialog.getByTestId("image3d-width")).toHaveValue("4961"); + await expect(dialog.getByTestId("image3d-height")).toHaveValue("3508"); + await dialog.getByTestId("image3d-size").selectOption("uhd"); + await expect(dialog.getByTestId("image3d-width")).toHaveValue("3840"); + await dialog.getByTestId("image3d-transparent").check(); + await dialog.getByTestId("image3d-start").click(); + await expect(dialog.getByTestId("image3d-result")).toBeVisible({ timeout: 20_000 }); + await expect(dialog.getByTestId("image3d-save")).toBeVisible(); + const toLayout = dialog.getByTestId("image3d-to-layout"); + if (await toLayout.isEnabled()) { + await toLayout.click(); + await expect(page.getByText(/eingesetzt|Layout/).first()).toBeVisible(); + } +}); test.fixme("[211] Rendering mit Blender/Cycles aus der 3D-Ansicht", async () => {}); -test.fixme("[224] Präsentationsplan: leere Geschosse nicht vorgewählt, Ansichten N/O/W aus dem Gebäude", async () => {}); +test("[224] Präsentationsplan: leere Geschosse nicht vorgewählt, Massstab 1:200, Plakat als Ziel", async ({ page }) => { + test.setTimeout(120_000); + await startNewProject(page); + await fileMenu(page, /Musterhaus \(komplex\)/); + await discardIfAsked(page); + await expect(page.locator(".project-name")).toHaveText("Musterhaus komplex", { timeout: 30_000 }); + await typeCommand(page, "praesentation"); + const dialog = page.getByRole("dialog", { name: "Präsentationsplan" }); + await expect(dialog).toBeVisible(); + // Vorgabe 1:200, Plakat-Vorlage wählbar, nur vorhandene Ansichten. + await expect(dialog.getByTestId("presentation-scale")).toHaveValue("200"); + expect(await dialog.getByTestId("presentation-target").locator("option").count()).toBeGreaterThan(1); + // Leere Geschosse (Markierung „leer“) sind nicht vorgewählt. + const floors = dialog.locator("input[data-floor]"); + for (let i = 0; i < (await floors.count()); i++) { + const label = floors.nth(i).locator("xpath=.."); + const isEmpty = /leer/i.test((await label.textContent()) ?? ""); + if (isEmpty) await expect(floors.nth(i)).not.toBeChecked(); + } + await dialog.getByTestId("presentation-create").click(); + await expect(dialog).toBeHidden(); + await expect(page.locator("[data-viewport-id]").first()).toBeVisible({ timeout: 20_000 }); +}); test.fixme("[208] Wettbewerbs-Plakat A0/A1 mit Kennwort, anonymes PDF (keine Büro-Metadaten)", async () => {}); diff --git a/src-tauri/core/src/presentation_sheet.rs b/src-tauri/core/src/presentation_sheet.rs index 42276af5..76d1b97a 100644 --- a/src-tauri/core/src/presentation_sheet.rs +++ b/src-tauri/core/src/presentation_sheet.rs @@ -40,18 +40,34 @@ pub struct Sheet { pub w: f64, pub h: f64, pub title_block: Option<[f64; 4]>, + /// Rand links/rechts/unten (mm). + pub margin: f64, + /// Obere Kante der Inhaltsfläche (mm); bei Plakaten unter der Kopfzeile ([224]). + pub top: f64, } impl Sheet { pub fn new(w: f64, h: f64, title_block: bool) -> Sheet { let [tw, th, pad] = TITLE_BLOCK_MM; - Sheet { w, h, title_block: title_block.then(|| [w - tw - pad, h - th - pad, tw, th]) } + Sheet { w, h, title_block: title_block.then(|| [w - tw - pad, h - th - pad, tw, th]), margin: MARGIN_MM, top: MARGIN_MM } + } + + /// Eigene Ränder (Plakat-Vorlage): `margin` seitlich/unten, `top` oben. Unsinn (NaN, negativ, zu gross) bleibt beim Standard. + pub fn with_area(mut self, margin: Option, top: Option) -> Sheet { + let ok = |v: f64| v.is_finite() && v >= 0.0 && v < self.w.min(self.h) / 2.0; + if let Some(m) = margin.filter(|v| ok(*v)) { + self.margin = m; + } + if let Some(t) = top.filter(|v| ok(*v)) { + self.top = t; + } + self } } /// Zeilen ab `y0` füllen; `strict`: `None`, wenn eine Zeile oder der Block nicht aufs Blatt passt. fn pack_from(items: &[(u32, f64, f64)], sheet: &Sheet, y0: f64, strict: bool) -> Option<(Vec, f64)> { - let (l, r, b) = (MARGIN_MM, sheet.w - MARGIN_MM, sheet.h - MARGIN_MM); + let (l, r, b) = (sheet.margin, sheet.w - sheet.margin, sheet.h - sheet.margin); let mut out = vec![Rect::default(); items.len()]; let mut y = y0; let mut i = 0; @@ -91,7 +107,7 @@ fn pack_from(items: &[(u32, f64, f64)], sheet: &Sheet, y0: f64, strict: bool) -> /// reihenfolge; `None`, wenn sie nicht aufs Blatt passen. Der Block wird senkrecht zentriert, wenn das /// die Zeilen nicht verändert. pub fn pack(items: &[(u32, f64, f64)], sheet: &Sheet) -> Option> { - let (top, b) = (MARGIN_MM, sheet.h - MARGIN_MM); + let (top, b) = (sheet.top, sheet.h - sheet.margin); let (first, bottom) = pack_from(items, sheet, top, true)?; let off = (b - bottom) / 2.0; if off > 0.0 { @@ -119,7 +135,17 @@ pub fn choose(mut sizes_at: impl FnMut(f64) -> Vec<(u32, f64, f64)>, sheet: &She } } let s = SCALES[SCALES.len() - 1]; - let rects = pack_from(&sizes_at(s), sheet, MARGIN_MM, false).map(|r| r.0).unwrap_or_default(); + let rects = pack_from(&sizes_at(s), sheet, sheet.top, false).map(|r| r.0).unwrap_or_default(); + Choice { scale: s, fits: false, rects } +} + +/// Fester Massstab `s` ([224]): passt es, `fits = true`, sonst überlaufende Zeilen (`fits = false`). +pub fn choose_fixed(mut sizes_at: impl FnMut(f64) -> Vec<(u32, f64, f64)>, sheet: &Sheet, s: f64) -> Choice { + let sizes = sizes_at(s); + if let Some(rects) = pack(&sizes, sheet) { + return Choice { scale: s, fits: true, rects }; + } + let rects = pack_from(&sizes, sheet, sheet.top, false).map(|r| r.0).unwrap_or_default(); Choice { scale: s, fits: false, rects } } @@ -138,6 +164,13 @@ pub struct Request { pub title_block: bool, /// Schatten der Ansichten (Vorlage „Präsentation"). pub shadows: bool, + /// [224] Fester gemeinsamer Massstab (1:N); fehlt er, wählt der Kern den grössten, der passt. + pub scale: Option, + /// [224] Massstab je Ebene (übersteuert den gemeinsamen). + pub scales: BTreeMap, + /// [224] Eigener Rand/obere Kante (Plakat-Vorlage, unter der Kopfzeile). + pub margin_mm: Option, + pub top_mm: Option, } /// Abfrage `presentationSheet`: Massstab und Rahmen für die Ebenen; Ebenen ohne Inhalt stehen unter @@ -167,22 +200,28 @@ pub fn query(p: &Project, text: &str) -> Result { } } kept.sort_by_key(|k| k.1); - let sheet = Sheet::new(req.sheet_w, req.sheet_h, req.title_block); - let choice = choose( - |s| { - kept.iter() - .map(|(id, g)| { - let b = bounds_at(id, s).unwrap_or([0.0, 0.0, 1.0, 1.0]); - (*g, (b[2] - b[0]) * 1000.0 / s, (b[3] - b[1]) * 1000.0 / s) - }) - .collect() - }, - &sheet, - ); + let sheet = Sheet::new(req.sheet_w, req.sheet_h, req.title_block).with_area(req.margin_mm, req.top_mm); + let valid = |v: f64| v.is_finite() && v > 0.0; + let own = |id: &str| req.scales.get(id).copied().filter(|v| valid(*v)); + let sizes_at = |s: f64| -> Vec<(u32, f64, f64)> { + kept.iter() + .map(|(id, g)| { + let sc = own(id).unwrap_or(s); + let b = bounds_at(id, sc).unwrap_or([0.0, 0.0, 1.0, 1.0]); + (*g, (b[2] - b[0]) * 1000.0 / sc, (b[3] - b[1]) * 1000.0 / sc) + }) + .collect() + }; + let all_own = !kept.is_empty() && kept.iter().all(|(id, _)| own(id).is_some()); + let choice = match req.scale.filter(|v| valid(*v)) { + Some(s) => choose_fixed(sizes_at, &sheet, s), + None if all_own => choose_fixed(sizes_at, &sheet, 100.0), + None => choose(sizes_at, &sheet), + }; let items: Vec = kept .iter() .zip(&choice.rects) - .map(|((id, g), r)| json!({"levelId": id, "group": g, "xMm": r.x_mm, "yMm": r.y_mm, "widthMm": r.width_mm, "heightMm": r.height_mm})) + .map(|((id, g), r)| json!({"levelId": id, "group": g, "scale": own(id).unwrap_or(choice.scale), "xMm": r.x_mm, "yMm": r.y_mm, "widthMm": r.width_mm, "heightMm": r.height_mm})) .collect(); Ok(json!({"scale": choice.scale, "fits": choice.fits, "items": items, "skipped": skipped})) } @@ -262,6 +301,24 @@ mod tests { assert_eq!(pack(&[], &s), Some(vec![])); } + /// [224] Fester Massstab 1:200 (Wettbewerb) wird eingehalten, passt es; sonst `fits = false`. Plakat-Rand und + /// obere Kante begrenzen die Fläche. + #[test] + fn fester_massstab_und_plakatflaeche() { + let s = Sheet::new(841.0, 594.0, false); + let sizes = |sc: f64| (0..3).map(|_| (0, 12000.0 / sc, 10000.0 / sc)).collect::>(); + let c = choose_fixed(sizes, &s, 200.0); + assert!(c.fits && c.scale == 200.0 && c.rects.len() == 3); + let tiny = choose_fixed(sizes, &s, 10.0); + assert!(!tiny.fits && tiny.scale == 10.0); + let poster = Sheet::new(841.0, 594.0, false).with_area(Some(20.0), Some(78.0)); + let r = pack(&sizes(200.0), &poster).expect("passt"); + assert!(r.iter().all(|f| f.y_mm >= 78.0 - 1e-9 && f.x_mm >= 20.0 - 1e-9 && f.x_mm + f.width_mm <= 841.0 - 20.0 + 1e-9)); + // Unsinn bleibt beim Standard. + let bad = Sheet::new(841.0, 594.0, false).with_area(Some(f64::NAN), Some(-3.0)); + assert_eq!((bad.margin, bad.top), (MARGIN_MM, MARGIN_MM)); + } + #[test] fn unsinn_wird_abgelehnt() { let p = Project::default(); diff --git a/src-tauri/render3d/src/web.rs b/src-tauri/render3d/src/web.rs index 96c708b4..48de8998 100644 --- a/src-tauri/render3d/src/web.rs +++ b/src-tauri/render3d/src/web.rs @@ -658,6 +658,20 @@ impl WebModelRenderer { self.renderer.clear_point_clouds(); } + /// [223] Hintergrundfarbe (0..1) setzen; Standard #f5f5f5. Der Bild-Export rendert damit zweimal + /// (schwarz/weiss) und rechnet daraus einen transparenten Hintergrund. NaN wird verworfen. + pub fn set_clear_color(&mut self, r: f32, g: f32, b: f32) { + if ![r, g, b].iter().all(|v| v.is_finite()) { + return; + } + self.renderer.clear_color = wgpu::Color { + r: r.clamp(0.0, 1.0) as f64, + g: g.clamp(0.0, 1.0) as f64, + b: b.clamp(0.0, 1.0) as f64, + a: 1.0, + }; + } + /// Surface an eine neue Pixelgroesse anpassen (DPR beachtet der Aufrufer). pub fn resize(&mut self, width: u32, height: u32) { let (w, h) = (width.max(1), height.max(1)); diff --git a/src/commands/cmds/imageExport.ts b/src/commands/cmds/imageExport.ts new file mode 100644 index 00000000..ac2d21a8 --- /dev/null +++ b/src/commands/cmds/imageExport.ts @@ -0,0 +1,28 @@ +// [223] 3D-Bild exportieren — öffnet den Dialog (in App montiert) und endet sofort; Muster `rendering`. + +import { openImageExportDialog } from "../../state/imageExportDialogHook"; +import type { Command, CommandResult, CommandState } from "../types"; + +const IDLE: CommandState = { phase: "idle", lastPoint: null }; + +function open(): [CommandState, CommandResult] { + openImageExportDialog(); + return [{ ...IDLE }, { draft: null, done: true }]; +} + +export const imageExportCommand: Command = { + name: "bild3d", + labelKey: "cmd.bild3d.label", + prompt: () => "cmd.bild3d.prompt", + accepts: () => [], + options: () => [], + init: () => ({ ...IDLE }), + autoRun: (): CommandResult => { + openImageExportDialog(); + return { draft: null, done: true }; + }, + onInput: () => open(), + onMove: (state): [CommandState, CommandResult] => [state, { draft: null }], + onConfirm: () => open(), + onCancel: (): [CommandState, CommandResult] => [{ ...IDLE }, { draft: null, done: true }], +}; diff --git a/src/commands/registry.ts b/src/commands/registry.ts index 40e64e30..3d8113ff 100644 --- a/src/commands/registry.ts +++ b/src/commands/registry.ts @@ -77,6 +77,7 @@ import { defblockCommand } from "./cmds/defblock"; import { presentationCommand } from "./cmds/presentation"; import { traceMoveCommand, traceRotateCommand } from "./cmds/tracemove"; import { renderingCommand } from "./cmds/rendering"; +import { imageExportCommand } from "./cmds/imageExport"; /** Alle bekannten Befehle, Schlüssel = Befehlsname (lowercase). */ export const COMMANDS: Record = { @@ -151,6 +152,7 @@ export const COMMANDS: Record = { import: importCommand, praesentation: presentationCommand, rendering: renderingCommand, + bild3d: imageExportCommand, terrain: terrainCommand, excavation: excavationCommand, meshcrop: meshCropCommand, @@ -206,6 +208,9 @@ export const ALIASES: Record = { render: "rendering", blender: "rendering", rendern: "rendering", + image3d: "bild3d", + "3dbild": "bild3d", + bildexport: "bild3d", lukarne: "dormer", dachhof: "roofhole", lichthof: "roofhole", diff --git a/src/core/extra.ts b/src/core/extra.ts index dffbc951..26ad827c 100644 --- a/src/core/extra.ts +++ b/src/core/extra.ts @@ -86,7 +86,7 @@ export { AI_TOOLS, AI_BRIDGE_DEFAULT_PORT, aiText, aiToolDef, hmacHex, randomHex export type { AiToolDef, AiToolResult, AiBridgeMsg } from "./aiToolDefs"; export { callAiTool } from "./aiTools"; export type { AiHost } from "./aiTools"; -export { PRESENTATION_TEMPLATE_ID, presentationDefaults, presentationSheetOps, planPresentationSheet } from "../plan/presentationSheet"; +export { PRESENTATION_SCALES, PRESENTATION_DEFAULT_SCALE, levelHasContent, PRESENTATION_TEMPLATE_ID, presentationDefaults, presentationSheetOps, planPresentationSheet } from "../plan/presentationSheet"; export type { PresentationOptions, PresentationPlan, PresentationLabels } from "../plan/presentationSheet"; export { lineEndsOf, lineEndsCode, lineEndsFromCode, lineEndsSvgAttrs, planLineEndsProps, MITER_LIMIT as LINE_MITER_LIMIT } from "../model/lineEnds"; export type { LineEnds } from "../model/lineEnds"; diff --git a/src/i18n/de.ts b/src/i18n/de.ts index 72995716..f623cff1 100644 --- a/src/i18n/de.ts +++ b/src/i18n/de.ts @@ -3907,12 +3907,17 @@ export const de = { "presentation.title": "Präsentationsplan", "presentation.button": "Präsentationsplan erstellen", "presentation.floors": "Geschosse", + "presentation.floorEmpty": "(leer)", + "presentation.noElevations": "Keine Ansichten im Projekt", + "presentation.scale.auto": "Massstab automatisch", + "presentation.scale.common": "gemeinsamer Massstab", + "presentation.target.sheet": "Neues Blatt (Format wählen)", "presentation.elevations": "Ansichten", "presentation.section": "Schnitt", "presentation.noSection": "Kein Schnitt", "presentation.sheet": "Blatt", "presentation.sketch": "Skizzenstil (gezeigte Ebenen)", - "presentation.hint": "Der gemeinsame Massstab wird so gewählt, dass alles aufs Blatt passt; die Ausschnitte folgen der Vorlage „Präsentation“.", + "presentation.hint": "Vorgabe 1:200 (Wettbewerb); „automatisch“ wählt den grössten Massstab, der aufs Blatt passt; je Ansicht ist ein eigener wählbar; die Ausschnitte folgen der Vorlage „Präsentation“.", "presentation.create": "Erstellen", "presentation.sheetName": "Präsentationsplan", "presentation.masterName": "Planrahmen {format}", @@ -3926,6 +3931,28 @@ export const de = { // [211] Rendering mit Blender/Cycles "cmd.rendering.label": "Rendering…", "cmd.rendering.prompt": "Rendering mit Blender einrichten …", + "cmd.bild3d.label": "3D-Bild exportieren…", + "cmd.bild3d.prompt": "3D-Bild als PNG exportieren …", + "menu.view.image3d": "3D-Bild exportieren …", + "image3d.title": "3D-Bild exportieren", + "image3d.intro": "Zeichnet die aktuelle 3D-Ansicht (Darstellung, Schatten, Kanten, Texturen) direkt in der gewählten Auflösung als PNG; nicht ein Bildschirmfoto.", + "image3d.size.view": "Ansicht (2000 px)", + "image3d.size.hd": "Full HD (1920 × 1080)", + "image3d.size.uhd": "4K (3840 × 2160)", + "image3d.size.a4": "A4 quer, 300 dpi", + "image3d.size.a3": "A3 quer, 300 dpi", + "image3d.size.a2": "A2 quer, 300 dpi", + "image3d.size.custom": "Eigene Grösse", + "image3d.clamped": "Die Grafikkarte erlaubt höchstens {max} px je Seite: das Bild wird {width} × {height} px.", + "image3d.transparent": "Transparenter Hintergrund", + "image3d.working": "Zeichne {width} × {height} px …", + "image3d.done": "Bild {width} × {height} px erstellt", + "image3d.start": "Bild erzeugen", + "image3d.empty": "Das 3D-Bild ist leer (kein Modell sichtbar oder kein Bild von der Grafikkarte).", + "image3d.noViewport": "Keine 3D-Ansicht offen: zuerst in den 3D-Reiter wechseln.", + "image3d.cameraBad": "Die gewählte Kamera ist unbrauchbar (Standpunkt gleich Ziel).", + "image3d.noTransparency": "Transparenter Hintergrund ist mit diesem Renderer nicht möglich: Bild mit Hintergrund erstellt.", + "image3d.saved": "3D-Bild gespeichert", "menu.view.rendering": "Rendering mit Blender …", "render.title": "Rendering mit Blender", "render.intro": "Fotorealistisches Bild der aktiven 3D-Ansicht mit Blender/Cycles (installiertes Blender, läuft als eigener Prozess).", diff --git a/src/i18n/en.ts b/src/i18n/en.ts index f5a29bca..2ef414fc 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -3893,12 +3893,17 @@ export const en: Record = { "presentation.title": "Presentation sheet", "presentation.button": "Create presentation sheet", "presentation.floors": "Floors", + "presentation.floorEmpty": "(empty)", + "presentation.noElevations": "No elevations in the project", + "presentation.scale.auto": "Scale automatic", + "presentation.scale.common": "common scale", + "presentation.target.sheet": "New sheet (choose format)", "presentation.elevations": "Elevations", "presentation.section": "Section", "presentation.noSection": "No section", "presentation.sheet": "Sheet", "presentation.sketch": "Sketch style (shown views)", - "presentation.hint": "A common scale is chosen so that everything fits on the sheet; the views follow the “Presentation” template.", + "presentation.hint": "Default 1:200 (competition); “automatic” picks the largest scale that fits the sheet; each view can have its own scale; the views follow the “Presentation” template.", "presentation.create": "Create", "presentation.sheetName": "Presentation sheet", "presentation.masterName": "Sheet frame {format}", @@ -3912,6 +3917,28 @@ export const en: Record = { // [211] Rendering mit Blender/Cycles "cmd.rendering.label": "Rendering…", "cmd.rendering.prompt": "Set up rendering with Blender …", + "cmd.bild3d.label": "Export 3D image…", + "cmd.bild3d.prompt": "Export 3D image as PNG …", + "menu.view.image3d": "Export 3D Image …", + "image3d.title": "Export 3D image", + "image3d.intro": "Draws the current 3D view (display mode, shadows, edges, textures) directly at the chosen resolution as PNG; not a screenshot.", + "image3d.size.view": "View (2000 px)", + "image3d.size.hd": "Full HD (1920 × 1080)", + "image3d.size.uhd": "4K (3840 × 2160)", + "image3d.size.a4": "A4 landscape, 300 dpi", + "image3d.size.a3": "A3 landscape, 300 dpi", + "image3d.size.a2": "A2 landscape, 300 dpi", + "image3d.size.custom": "Custom size", + "image3d.clamped": "The graphics card allows at most {max} px per side: the image will be {width} × {height} px.", + "image3d.transparent": "Transparent background", + "image3d.working": "Drawing {width} × {height} px …", + "image3d.done": "Image {width} × {height} px created", + "image3d.start": "Create image", + "image3d.empty": "The 3D image is empty (no model visible or no image from the graphics card).", + "image3d.noViewport": "No 3D view open: switch to the 3D tab first.", + "image3d.cameraBad": "The chosen camera is unusable (position equals target).", + "image3d.noTransparency": "Transparent background is not possible with this renderer: image created with background.", + "image3d.saved": "3D image saved", "menu.view.rendering": "Render with Blender …", "render.title": "Render with Blender", "render.intro": "Photorealistic image of the active 3D view with Blender/Cycles (installed Blender, runs as a separate process).", diff --git a/src/native/appMenu.ts b/src/native/appMenu.ts index 94f88b26..87b37502 100644 --- a/src/native/appMenu.ts +++ b/src/native/appMenu.ts @@ -16,6 +16,7 @@ import { useEffect, useRef } from "react"; import { isTauriRuntime } from "./projectFile"; import { t } from "../i18n"; import { openRenderDialog } from "../state/renderDialogHook"; +import { openImageExportDialog } from "../state/imageExportDialogHook"; import { APP_VERSION } from "../ui/TopBar"; import type { View3d, ViewType } from "../model/viewTypes"; import type { SelectionActionId } from "../state/selectionActions"; @@ -425,6 +426,10 @@ export function useNativeAppMenu( }), // [211] Rendering mit Blender/Cycles (Dialog in App montiert, Öffner über den Modul-Hook). await PredefinedMenuItem.new({ item: "Separator" }), + await MenuItem.new({ + text: t("menu.view.image3d"), + action: () => openImageExportDialog(), + }), await MenuItem.new({ text: t("menu.view.rendering"), action: () => openRenderDialog(), diff --git a/src/plan/presentationSheet.test.ts b/src/plan/presentationSheet.test.ts index ede8d89d..679de38e 100644 --- a/src/plan/presentationSheet.test.ts +++ b/src/plan/presentationSheet.test.ts @@ -2,7 +2,8 @@ import { beforeEach, describe, expect, it } from "vitest"; import { buildComplexSampleProject } from "../model/sampleProjectComplex"; import { getState } from "../state/appStore"; import { sheetSizeMm } from "../model/layoutModel"; -import { PRESENTATION_TEMPLATE_ID, presentationDefaults, presentationSheetOps } from "./presentationSheet"; +import { posterMetrics } from "../model/posterTemplates"; +import { PRESENTATION_TEMPLATE_ID, levelHasContent, presentationDefaults, presentationSheetOps } from "./presentationSheet"; import type { Project } from "../model/types"; const LABELS = { sheetName: "Präsentationsplan", masterName: "Planrahmen", north: "N", northGroup: "Nordpfeil", scaleBarGroup: "Massstabsbalken" }; @@ -23,7 +24,7 @@ describe("[66] Präsentationsplan", () => { it("Vorschlag: alle Geschosse, Ansichten, ein Schnitt, A1 quer (Master)", () => { const d = presentationDefaults(project); expect(d.floors.length).toBeGreaterThanOrEqual(4); - expect(d.elevations).toBe(true); + expect(d.elevationIds.length).toBeGreaterThan(0); expect(d.sectionId).not.toBeNull(); expect([d.paper, d.orientation]).toEqual(["a1", "landscape"]); expect(d.sketch).toBe(false); @@ -83,7 +84,7 @@ describe("[66] Präsentationsplan", () => { it("gewählte Geschosse, ohne Ansichten/Schnitt, Skizze an, A3: kleinerer Massstab", () => { const floors = project.drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId).slice(0, 2).map((l) => l.id); - const res = presentationSheetOps(project, { floors, elevations: false, sectionId: null, paper: "a3", orientation: "landscape", sketch: true }, LABELS, "t2")!; + const res = presentationSheetOps(project, { floors, elevationIds: [], scale: null, sectionId: null, paper: "a3", orientation: "landscape", sketch: true }, LABELS, "t2")!; expect(res.plan.items.map((i) => i.levelId)).toEqual(floors); expect(res.plan.scale).toBeGreaterThanOrEqual(100); st().applyChange(res.ops); @@ -93,6 +94,40 @@ describe("[66] Präsentationsplan", () => { }); it("nichts gewählt ⇒ null, Projekt unverändert", () => { - expect(presentationSheetOps(project, { floors: [], elevations: false, sectionId: null, paper: "a1", orientation: "landscape", sketch: false }, LABELS, "t3")).toBeNull(); + expect(presentationSheetOps(project, { floors: [], elevationIds: [], scale: null, sectionId: null, paper: "a1", orientation: "landscape", sketch: false }, LABELS, "t3")).toBeNull(); }); + + it("[224] Vorschlag: leere Geschosse nicht vorgewählt, Vorgabe 1:200", () => { + const floor = project.drawingLevels.find((l) => l.kind === "floor" && !l.layoutId)!; + const withEmpty = { ...project, drawingLevels: [...project.drawingLevels, { ...floor, id: "lv-leer", name: "OG leer", baseElevation: 99 }] }; + const d = presentationDefaults(withEmpty); + expect(d.floors).not.toContain("lv-leer"); + expect(d.floors).toContain(floor.id); + expect(d.scale).toBe(200); + expect(levelHasContent(withEmpty, "lv-leer")).toBe(false); + expect(levelHasContent(withEmpty, floor.id)).toBe(true); + }); + + it("[224] fester Massstab und Massstab je Viewport landen in Ausschnitt und Viewport", () => { + const floors = project.drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId).slice(0, 2).map((l) => l.id); + const res = presentationSheetOps(project, { floors, elevationIds: [], scale: 200, scales: { [floors[1]]: 100 }, sectionId: null, paper: "a1", orientation: "landscape", sketch: false }, LABELS, "t4")!; + expect(res.plan.scale).toBe(200); + expect(res.plan.items.map((i) => i.scale)).toEqual([200, 100]); + st().applyChange(res.ops); + const lay = st().project.layouts!.find((l) => l.id === res.layoutId)!; + expect(lay.viewports.map((v) => v.scaleDenominator)).toEqual([200, 100]); + expect(st().project.viewSnapshots!.filter((v) => v.id.startsWith("vs-pres-t4")).map((v) => v.scaleDenominator)).toEqual([200, 100]); + }); + + it("[224] Plakat-Vorlage als Ziel: Master der Vorlage, Viewports unter der Kopfzeile", () => { + const floors = project.drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId).slice(0, 2).map((l) => l.id); + const res = presentationSheetOps(project, { floors, elevationIds: [], scale: 200, sectionId: null, paper: "a4", orientation: "portrait", sketch: false, poster: "poster-a1-landscape" }, LABELS, "t5")!; + st().applyChange(res.ops); + const p = st().project; + const lay = p.layouts!.find((l) => l.id === res.layoutId)!; + const master = p.masterLayouts!.find((m) => m.id === lay.masterId)!; + expect([master.template, lay.paper, lay.orientation]).toEqual(["poster-a1-landscape", "a1", "landscape"]); + const top = posterMetrics(841, 594).contentTopMm; + for (const v of lay.viewports) expect(v.yMm).toBeGreaterThanOrEqual(top - 1e-6); + }, 60_000); }); diff --git a/src/plan/presentationSheet.ts b/src/plan/presentationSheet.ts index 012e59ac..127f38da 100644 --- a/src/plan/presentationSheet.ts +++ b/src/plan/presentationSheet.ts @@ -25,6 +25,7 @@ import { documentFor } from "../core/document"; import { addedItems, addItems, patchItem } from "../core/opsBuild"; import { standardsMergeOps } from "../model/standards"; import { createLayout, createMasterLayout, createSheetLevel, sheetMmToModel, sheetSizeMm } from "../model/layoutModel"; +import { createPosterMaster, findPosterMaster, posterMetrics, posterTemplate } from "../model/posterTemplates"; /** Id der Standard-Ansichtsvorlage „Präsentation" (`standards.rs`). */ export const PRESENTATION_TEMPLATE_ID = "std-vt-praesentation"; @@ -34,18 +35,31 @@ const FRAME_PAD_MM = 4; export interface PresentationOptions { /** Geschosse (Ebenen der Art `floor`) in Blattreihenfolge. */ floors: string[]; - /** Alle Ansichten (Ebenen der Art `elevation`) aufnehmen. */ - elevations: boolean; + /** Gewählte Ansichten (Ebenen der Art `elevation`) in Blattreihenfolge. */ + elevationIds: string[]; /** Ein Schnitt (Ebene der Art `section`) oder keiner. */ sectionId: string | null; paper: LayoutPaperFormat; orientation: LayoutOrientation; /** Skizzenstil ([67]) für die gezeigten Ebenen. */ sketch: boolean; + /** [224] Gemeinsamer Massstab (1:N); `null` = der grösste, der aufs Blatt passt. Vorgabe 1:200 (Wettbewerb). */ + scale: number | null; + /** [224] Massstab je Ebene (übersteuert `scale`). */ + scales?: Record; + /** [224] Plakat-Vorlage ([208], Schlüssel in `POSTER_TEMPLATES`) als Ziel; fehlt sie, gilt `paper`/`orientation`. */ + poster?: string; } +/** Massstäbe zur Wahl im Dialog (wie `SCALES` im Kern). */ +export const PRESENTATION_SCALES = [50, 100, 200, 500, 1000] as const; +/** Vorgabe-Massstab für den Wettbewerb (WBW 1:200, Vorprojekt 1:100). */ +export const PRESENTATION_DEFAULT_SCALE = 200; + export interface PresentationItem { levelId: string; + /** Massstab dieses Viewports (gemeinsam oder je Ebene gewählt). */ + scale: number; group: number; xMm: number; yMm: number; @@ -73,7 +87,16 @@ export interface PresentationLabels { const isFloor = (l: DrawingLevel) => l.kind === "floor" && !l.layoutId; -/** Vorschlag für den Dialog: alle Geschosse, Ansichten, erster Schnitt; Blatt des meistgenutzten Masters, sonst A1 quer. */ +/** [224] Hat die Ebene Bauteile oder Zeichnungen? Leere Geschosse (z. B. ein OG ohne Bauteile) werden nicht vorgewählt. */ +export function levelHasContent(project: Project, levelId: string): boolean { + for (const [key, v] of Object.entries(project as unknown as Record)) { + if (key === "drawingLevels" || !Array.isArray(v)) continue; + if (v.some((it) => typeof it === "object" && it !== null && (it as { levelId?: string }).levelId === levelId)) return true; + } + return false; +} + +/** Vorschlag für den Dialog: Geschosse mit Inhalt, alle Ansichten, erster Schnitt, 1:200; Blatt des meistgenutzten Masters, sonst A1 quer. */ export function presentationDefaults(project: Project): PresentationOptions { const levels = project.drawingLevels; const masters = project.masterLayouts ?? []; @@ -82,15 +105,22 @@ export function presentationDefaults(project: Project): PresentationOptions { const master = [...masters].sort((a, b) => (uses.get(b.id) ?? 0) - (uses.get(a.id) ?? 0))[0]; const usable = master && !master.customWidthMm; return { - floors: levels.filter(isFloor).map((l) => l.id), - elevations: levels.some((l) => l.kind === "elevation"), + floors: levels.filter((l) => isFloor(l) && levelHasContent(project, l.id)).map((l) => l.id), + elevationIds: levels.filter((l) => l.kind === "elevation").map((l) => l.id), sectionId: levels.find((l) => l.kind === "section")?.id ?? null, paper: usable ? master.paper : "a1", orientation: usable ? master.orientation : "landscape", sketch: false, + scale: PRESENTATION_DEFAULT_SCALE, }; } +/** Blattgrösse und Master-Papier der Wahl: Plakat-Vorlage, sonst `paper`/`orientation`. */ +function targetSheet(o: PresentationOptions): { paper: LayoutPaperFormat; orientation: LayoutOrientation } { + const tpl = o.poster ? posterTemplate(o.poster) : undefined; + return tpl ? { paper: tpl.paper, orientation: tpl.orientation } : { paper: o.paper, orientation: o.orientation }; +} + /** Die Vorlage „Präsentation" des Projekts bzw. aus den Standards (dann muss sie mit angelegt werden). */ export function presentationTemplate(project: Project): { template: ViewTemplate; isNew: boolean } { const own = (project.viewTemplates ?? []).find((t) => t.id === PRESENTATION_TEMPLATE_ID); @@ -146,22 +176,27 @@ function chosenLevels(project: Project, o: PresentationOptions): { id: string; g const byId = new Map(project.drawingLevels.map((l) => [l.id, l])); const out: { id: string; group: number }[] = []; for (const id of o.floors) if (byId.get(id) && isFloor(byId.get(id)!)) out.push({ id, group: 0 }); - if (o.elevations) for (const l of project.drawingLevels) if (l.kind === "elevation") out.push({ id: l.id, group: 1 }); + for (const id of o.elevationIds) if (byId.get(id)?.kind === "elevation") out.push({ id, group: 1 }); if (o.sectionId && byId.get(o.sectionId)?.kind === "section") out.push({ id: o.sectionId, group: 2 }); return out; } /** Master des Blatts: einer mit gleichem Format und gleicher Ausrichtung, sonst ein neuer. */ function masterFor(project: Project, o: PresentationOptions): MasterLayout | undefined { + const tpl = o.poster ? posterTemplate(o.poster) : undefined; + if (tpl) return findPosterMaster(project, tpl.key); return (project.masterLayouts ?? []).find( - (m) => m.paper === o.paper && m.orientation === o.orientation && m.customWidthMm === undefined, + (m) => m.paper === o.paper && m.orientation === o.orientation && m.customWidthMm === undefined && !m.template, ); } /** Massstab und Rahmen aus dem Kern (ohne das Projekt zu ändern). */ export function planPresentationSheet(project: Project, o: PresentationOptions): PresentationPlan { const { template } = presentationTemplate(project); - const size = sheetSizeMm(o.paper, o.orientation); + const { paper, orientation } = targetSheet(o); + const size = sheetSizeMm(paper, orientation); + // Plakat: Kopfzeile und Ränder der Vorlage, kein Schriftfeld des Masters. + const poster = o.poster && posterTemplate(o.poster) ? posterMetrics(size.w, size.h) : null; const levels = chosenLevels(project, o); const vis = presentationVisibility(project, template); const text = JSON.stringify({ @@ -171,8 +206,11 @@ export function planPresentationSheet(project: Project, o: PresentationOptions): detail: (template.detail ?? "mittel") satisfies DetailLevel, sheetW: size.w, sheetH: size.h, - titleBlock: true, + titleBlock: !poster, shadows: template.shadows ?? false, + ...(o.scale ? { scale: o.scale } : {}), + scales: o.scales ?? {}, + ...(poster ? { marginMm: poster.marginMm, topMm: poster.contentTopMm } : {}), }); return documentFor(project).query("presentationSheet", [], text); } @@ -256,14 +294,19 @@ export function presentationSheetOps( const { template, isNew } = presentationTemplate(project); const ops: CoreOp[] = []; if (isNew) ops.push(...addItems("viewTemplates", [template])); + const sheet = targetSheet(o); + const tpl = o.poster ? posterTemplate(o.poster) : undefined; let master = masterFor(project, o); - if (!master) { + if (!master && tpl) { + master = createPosterMaster(`mas-${tpl.key}`, tpl); + ops.push(...addItems("masterLayouts", [master])); + } else if (!master) { const first = (project.masterLayouts ?? [])[0]; - master = { ...createMasterLayout(`mas-pres-${stamp}`, labels.masterName, o.paper, o.orientation), titleBlock: { ...(first?.titleBlock ?? {}) } }; + master = { ...createMasterLayout(`mas-pres-${stamp}`, labels.masterName, sheet.paper, sheet.orientation), titleBlock: { ...(first?.titleBlock ?? {}) } }; ops.push(...addItems("masterLayouts", [master])); } const layoutId = `lay-pres-${stamp}`; - const layout: Layout = { ...createLayout(layoutId, labels.sheetName, o.paper, o.orientation), masterId: master.id }; + const layout: Layout = { ...createLayout(layoutId, labels.sheetName, sheet.paper, sheet.orientation), masterId: master.id }; const sheetLevel = createSheetLevel(`sheet-${layoutId}`, layout); const vis = presentationVisibility(project, template); const cat = annotationCategory(project); @@ -283,7 +326,7 @@ export function presentationSheetOps( name: `${level.name} · ${template.name}`, viewType: "grundriss", view3d: "top", - scaleDenominator: plan.scale, + scaleDenominator: it.scale, detail: template.detail ?? "mittel", activeLevelId: level.id, layerVisibility: vis, @@ -292,9 +335,9 @@ export function presentationSheetOps( templateId: template.id, templateLinked: true, } as ViewSnapshot); - vps.push({ id: `vp-pres-${stamp}-${i}`, snapshotId: snapId, xMm: it.xMm, yMm: it.yMm, widthMm: it.widthMm, heightMm: it.heightMm, scaleDenominator: plan.scale }); + vps.push({ id: `vp-pres-${stamp}-${i}`, snapshotId: snapId, xMm: it.xMm, yMm: it.yMm, widthMm: it.widthMm, heightMm: it.heightMm, scaleDenominator: it.scale }); drawings.push( - sheetText(`d-pres-${stamp}-t${i}`, sheetLevel.id, cat, it.xMm + FRAME_PAD_MM, it.yMm + it.heightMm + 6, `${level.name} 1:${plan.scale}`, 4, true), + sheetText(`d-pres-${stamp}-t${i}`, sheetLevel.id, cat, it.xMm + FRAME_PAD_MM, it.yMm + it.heightMm + 6, tpl ? level.name : `${level.name} 1:${it.scale}`, 4, true), ); }); // Nordpfeil rechts neben dem Titel des ersten Grundrisses. @@ -306,7 +349,7 @@ export function presentationSheetOps( drawings.push(...north); group(`grp-pres-${stamp}-n`, labels.northGroup, north); // Massstabsbalken links vom Nordpfeil, sofern er den Titel nicht berührt (Breite grob 0.65 × Schrifthöhe je Zeichen). - const bar = scaleBar(stamp, sheetLevel.id, cat, cx - 3.6 - 10, cy - 1, plan.scale); + const bar = scaleBar(stamp, sheetLevel.id, cat, cx - 3.6 - 10, cy - 1, firstFloor.scale); const title = byId.get(firstFloor.levelId)!.name; const titleEnd = firstFloor.xMm + FRAME_PAD_MM + (title.length + 8) * 4 * 0.65; const barLeft = Math.min(...bar.flatMap((d) => (d.geom.shape === "polyline" ? d.geom.pts.map((p) => p.x * 1000) : []))); diff --git a/src/state/imageExportDialogHook.ts b/src/state/imageExportDialogHook.ts new file mode 100644 index 00000000..f9434b98 --- /dev/null +++ b/src/state/imageExportDialogHook.ts @@ -0,0 +1,14 @@ +// [223] Modul-Hook: App registriert den Öffner des Dialogs „3D-Bild exportieren …"; Befehl `bild3d` und die Menüs +// rufen ihn auf, ohne an React/App gekoppelt zu sein (Muster `renderDialogHook`). + +let opener: (() => void) | null = null; + +/** App registriert hier den Öffner (oder hebt ihn beim Unmount auf). */ +export function setImageExportDialogOpener(fn: (() => void) | null): void { + opener = fn; +} + +/** Öffnet den Dialog, falls App ihn registriert hat. */ +export function openImageExportDialog(): void { + opener?.(); +} diff --git a/src/ui/AppDialogs.tsx b/src/ui/AppDialogs.tsx index 97197a1d..04245b21 100644 --- a/src/ui/AppDialogs.tsx +++ b/src/ui/AppDialogs.tsx @@ -29,6 +29,7 @@ import { ImportDialog } from "./ImportDialog"; import { LockConflictDialog } from "./LockConflictDialog"; import { PresentationDialogHost } from "./PresentationDialog"; import { RenderDialogHost } from "./RenderDialog"; +import { ImageExportDialogHost } from "./ImageExportDialog"; import { PromptDialog } from "./PromptDialog"; import { RecoverAutosaveDialog } from "./RecoverAutosaveDialog"; import { ResourceManager, type ResourceManagerHandlers } from "./ResourceManager"; @@ -160,6 +161,8 @@ export function AppDialogs(props: { {/* [211] Rendering mit Blender/Cycles (Befehl `rendering`, Menü Ansicht) */} + {/* [223] 3D-Bild exportieren (Befehl `bild3d`, Menü Ansicht) */} + {importState && ( , aspect: number): { width: number; height: number } { + switch (id) { + case "view": + return aspect >= 1 ? { width: 2000, height: Math.round(2000 / aspect) } : { width: Math.round(2000 * aspect), height: 2000 }; + case "hd": + return { width: 1920, height: 1080 }; + case "uhd": + return { width: 3840, height: 2160 }; + default: + return paperPixels(id, "landscape", 300); + } +} + +type Phase = "setup" | "working" | "done" | "error"; + +export const ImageExportDialogHost = memo(function ImageExportDialogHost() { + const [open, setOpen] = useState(false); + const [size, setSize] = useState("uhd"); + const [dims, setDims] = useState({ width: 3840, height: 2160 }); + const [transparent, setTransparent] = useState(false); + const [cameraKey, setCameraKey] = useState("live"); + const [phase, setPhase] = useState("setup"); + const [message, setMessage] = useState(""); + const [result, setResult] = useState<{ png: Uint8Array; width: number; height: number; transparent: boolean } | null>(null); + const [imageUrl, setImageUrl] = useState(null); + const [layoutTarget, setLayoutTarget] = useState(""); + const [aspect, setAspect] = useState(16 / 9); + + useEffect(() => { + setImageExportDialogOpener(() => { + const st = getState(); + const a = getCamera()?.aspect; + const asp = a && Number.isFinite(a) && a > 0 ? a : 16 / 9; + setAspect(asp); + setCameraKey("live"); + setPhase("setup"); + setMessage(""); + setResult(null); + setLayoutTarget(defaultTargetLayout(st.project, st.activeLevelId)?.id ?? ""); + setOpen(true); + }); + return () => setImageExportDialogOpener(null); + }, []); + + useEffect(() => { + if (!result) { + setImageUrl(null); + return; + } + const url = URL.createObjectURL(new Blob([result.png as BlobPart], { type: "image/png" })); + setImageUrl(url); + return () => URL.revokeObjectURL(url); + }, [result]); + + const busy = phase === "working"; + const close = useCallback(() => { + setOpen(false); + setResult(null); + }, []); + + useEffect(() => { + if (!open) return; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape" && !busy) close(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [open, busy, close]); + + const cameras = useMemo(() => (open ? (getState().project.cameras ?? []) : []), [open]); + if (!open) return null; + + const pickSize = (id: SizeId) => { + setSize(id); + if (id !== "custom") setDims(presetSize(id, aspect)); + }; + const effective = clampImageSize(dims.width, dims.height); + const validDims = Number.isFinite(dims.width) && Number.isFinite(dims.height) && dims.width >= 16 && dims.height >= 16; + const canStart = validDims && !busy; + const layouts = getState().project.layouts ?? []; + + const start = async () => { + if (!canStart) return; + const st = getState(); + let camera: ViewCamera | undefined; + if (cameraKey !== "live") { + const cam = (st.project.cameras ?? []).find((c) => c.id === cameraKey); + const view = cam ? cameraToView(st.project, cam, effective.width / effective.height) : null; + if (!view) { + setPhase("error"); + setMessage(t("image3d.cameraBad")); + return; + } + camera = view; + } + setPhase("working"); + setMessage(""); + // Dem Browser einen Frame lassen, damit „Arbeite …" erscheint, bevor das Zeichnen den Hauptthread belegt. + await new Promise((r) => requestAnimationFrame(() => r(null))); + const img = await captureImage({ width: dims.width, height: dims.height, transparent, ...(camera ? { camera } : {}) }); + if (!img) { + setPhase("error"); + setMessage(viewportAvailable() ? t("image3d.empty") : t("image3d.noViewport")); + return; + } + setResult(img); + setPhase("done"); + if (transparent && !img.transparent) setMessage(t("image3d.noTransparency")); + }; + + const fileName = () => imageFileName(getState().project.name, result?.width ?? 0, result?.height ?? 0); + const save = async () => { + if (!result) return; + if (await saveBinaryFile(result.png, fileName(), "image/png")) getState().notify(t("image3d.saved"), "info"); + }; + const placeInLayout = () => { + if (!result) return; + const st = getState(); + const layout = (st.project.layouts ?? []).find((l) => l.id === layoutTarget); + if (layout && placeImageOnLayout(layout.id, fileName(), result.png)) st.notify(t("render.toLayout.done", { name: layout.name }), "info"); + else st.notify(t("render.toLayout.none"), "warning"); + }; + + return ( +
!busy && close()}> +
e.stopPropagation()}> +
+ {t("image3d.title")} + +
+
+ {phase !== "done" && ( + <> +

{t("image3d.intro")}

+
+
{t("render.camera.title")}
+ +
+
+
{t("render.size")}
+ +
+ + +
+ {validDims && effective.clamped && ( +
+ {t("image3d.clamped", { max: IMAGE_MAX_EDGE, width: effective.width, height: effective.height })} +
+ )} +
+
+ +
+ + )} + + {busy && ( +
+ +
{t("image3d.working", { width: effective.width, height: effective.height })}
+
+ )} + + {phase === "done" && result && imageUrl && ( +
+
{t("image3d.done", { width: result.width, height: result.height })}
+ {t("image3d.title")} + {layouts.length > 0 && ( + + )} +
+ )} + + {message && ( +

+ {message} +

+ )} +
+
+ + {phase === "done" ? ( + <> + + + + + ) : ( + + )} +
+
+
+ ); +}); diff --git a/src/ui/PresentationDialog.tsx b/src/ui/PresentationDialog.tsx index 4e929d46..9b8e47a4 100644 --- a/src/ui/PresentationDialog.tsx +++ b/src/ui/PresentationDialog.tsx @@ -5,9 +5,10 @@ import { memo, useCallback, useEffect, useState } from "react"; import { t } from "../i18n"; -import { presentationDefaults, type PresentationOptions } from "../core"; +import { PRESENTATION_SCALES, levelHasContent, presentationDefaults, type PresentationOptions } from "../core"; import type { LayoutOrientation, LayoutPaperFormat } from "../model/types"; import { PAPER_FORMAT_GROUPS } from "../model/layoutModel"; +import { POSTER_TEMPLATES, posterTemplateLabel } from "../model/posterTemplates"; import { getState, useStore } from "../state/appStore"; import { setPresentationDialogOpener } from "../state/presentationSheetHook"; import { createPresentationSheet } from "../state/presentationSheet"; @@ -20,6 +21,7 @@ export const PresentationDialogHost = memo(function PresentationDialogHost({ }) { const [opts, setOpts] = useState(null); const drawingLevels = useStore((s) => s.project.drawingLevels); + const project = useStore((s) => s.project); useEffect(() => { setPresentationDialogOpener(() => setOpts(presentationDefaults(getState().project))); @@ -49,12 +51,31 @@ export const PresentationDialogHost = memo(function PresentationDialogHost({ if (!opts) return null; const floors = drawingLevels.filter((l) => l.kind === "floor" && !l.layoutId); const sections = drawingLevels.filter((l) => l.kind === "section"); - const hasElevations = drawingLevels.some((l) => l.kind === "elevation"); + const elevations = drawingLevels.filter((l) => l.kind === "elevation"); const set = (patch: Partial) => setOpts({ ...opts, ...patch }); const toggleFloor = (id: string, on: boolean) => // Blattreihenfolge = Reihenfolge der Geschosse im Projekt. set({ floors: floors.map((f) => f.id).filter((f) => (f === id ? on : opts.floors.includes(f))) }); - const empty = opts.floors.length === 0 && !(opts.elevations && hasElevations) && !opts.sectionId; + const toggleElevation = (id: string, on: boolean) => + set({ elevationIds: elevations.map((e) => e.id).filter((e) => (e === id ? on : opts.elevationIds.includes(e))) }); + const empty = opts.floors.length === 0 && opts.elevationIds.length === 0 && !opts.sectionId; + // [224] Massstab je Viewport: "" = gemeinsamer Massstab. + const scaleOf = (id: string) => String(opts.scales?.[id] ?? ""); + const setScaleOf = (id: string, v: string) => { + const next = { ...(opts.scales ?? {}) }; + if (v) next[id] = Number(v); + else delete next[id]; + set({ scales: next }); + }; + const scaleSelect = (id: string) => ( + + ); + const poster = !!opts.poster; return (
@@ -83,20 +104,26 @@ export const PresentationDialogHost = memo(function PresentationDialogHost({ onChange={(e) => toggleFloor(f.id, e.target.checked)} /> {f.name} + {!levelHasContent(project, f.id) && {t("presentation.floorEmpty")}} + {scaleSelect(f.id)} ))}
- +
{t("presentation.elevations")}
+ {elevations.length === 0 &&
{t("presentation.noElevations")}
} + {elevations.map((e) => ( + + ))}
{t("presentation.section")}
@@ -113,14 +140,42 @@ export const PresentationDialogHost = memo(function PresentationDialogHost({ ))} + {opts.sectionId &&
{scaleSelect(opts.sectionId)}
}
{t("presentation.sheet")}
-
+
+ + +
+