[266] Vektor-Axonometrie / 3D-Dokument: Linienzeichnung mit verdeckten Kanten aus beliebiger Kamera, ohne GPU
Kern `plan/axo.rs`: die Körper der Schnitt-Projektion (`section::model_view_faces`, aus `projection_edges` herausgelöst, Schnitt unverändert) in Ansichtskoordinaten, exakte Sichtbarkeit `hlr.rs`, Silhouette (Kante gegen den Hintergrund) 0.35 mm, Kanten 0.18 mm, verdeckte gestrichelt auf Wunsch, Flächen nach Lage hellgrau (`hlr_fill.rs` mit Tiefenraster als Vorauswahl). Parallel (Isometrie, Kamera, Militär 45/45 und 30/60 als schiefe Projektion) und Perspektive (Nahebene/Bildrahmen, projektiv). Abfrage `axoPlan` (camera / cameraId / view), Budget, Klassen der Bauteile ([180]). Modell `ViewSnapshot.doc3d`; 3D-Ausschnitte zeigen auf Blatt, PDF und im Kern-Viewport das 3D-Dokument; Ansicht → „3D-Dokument erstellen“ (Kamera der 3D-Ansicht → Ausschnitt + Blatt A3); Präsentationsplan setzt die Axonometrie Südost in den Bild-Rahmen, Platzhalter nur noch, wenn auch sie scheitert; CLI `axo`. Musterhaus komplex: 13 900 Flächen, 0.45 s nativ, 0.7–1.1 s CLI (WASM, Linux-Container). Geprüft: cargo test --release (1781 + neue), robustness_web, tsc, vitest gesamt (ein Zeitüberschreitungs- Fehler nur unter Last, einzeln grün), e2e presentationSheet/release10 2×, Golden neu muster-axo-southeast (bestehende unverändert). Nicht geprüft: Tauri/Mac, Übereinstimmung mit dem 3D-Fenster (Achsen).
This commit is contained in:
40 files changed
+1675
-51
No files matched your search
@@ -67,6 +67,7 @@ Herkunft, kein Wegweiser.
|
||||
| `elevation/silhouette.rs` | Silhouette, Kanten mit exakter Verdeckung, Geländekante |
|
||||
| `elevation/patterns.rs` | Oberflächenmuster auf Ansichtsflächen |
|
||||
| `elevation/tests.rs` | Tests der Ansicht |
|
||||
| `axo.rs` | [266] 3D-Dokument: Vektor-Axonometrie/-Perspektive mit verdeckten Kanten (Flächen aus `section::model_view_faces`, `hlr.rs`, Tönung über `hlr_fill.rs`), Vorgaben, Kamera, Abfrage `axo_plan_buf()`; Tests `axo_tests.rs` |
|
||||
| `elevation_geom.rs` | Geometrie der Ansicht: Verdeckung, Schlagschatten, Eck-Verlängerung, Öffnungen |
|
||||
| `grid_view.rs` | Achsraster in Schnitt und Ansicht |
|
||||
| `underlay.rs` | Grundriss ausgerichtet unter Schnitt und Ansicht (Ausrichtung der Pausfolie „Grundriss hinter Schnitt“) |
|
||||
|
||||
@@ -0,0 +1,729 @@
|
||||
//! [266] 3D-Dokument: Vektor-Axonometrie bzw. -Perspektive mit verdeckten Kanten aus dem Kern — eine Linienzeichnung
|
||||
//! des Modells aus einer beliebigen Kamera (wie das „3D-Dokument“ in Archicad), ohne GPU (CLI, Linux, Plakat, PDF).
|
||||
//!
|
||||
//! Rechenweg: dieselben Körper wie die Projektion hinter dem Schnitt (`section::model_view_faces`: Wände samt
|
||||
//! Gehrung und Löchern, Platten, Treppen, Dächer, freie Körper, auf Wunsch importierte Netze) werden in
|
||||
//! Ansichtskoordinaten `(u, v, Tiefe)` gebracht und mit der exakten Sichtbarkeit (`hlr.rs`, [G4]: Kanten gegen Flächen,
|
||||
//! Durchdringungslinien, Rasterteilung) verdeckt; die sichtbaren Teilflächen (`hlr_fill.rs`) werden nach ihrer Lage
|
||||
//! zum Licht hell grau getönt. Kanten, die an den Hintergrund grenzen, sind Silhouette (stärker).
|
||||
//!
|
||||
//! Projektionen ([`Projection`]):
|
||||
//! - **Parallel** (`u, v, Tiefe` = lineare Abbildung): Isometrie und Kamera-Parallelprojektion (orthonormal) sowie
|
||||
//! Militärprojektion 45°/45° und 30°/60° (schiefe Parallelprojektion: Grundriss unverzerrt gedreht, Senkrechte
|
||||
//! unverkürzt). Normalen gehen über die inverse Transponierte, damit „zugewandt“ auch schief stimmt.
|
||||
//! - **Perspektive**: Kamera-Koordinaten, an der Nahebene und am Bildrahmen zugeschnitten, dann projektiv nach
|
||||
//! `(x·z₀/z, y·z₀/z, z₀ − z₀²/z)` — eine projektive Abbildung erhält Ebenen, also bleibt die Sichtbarkeit exakt;
|
||||
//! `z₀` = Abstand zur Modellmitte, dort ist die Zeichnung massstäblich.
|
||||
//!
|
||||
//! Vorgaben (Blick von …): `southeast`, `southwest`, `northeast`, `northwest` (Norden = +y), dazu die
|
||||
//! Blickwinkel der 3D-Ansicht (`iso` = von vorne-oben-rechts, `isoFrontLeft`, `isoBackRight`, `isoBackLeft`, `front`,
|
||||
//! `back`, `side`, `left`, `top`; „vorne“ = +y wie `render3d::preset_camera` mit Welt-z = Modell-y).
|
||||
//!
|
||||
//! Klassen ([180]): jede Linie und Fläche gehört zu einem Bauteil und verschwindet mit dessen Klasse (Bauteile
|
||||
//! ausgeblendeter Klassen nehmen an der Verdeckung nicht teil).
|
||||
|
||||
use super::prim::Primitive;
|
||||
use super::section::{line, polygon, v2, Kind, OwnerRef, Visibility};
|
||||
use super::style::no_hatch;
|
||||
use crate::hlr;
|
||||
use crate::model::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
type V3 = [f64; 3];
|
||||
|
||||
/// Sichtbare Kanten.
|
||||
const EDGE_MM: f64 = 0.18;
|
||||
const EDGE_INK: &str = "#2b3039";
|
||||
/// Silhouette (Kante gegen den Hintergrund).
|
||||
const OUTLINE_MM: f64 = 0.35;
|
||||
const OUTLINE_INK: &str = "#1f242c";
|
||||
const HIDDEN_MM: f64 = 0.13;
|
||||
const HIDDEN_INK: &str = "#8a929c";
|
||||
/// Höchstens so viele Flächen rechnen; darüber entfallen zuerst die Kontext-Netze, dann gibt es kein Bild.
|
||||
pub const FACE_BUDGET: usize = 400_000;
|
||||
/// Höchstens so viele zugewandte Flächen werden exakt getönt; darüber bleibt es bei den Linien.
|
||||
pub const FILL_BUDGET: usize = 30_000;
|
||||
|
||||
fn dot(a: V3, b: V3) -> f64 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
fn cross(a: V3, b: V3) -> V3 {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
fn norm(a: V3) -> f64 {
|
||||
dot(a, a).sqrt()
|
||||
}
|
||||
fn unit(a: V3) -> Option<V3> {
|
||||
let l = norm(a);
|
||||
(l > 1e-12 && l.is_finite()).then(|| [a[0] / l, a[1] / l, a[2] / l])
|
||||
}
|
||||
fn sub(a: V3, b: V3) -> V3 {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
fn finite3(a: V3) -> bool {
|
||||
a.iter().all(|v| v.is_finite())
|
||||
}
|
||||
|
||||
/// Abbildung Modell (x, y, z = Höhe) → Zeichnung.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Projection {
|
||||
/// `(u, v, Tiefe) = m · (p − o)`; Tiefe wächst vom Betrachter weg.
|
||||
Parallel { m: [V3; 3], o: V3 },
|
||||
/// Zentralprojektion: Auge, Basis rechts/oben/vorwärts, Bildebene `zref`, halbe Bildhöhe (Winkel als Tangens), Seitenverhältnis.
|
||||
Perspective { eye: V3, r: V3, u: V3, f: V3, zref: f64, tan_half: f64, aspect: f64 },
|
||||
}
|
||||
|
||||
/// Parallelprojektion einer Kamera (Blickrichtung, Up) mit Ursprung `o`.
|
||||
fn camera_basis(dir: V3, up: V3) -> Option<(V3, V3, V3)> {
|
||||
let f = unit(dir)?;
|
||||
let r = unit(cross(f, up)).or_else(|| unit(cross(f, [0.0, 1.0, 0.0])))?;
|
||||
let u = cross(r, f);
|
||||
Some((r, u, f))
|
||||
}
|
||||
|
||||
/// Vorgabe nach Name (`view`) und Projektionsart (`kind`: `iso`, `military` = 45°/45°, `military30` = 30°/60°).
|
||||
pub fn preset(view: &str, kind: &str) -> Option<Projection> {
|
||||
let s = std::f64::consts::FRAC_1_SQRT_2;
|
||||
// Horizontale Richtung zum Betrachter.
|
||||
let corner = match view {
|
||||
"southeast" | "isoBackRight" => Some([s, -s]),
|
||||
"southwest" | "isoBackLeft" => Some([-s, -s]),
|
||||
"northeast" | "iso" | "perspective" | "" => Some([s, s]),
|
||||
"northwest" | "isoFrontLeft" => Some([-s, s]),
|
||||
_ => None,
|
||||
};
|
||||
let Some(h) = corner else {
|
||||
// Senkrechte Ansichten und Draufsicht (Parallel, ohne Militär).
|
||||
let (dir, up): (V3, V3) = match view {
|
||||
"front" => ([0.0, -1.0, 0.0], [0.0, 0.0, 1.0]),
|
||||
"back" => ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0]),
|
||||
"side" => ([-1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
|
||||
"left" => ([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]),
|
||||
"top" => ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0]),
|
||||
_ => return None,
|
||||
};
|
||||
let (r, u, f) = camera_basis(dir, up)?;
|
||||
return Some(Projection::Parallel { m: [r, u, f], o: [0.0; 3] });
|
||||
};
|
||||
// Rechts (vom Betrachter aus) und vorwärts in der Ebene.
|
||||
let fwd = [-h[0], -h[1]];
|
||||
let right = [fwd[1], -fwd[0]];
|
||||
match kind {
|
||||
"military" | "military45" | "military30" => {
|
||||
let (mut r2, mut f2) = (right, fwd);
|
||||
if kind == "military30" {
|
||||
// 30°/60°: so drehen, dass die x-Fassaden (Süd/Nord) flach (30°) liegen.
|
||||
let rot = |a: [f64; 2], t: f64| [a[0] * t.cos() - a[1] * t.sin(), a[0] * t.sin() + a[1] * t.cos()];
|
||||
let t = 15f64.to_radians();
|
||||
let (ra, rb) = (rot(right, t), rot(right, -t));
|
||||
let k = if ra[0].abs() >= rb[0].abs() { t } else { -t };
|
||||
r2 = rot(right, k);
|
||||
f2 = rot(fwd, k);
|
||||
}
|
||||
let row_u = [r2[0], r2[1], 0.0];
|
||||
let row_v = [f2[0], f2[1], 1.0];
|
||||
let c = cross(row_u, row_v);
|
||||
let d = unit([-c[0], -c[1], -c[2]])?;
|
||||
Some(Projection::Parallel { m: [row_u, row_v, d], o: [0.0; 3] })
|
||||
}
|
||||
_ => {
|
||||
// Isometrie: Höhenwinkel asin(1/√3) ≈ 35.26°.
|
||||
let e = [h[0], h[1], s];
|
||||
let (r, u, f) = camera_basis([-e[0], -e[1], -e[2]], [0.0, 0.0, 1.0])?;
|
||||
Some(Projection::Parallel { m: [r, u, f], o: [0.0; 3] })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kamera in Modell-Koordinaten wie `ViewCamera` der 3D-Ansicht (`viewport/cameraBridge.ts`): `kind`
|
||||
/// („perspective“/„orthogonal“), `position`, `direction`, `up`, `fovDeg`; `aspect` = Breite/Höhe des Bildrahmens.
|
||||
/// `center`: Modellmitte (Abstand der massstäblichen Bildebene der Perspektive).
|
||||
pub fn camera(kind: &str, position: V3, direction: V3, up: V3, fov_deg: f64, aspect: f64, center: V3) -> Option<Projection> {
|
||||
if !(finite3(position) && finite3(direction) && finite3(up)) {
|
||||
return None;
|
||||
}
|
||||
let (r, u, f) = camera_basis(direction, up)?;
|
||||
if kind != "perspective" {
|
||||
return Some(Projection::Parallel { m: [r, u, f], o: position });
|
||||
}
|
||||
let fov = if fov_deg.is_finite() && fov_deg > 0.0 { fov_deg.clamp(5.0, 150.0) } else { 50.0 };
|
||||
let aspect = if aspect.is_finite() && aspect > 0.0 { aspect.clamp(0.2, 5.0) } else { 1.5 };
|
||||
let zref = dot(sub(center, position), f);
|
||||
let zref = if zref.is_finite() && zref > 1.0 { zref } else { 10.0 };
|
||||
Some(Projection::Perspective { eye: position, r, u, f, zref, tan_half: (fov.to_radians() / 2.0).tan(), aspect })
|
||||
}
|
||||
|
||||
/// Kamera-Element des Projekts ([213]) wie `renderCameraOf` (`export/blenderRender.ts`): Standpunkt = Fussboden des
|
||||
/// Geschosses + Augenhöhe, Blick zum Ziel, Up aus der Senkrechten.
|
||||
pub fn project_camera(p: &Project, id: &str, aspect: f64, center: V3) -> Option<Projection> {
|
||||
let cam = p.cameras.as_deref()?.iter().find(|c| c.id == id)?;
|
||||
let base = p.drawing_levels.iter().find(|l| l.id == cam.floor_id).and_then(|l| l.base_elevation).filter(|b| b.is_finite()).unwrap_or(0.0);
|
||||
let eye = [cam.position.x, cam.position.y, base + if cam.eye_height.is_finite() { cam.eye_height } else { 1.6 }];
|
||||
let tgt = [cam.target.x, cam.target.y, cam.target_height];
|
||||
let d = unit(sub(tgt, eye))?;
|
||||
let up = if d[2].abs() > 0.9999 { [0.0, 1.0, 0.0] } else { [0.0, 0.0, 1.0] };
|
||||
let kind = if cam.projection == CameraProjection::Perspective { "perspective" } else { "orthogonal" };
|
||||
camera(kind, eye, d, up, cam.fov_deg, aspect, center)
|
||||
}
|
||||
|
||||
/// Inverse Transponierte (bis auf einen positiven Faktor) einer 3×3-Matrix aus Zeilen: Normalen der Parallelprojektion.
|
||||
fn cofactor(m: &[V3; 3]) -> Option<[V3; 3]> {
|
||||
let c = [cross(m[1], m[2]), cross(m[2], m[0]), cross(m[0], m[1])];
|
||||
let det = dot(m[0], c[0]);
|
||||
if !(det.abs() > 1e-12) {
|
||||
return None;
|
||||
}
|
||||
let s = det.signum();
|
||||
// Die Spalten von M⁻¹ sind c[j]/det, also die Zeilen von M⁻ᵀ: n'_j = (c[j] · n)/det; der Betrag zählt nicht.
|
||||
Some([[c[0][0] * s, c[0][1] * s, c[0][2] * s], [c[1][0] * s, c[1][1] * s, c[1][2] * s], [c[2][0] * s, c[2][1] * s, c[2][2] * s]])
|
||||
}
|
||||
|
||||
/// Welt (x, Höhe, y) → Modell (x, y, Höhe).
|
||||
fn model_of(w: V3) -> V3 {
|
||||
[w[0], w[2], w[1]]
|
||||
}
|
||||
|
||||
/// Sutherland-Hodgman an `g(p) ≥ 0`; `ne[i]`: Kante i → i+1 nie zeichnen (neue Kanten am Schnitt ebenso).
|
||||
fn clip_by(pts: &[V3], ne: &[bool], g: &dyn Fn(V3) -> f64) -> Option<(Vec<V3>, Vec<bool>)> {
|
||||
let n = pts.len();
|
||||
let vals: Vec<f64> = pts.iter().map(|&p| g(p)).collect();
|
||||
if vals.iter().all(|v| *v >= 0.0) {
|
||||
return Some((pts.to_vec(), ne.to_vec()));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut flags = Vec::new();
|
||||
for i in 0..n {
|
||||
let j = (i + 1) % n;
|
||||
let (p, q, gp, gq) = (pts[i], pts[j], vals[i], vals[j]);
|
||||
let e = ne.get(i).copied().unwrap_or(false);
|
||||
let (pin, qin) = (gp >= 0.0, gq >= 0.0);
|
||||
let x = || {
|
||||
let t = gp / (gp - gq);
|
||||
[p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t]
|
||||
};
|
||||
match (pin, qin) {
|
||||
(true, true) => {
|
||||
out.push(p);
|
||||
flags.push(e);
|
||||
}
|
||||
(true, false) => {
|
||||
out.push(p);
|
||||
flags.push(e);
|
||||
out.push(x());
|
||||
flags.push(true);
|
||||
}
|
||||
(false, true) => {
|
||||
out.push(x());
|
||||
flags.push(e);
|
||||
}
|
||||
(false, false) => {}
|
||||
}
|
||||
}
|
||||
(out.len() >= 3).then_some((out, flags))
|
||||
}
|
||||
|
||||
fn newell(pts: &[V3]) -> V3 {
|
||||
let n = pts.len();
|
||||
(0..n).fold([0.0; 3], |m, k| {
|
||||
let (a, b) = (pts[k], pts[(k + 1) % n]);
|
||||
[m[0] + (a[1] - b[1]) * (a[2] + b[2]), m[1] + (a[2] - b[2]) * (a[0] + b[0]), m[2] + (a[0] - b[0]) * (a[1] + b[1])]
|
||||
})
|
||||
}
|
||||
|
||||
/// Ergebnis der Rechnung (Zeichenebene, Meter; v nach oben).
|
||||
#[derive(Default, Debug)]
|
||||
pub struct AxoOut {
|
||||
/// Sichtbare Kanten: (a, b, Besitzer, Silhouette).
|
||||
pub edges: Vec<([f64; 2], [f64; 2], u32, bool)>,
|
||||
/// Verdeckte Kanten (nur mit `hidden`).
|
||||
pub hidden: Vec<([f64; 2], [f64; 2], u32)>,
|
||||
/// Getönte sichtbare Flächen: (Polygone mit Löchern, Grauwert 0–1, Besitzer).
|
||||
pub fills: Vec<(Vec<crate::flat::Polygon>, f64, u32)>,
|
||||
}
|
||||
|
||||
/// Optionen der Rechnung.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AxoOpts {
|
||||
pub hidden: bool,
|
||||
pub fills: bool,
|
||||
}
|
||||
|
||||
/// Flächen (Ansichtskoordinaten vor der Perspektive) samt Modell-Normale.
|
||||
struct Prepared {
|
||||
faces: Vec<hlr::Face>,
|
||||
model_n: Vec<V3>,
|
||||
}
|
||||
|
||||
/// Perspektive: zuschneiden (Nahebene, Bildrahmen) und projektiv abbilden; Normale aus der neuen Lage, zugewandt wie vorher.
|
||||
fn perspective_pass(faces: Vec<hlr::Face>, model_n: Vec<V3>, zref: f64, tan_half: f64, aspect: f64) -> Prepared {
|
||||
let near = (zref * 1e-3).max(0.05);
|
||||
let (tx, ty) = (tan_half * aspect, tan_half);
|
||||
let planes: [&dyn Fn(V3) -> f64; 5] = [&|p: V3| p[2] - near, &|p: V3| p[2] * tx - p[0], &|p: V3| p[2] * tx + p[0], &|p: V3| p[2] * ty - p[1], &|p: V3| p[2] * ty + p[1]];
|
||||
let mut out = Prepared { faces: Vec::with_capacity(faces.len()), model_n: Vec::with_capacity(faces.len()) };
|
||||
for (mut f, mn) in faces.into_iter().zip(model_n) {
|
||||
let facing = dot(f.normal, f.pts[0]) < 0.0;
|
||||
let mut cur = (f.pts.clone(), if f.no_edge.is_empty() { vec![false; f.pts.len()] } else { f.no_edge.clone() });
|
||||
let mut ok = true;
|
||||
for g in planes.iter() {
|
||||
match clip_by(&cur.0, &cur.1, *g) {
|
||||
Some(c) => cur = c,
|
||||
None => {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ok {
|
||||
continue;
|
||||
}
|
||||
let pts: Vec<V3> = cur.0.iter().map(|p| [p[0] * zref / p[2], p[1] * zref / p[2], zref - zref * zref / p[2]]).collect();
|
||||
if !pts.iter().all(|p| finite3(*p)) {
|
||||
continue;
|
||||
}
|
||||
let mut n = newell(&pts);
|
||||
let l = norm(n);
|
||||
n = if l > 1e-14 { [n[0] / l, n[1] / l, n[2] / l] } else { [0.0, 0.0, if facing { -1.0 } else { 1.0 }] };
|
||||
if (n[2] < 0.0) != facing {
|
||||
n = [-n[0], -n[1], -n[2]];
|
||||
}
|
||||
f.pts = pts;
|
||||
f.normal = n;
|
||||
f.no_edge = cur.1;
|
||||
out.faces.push(f);
|
||||
out.model_n.push(mn);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Flächen des Modells in der Projektion; `None`, wenn die Projektion entartet ist.
|
||||
fn prepare(p: &Project, proj: &Projection, vis: &Visibility, context: bool) -> Result<Option<(Prepared, Vec<OwnerRef>)>, String> {
|
||||
match *proj {
|
||||
Projection::Parallel { m, o } => {
|
||||
let Some(cof) = cofactor(&m) else { return Ok(None) };
|
||||
// Schiefe Projektion: Netz-Normalen (`mesh_view::hlr_faces`) setzen eine längentreue Abbildung voraus.
|
||||
let ortho = (0..3).all(|i| (0..3).all(|j| (dot(m[i], m[j]) - if i == j { 1.0 } else { 0.0 }).abs() < 1e-9));
|
||||
let view = |w: V3| {
|
||||
let q = sub(model_of(w), o);
|
||||
[dot(m[0], q), dot(m[1], q), dot(m[2], q)]
|
||||
};
|
||||
let view_n = |n: V3| {
|
||||
let q = model_of(n);
|
||||
[dot(cof[0], q), dot(cof[1], q), dot(cof[2], q)]
|
||||
};
|
||||
let (mut vf, refs) = super::section::model_view_faces(p, vis, &view, &view_n, context && ortho)?;
|
||||
if vf.faces.len() > FACE_BUDGET && context {
|
||||
(vf, _) = super::section::model_view_faces(p, vis, &view, &view_n, false)?;
|
||||
}
|
||||
// Modell-Normale = Mᵀ · Normale (die Normale ging über M⁻ᵀ).
|
||||
let model_n = vf.faces.iter().map(|f| unit([0, 1, 2].map(|k| m[0][k] * f.normal[0] + m[1][k] * f.normal[1] + m[2][k] * f.normal[2])).unwrap_or([0.0, 0.0, 1.0])).collect();
|
||||
Ok(Some((Prepared { faces: vf.faces, model_n }, refs)))
|
||||
}
|
||||
Projection::Perspective { eye, r, u, f, zref, tan_half, aspect } => {
|
||||
let view = |w: V3| {
|
||||
let q = sub(model_of(w), eye);
|
||||
[dot(r, q), dot(u, q), dot(f, q)]
|
||||
};
|
||||
let view_n = |n: V3| {
|
||||
let q = model_of(n);
|
||||
[dot(r, q), dot(u, q), dot(f, q)]
|
||||
};
|
||||
let (mut vf, refs) = super::section::model_view_faces(p, vis, &view, &view_n, context)?;
|
||||
if vf.faces.len() > FACE_BUDGET && context {
|
||||
(vf, _) = super::section::model_view_faces(p, vis, &view, &view_n, false)?;
|
||||
}
|
||||
let model_n: Vec<V3> = vf.faces.iter().map(|q| unit([0, 1, 2].map(|k| r[k] * q.normal[0] + u[k] * q.normal[1] + f[k] * q.normal[2])).unwrap_or([0.0, 0.0, 1.0])).collect();
|
||||
Ok(Some((perspective_pass(vf.faces, model_n, zref, tan_half, aspect), refs)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lichtrichtung (Modell): von links oben hinter dem Betrachter, je Projektion aus deren Achsen.
|
||||
fn light_of(proj: &Projection) -> V3 {
|
||||
let (r, u, f) = match *proj {
|
||||
Projection::Parallel { m, .. } => {
|
||||
let r = unit(m[0]).unwrap_or([1.0, 0.0, 0.0]);
|
||||
let f = unit(m[2]).unwrap_or([0.0, 0.0, -1.0]);
|
||||
(r, cross(r, f), f)
|
||||
}
|
||||
Projection::Perspective { r, u, f, .. } => (r, u, f),
|
||||
};
|
||||
// Licht kommt von links oben vorne: Richtung ZUM Licht.
|
||||
let l = [-0.55 * r[0] + 0.8 * u[0] - 0.45 * f[0], -0.55 * r[1] + 0.8 * u[1] - 0.45 * f[1], -0.55 * r[2] + 0.8 * u[2] - 0.45 * f[2]];
|
||||
let l = [l[0], l[1], l[2] + 0.6];
|
||||
unit(l).unwrap_or([0.0, 0.0, 1.0])
|
||||
}
|
||||
|
||||
/// Grauwert einer Fläche (0 = schwarz, 1 = weiss), gestuft (12 Stufen) für wenige Füllfarben.
|
||||
fn tone(n: V3, light: V3) -> f64 {
|
||||
let lam = dot(n, light).max(0.0);
|
||||
let g = 0.78 + 0.19 * lam;
|
||||
(g * 48.0).round() / 48.0
|
||||
}
|
||||
|
||||
/// Gitter über den Umrissen der zugewandten Flächen für den Hintergrund-Test der Silhouette.
|
||||
struct Cover {
|
||||
lo: [f64; 2],
|
||||
cell: [f64; 2],
|
||||
side: usize,
|
||||
grid: Vec<Vec<u32>>,
|
||||
polys: Vec<Vec<[f64; 2]>>,
|
||||
}
|
||||
|
||||
impl Cover {
|
||||
fn new(polys: Vec<Vec<[f64; 2]>>) -> Cover {
|
||||
let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
|
||||
for q in polys.iter().flatten() {
|
||||
lo = [lo[0].min(q[0]), lo[1].min(q[1])];
|
||||
hi = [hi[0].max(q[0]), hi[1].max(q[1])];
|
||||
}
|
||||
let side = ((polys.len() as f64).sqrt().ceil() as usize).clamp(1, 512);
|
||||
let cell = [((hi[0] - lo[0]) / side as f64).max(1e-9), ((hi[1] - lo[1]) / side as f64).max(1e-9)];
|
||||
let mut c = Cover { lo, cell, side, grid: vec![Vec::new(); side * side], polys: Vec::new() };
|
||||
for (i, pl) in polys.iter().enumerate() {
|
||||
let (mut a, mut b) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
|
||||
for q in pl {
|
||||
a = [a[0].min(q[0]), a[1].min(q[1])];
|
||||
b = [b[0].max(q[0]), b[1].max(q[1])];
|
||||
}
|
||||
let (x0, y0, x1, y1) = (c.at(a[0], 0), c.at(a[1], 1), c.at(b[0], 0), c.at(b[1], 1));
|
||||
for y in y0..=y1 {
|
||||
for x in x0..=x1 {
|
||||
c.grid[y * side + x].push(i as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
c.polys = polys;
|
||||
c
|
||||
}
|
||||
fn at(&self, v: f64, k: usize) -> usize {
|
||||
let i = ((v - self.lo[k]) / self.cell[k]).floor();
|
||||
if i.is_nan() { 0 } else { i.clamp(0.0, (self.side - 1) as f64) as usize }
|
||||
}
|
||||
fn covered(&self, p: [f64; 2]) -> bool {
|
||||
if !self.lo[0].is_finite() {
|
||||
return false;
|
||||
}
|
||||
let cell = &self.grid[self.at(p[1], 1) * self.side + self.at(p[0], 0)];
|
||||
cell.iter().any(|&i| inside(p, &self.polys[i as usize]))
|
||||
}
|
||||
}
|
||||
|
||||
fn inside(p: [f64; 2], poly: &[[f64; 2]]) -> bool {
|
||||
let n = poly.len();
|
||||
let mut c = false;
|
||||
for i in 0..n {
|
||||
let (a, b) = (poly[i], poly[(i + 1) % n]);
|
||||
if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < a[0] + (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) {
|
||||
c = !c;
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// Zellen des Tiefenrasters über die längere Seite der Zeichnung.
|
||||
const RASTER: f64 = 1200.0;
|
||||
|
||||
/// Tiefenraster (Flächen-Id je Zellmitte, kleinste Tiefe gewinnt) über die zugewandten Flächen: welche Flächen irgendwo
|
||||
/// vorne liegen. Flächen kleiner als eine Zelle können durchfallen (nur ihre Tönung fehlt dann; die Kanten sind exakt).
|
||||
fn item_buffer(faces: &[hlr::Face], front: &[usize], lo: [f64; 2], hi: [f64; 2]) -> Vec<bool> {
|
||||
let ext = (hi[0] - lo[0]).max(hi[1] - lo[1]);
|
||||
let cell = (ext / RASTER).max(1e-6);
|
||||
let (w, h) = ((((hi[0] - lo[0]) / cell).ceil() as usize).clamp(1, 4096), (((hi[1] - lo[1]) / cell).ceil() as usize).clamp(1, 4096));
|
||||
let mut depth = vec![f64::INFINITY; w * h];
|
||||
let mut id = vec![u32::MAX; w * h];
|
||||
let mut xs: Vec<f64> = Vec::new();
|
||||
for &fi in front {
|
||||
let f = &faces[fi];
|
||||
let Some(pl) = crate::hlr_fill::plane(&f.pts) else { continue };
|
||||
let poly: Vec<[f64; 2]> = f.pts.iter().map(|q| [(q[0] - lo[0]) / cell, (q[1] - lo[1]) / cell]).collect();
|
||||
let (y0, y1) = poly.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[1]), b.max(q[1])));
|
||||
let (ry0, ry1) = ((y0 - 0.5).ceil().max(0.0) as usize, ((y1 - 0.5).floor().min(h as f64 - 1.0)).max(-1.0));
|
||||
if ry1 < 0.0 {
|
||||
continue;
|
||||
}
|
||||
for ry in ry0..=(ry1 as usize) {
|
||||
let yc = ry as f64 + 0.5;
|
||||
xs.clear();
|
||||
let n = poly.len();
|
||||
for k in 0..n {
|
||||
let (a, b) = (poly[k], poly[(k + 1) % n]);
|
||||
if (a[1] > yc) != (b[1] > yc) {
|
||||
xs.push(a[0] + (b[0] - a[0]) * (yc - a[1]) / (b[1] - a[1]));
|
||||
}
|
||||
}
|
||||
xs.sort_by(|a, b| a.total_cmp(b));
|
||||
for pair in xs.chunks_exact(2) {
|
||||
let (rx0, rx1) = ((pair[0] - 0.5).ceil().max(0.0), (pair[1] - 0.5).floor().min(w as f64 - 1.0));
|
||||
if rx1 < rx0 {
|
||||
continue;
|
||||
}
|
||||
let v = lo[1] + yc * cell;
|
||||
for rx in rx0 as usize..=rx1 as usize {
|
||||
let u = lo[0] + (rx as f64 + 0.5) * cell;
|
||||
let d = pl[0] + pl[1] * u + pl[2] * v;
|
||||
let k = ry * w + rx;
|
||||
if d < depth[k] {
|
||||
depth[k] = d;
|
||||
id[k] = fi as u32;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = vec![false; faces.len()];
|
||||
for &i in &id {
|
||||
if let Some(s) = seen.get_mut(i as usize) {
|
||||
*s = true;
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Die eigentliche Rechnung auf vorbereiteten Flächen (auch für Tests mit eigenen Flächen).
|
||||
fn compute(faces: &[hlr::Face], model_n: &[V3], light: V3, o: AxoOpts) -> AxoOut {
|
||||
let mut out = AxoOut::default();
|
||||
// Massstab der Toleranzen: Ausdehnung der Zeichnung.
|
||||
let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
|
||||
for q in faces.iter().flat_map(|f| f.pts.iter()) {
|
||||
lo = [lo[0].min(q[0]), lo[1].min(q[1])];
|
||||
hi = [hi[0].max(q[0]), hi[1].max(q[1])];
|
||||
}
|
||||
if !(lo[0].is_finite() && hi[0].is_finite() && lo[1].is_finite() && hi[1].is_finite()) {
|
||||
return out;
|
||||
}
|
||||
let ext = (hi[0] - lo[0]).max(hi[1] - lo[1]).max(1.0);
|
||||
let tol = (ext * 1e-6).max(1e-5);
|
||||
let opts = hlr::Opts { tol, depth_eps: tol, hidden: o.hidden, ..hlr::Opts::default() };
|
||||
let segs = hlr::hidden_lines(faces, &opts);
|
||||
let front: Vec<usize> = (0..faces.len()).filter(|&i| faces[i].two_sided || faces[i].normal[2] < -1e-12).collect();
|
||||
let cover = Cover::new(front.iter().map(|&i| faces[i].pts.iter().map(|q| [q[0], q[1]]).collect()).collect());
|
||||
let delta = (ext * 2e-5).max(2e-3);
|
||||
for s in segs {
|
||||
if s.hidden {
|
||||
out.hidden.push((s.a, s.b, s.owner));
|
||||
continue;
|
||||
}
|
||||
let (dx, dy) = (s.b[0] - s.a[0], s.b[1] - s.a[1]);
|
||||
let l = (dx * dx + dy * dy).sqrt();
|
||||
let m = [(s.a[0] + s.b[0]) / 2.0, (s.a[1] + s.b[1]) / 2.0];
|
||||
let nrm = if l > 0.0 { [-dy / l * delta, dx / l * delta] } else { [0.0, 0.0] };
|
||||
let outline = !cover.covered([m[0] + nrm[0], m[1] + nrm[1]]) || !cover.covered([m[0] - nrm[0], m[1] - nrm[1]]);
|
||||
out.edges.push((s.a, s.b, s.owner, outline));
|
||||
}
|
||||
if o.fills && front.len() <= FILL_BUDGET {
|
||||
// Vorauswahl über ein Tiefenraster (Flächen-Ids je Zelle): nur Flächen, die irgendwo vorne liegen, werden exakt
|
||||
// beschnitten — und nur sie können verdecken (was eine verdeckte Fläche deckte, deckt ihr Verdecker ebenso).
|
||||
let seen = item_buffer(faces, &front, lo, hi);
|
||||
let pts: Vec<Vec<V3>> = (0..faces.len()).map(|i| if seen[i] { faces[i].pts.clone() } else { Vec::new() }).collect();
|
||||
let regions = crate::hlr_fill::visible_regions(&pts, tol);
|
||||
// Je (Besitzer, Grauwert) vereinigt: keine Haarfugen zwischen den Dreiecken einer Wand.
|
||||
let mut groups: BTreeMap<(u32, i64), Vec<crate::flat::Polygon>> = BTreeMap::new();
|
||||
for (i, f) in faces.iter().enumerate() {
|
||||
if pts[i].is_empty() {
|
||||
continue;
|
||||
}
|
||||
let polys: Vec<crate::flat::Polygon> = match ®ions[i] {
|
||||
None => vec![vec![f.pts.iter().map(|q| [q[0], q[1]]).collect()]],
|
||||
Some(ps) => ps.clone(),
|
||||
};
|
||||
if polys.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Beidseitige Flächen (Dachhaut ohne Dicke): die dem Betrachter zugewandte Seite tönen.
|
||||
let mut n = model_n.get(i).copied().unwrap_or([0.0, 0.0, 1.0]);
|
||||
if f.two_sided && f.normal[2] > 0.0 {
|
||||
n = [-n[0], -n[1], -n[2]];
|
||||
}
|
||||
let g = tone(n, light);
|
||||
groups.entry((f.owner, (g * 1000.0) as i64)).or_default().extend(polys);
|
||||
}
|
||||
for ((owner, g), polys) in groups {
|
||||
let u = crate::polygon_bool::union(&polys);
|
||||
if !u.is_empty() {
|
||||
out.fills.push((u, g as f64 / 1000.0, owner));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Punkte auf einer Geraden zwischen ihren Nachbarn (Stösse der vereinigten Dreiecke) entfallen: sonst läse die
|
||||
/// Bogenerkennung der Ausgaben (`arc_fit`) lange, fast gerade Züge mit vielen Punkten als flachen Bogen.
|
||||
fn simplify(ring: &[[f64; 2]]) -> Vec<[f64; 2]> {
|
||||
let mut r: Vec<[f64; 2]> = ring.to_vec();
|
||||
loop {
|
||||
let n = r.len();
|
||||
if n <= 3 {
|
||||
return r;
|
||||
}
|
||||
// Erster entbehrlicher Punkt (gleich dem Vorgänger oder auf der Strecke zwischen seinen Nachbarn) fällt weg;
|
||||
// einer nach dem anderen, damit nie zwei Punkte mit Bezug aufeinander verschwinden.
|
||||
let drop = (0..n).find(|&i| {
|
||||
let (a, b, c) = (r[(i + n - 1) % n], r[i], r[(i + 1) % n]);
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
let (ux, uy, vx, vy) = (c[0] - a[0], c[1] - a[1], b[0] - a[0], b[1] - a[1]);
|
||||
let l2 = ux * ux + uy * uy;
|
||||
if !(l2 > 1e-24) {
|
||||
return false;
|
||||
}
|
||||
let t = vx * ux + vy * uy;
|
||||
(ux * vy - uy * vx).abs() / l2.sqrt() < 1e-6 && t > 0.0 && t < l2
|
||||
});
|
||||
match drop {
|
||||
Some(i) => {
|
||||
r.remove(i);
|
||||
}
|
||||
None => return r,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn grey_hex(g: f64) -> String {
|
||||
let v = (g.clamp(0.0, 1.0) * 255.0).round() as u32;
|
||||
format!("#{v:02x}{v:02x}{v:02x}")
|
||||
}
|
||||
|
||||
/// Argumente der Abfrage `axoPlan`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AxoArgs {
|
||||
pub proj: Projection,
|
||||
pub opts: AxoOpts,
|
||||
pub context: bool,
|
||||
pub vis: Visibility,
|
||||
}
|
||||
|
||||
/// Modellmitte (Hüllbox der Bauteile) für die Bildebene der Perspektive.
|
||||
fn model_center(p: &Project) -> V3 {
|
||||
let (mut lo, mut hi) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3]);
|
||||
let mut add = |x: f64, y: f64, z: f64| {
|
||||
if x.is_finite() && y.is_finite() && z.is_finite() {
|
||||
lo = [lo[0].min(x), lo[1].min(y), lo[2].min(z)];
|
||||
hi = [hi[0].max(x), hi[1].max(y), hi[2].max(z)];
|
||||
}
|
||||
};
|
||||
for w in &p.walls {
|
||||
let z = p.drawing_levels.iter().find(|l| l.id == w.floor_id).and_then(|l| l.base_elevation).unwrap_or(0.0);
|
||||
add(w.start.x, w.start.y, z);
|
||||
add(w.end.x, w.end.y, z + w.height);
|
||||
}
|
||||
if !lo[0].is_finite() {
|
||||
return [0.0; 3];
|
||||
}
|
||||
[(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0]
|
||||
}
|
||||
|
||||
impl AxoArgs {
|
||||
/// Aus dem JSON der Abfrage: `view` (Vorgabe), `projection` (`iso`/`military`/`military30`), `camera`
|
||||
/// (`ViewCamera`), `cameraId` (Kamera-Element), `aspect`, `hidden`, `fills` (Vorgabe an), `context` (Vorgabe aus) und
|
||||
/// die Sichtbarkeit wie im Schnitt (`hasVis`, `invisible`, …). Kamera vor Kamera-Element vor Vorgabe.
|
||||
pub fn parse(p: &Project, v: &serde_json::Value) -> Option<AxoArgs> {
|
||||
let s = |k: &str| v.get(k).and_then(|x| x.as_str()).unwrap_or("");
|
||||
let b = |k: &str, d: bool| v.get(k).and_then(|x| x.as_bool()).unwrap_or(d);
|
||||
let aspect = v.get("aspect").and_then(|x| x.as_f64()).unwrap_or(1.5);
|
||||
let center = model_center(p);
|
||||
let v3 = |c: &serde_json::Value, k: &str| -> Option<V3> {
|
||||
let a = c.get(k)?.as_array()?;
|
||||
Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?])
|
||||
};
|
||||
let proj = match v.get("camera").filter(|c| c.is_object()) {
|
||||
Some(c) => camera(c.get("kind").and_then(|k| k.as_str()).unwrap_or("orthogonal"), v3(c, "position")?, v3(c, "direction")?, v3(c, "up").unwrap_or([0.0, 0.0, 1.0]), c.get("fovDeg").and_then(|f| f.as_f64()).unwrap_or(50.0), aspect, center)?,
|
||||
None if !s("cameraId").is_empty() => project_camera(p, s("cameraId"), aspect, center)?,
|
||||
None => preset(s("view"), if s("projection").is_empty() { "iso" } else { s("projection") })?,
|
||||
};
|
||||
Some(AxoArgs { proj, opts: AxoOpts { hidden: b("hidden", false) || b("hiddenLines", false), fills: b("fills", true) }, context: b("context", false), vis: Visibility::from_json(v) })
|
||||
}
|
||||
}
|
||||
|
||||
/// [266] Abfrage-Text (`axoPlan`) eines 3D-Dokuments: Einstellungen des Ausschnitts (`doc3d`, sonst sein Blickwinkel
|
||||
/// `view3d`) und die Klassen, die er ausblendet (`invisible`, wie beim Schnitt-Viewport).
|
||||
pub fn snapshot_text(snap: &ViewSnapshot, invisible: &[String]) -> String {
|
||||
let mut v = snap.doc3d.as_ref().and_then(|d| serde_json::to_value(d).ok()).unwrap_or_else(|| serde_json::json!({}));
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
if !o.contains_key("view") {
|
||||
o.insert("view".into(), serde_json::to_value(snap.view3d).unwrap_or_default());
|
||||
}
|
||||
o.insert("hasVis".into(), serde_json::Value::Bool(true));
|
||||
o.insert("invisible".into(), serde_json::to_value(invisible).unwrap_or_default());
|
||||
}
|
||||
v.to_string()
|
||||
}
|
||||
|
||||
/// Plan-Primitive der Axonometrie und ihr Ausmass; `None` ohne sichtbares Bauteil.
|
||||
pub fn axo_primitives(p: &Project, a: &AxoArgs, mono: bool) -> Result<Option<(Vec<Primitive>, [f64; 4])>, String> {
|
||||
let Some((prep, refs)) = prepare(p, &a.proj, &a.vis, a.context)? else { return Ok(None) };
|
||||
if prep.faces.is_empty() || prep.faces.len() > FACE_BUDGET {
|
||||
return Ok(None);
|
||||
}
|
||||
let out = compute(&prep.faces, &prep.model_n, light_of(&a.proj), a.opts);
|
||||
let _ = mono; // Tusche wie Farbe: die Axonometrie ist grau.
|
||||
let mut prims = Vec::new();
|
||||
let mut acc = super::section::Acc::new();
|
||||
let owner = |o: u32| refs.get(o as usize);
|
||||
for (polys, g, o) in &out.fills {
|
||||
let fill = grey_hex(*g);
|
||||
for poly in polys {
|
||||
let ring = simplify(&if poly.len() > 1 { crate::voids::keyhole(poly).0 } else { poly[0].clone() });
|
||||
if ring.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
for q in &ring {
|
||||
acc.add(q[0], q[1]);
|
||||
}
|
||||
// Ein Hauch Kontur in der Füllfarbe deckt die Haarfugen zwischen Nachbarflächen.
|
||||
let mut prim = polygon(ring.iter().map(|q| v2(q[0], q[1])).collect(), &fill, &fill, 0.1, no_hatch());
|
||||
if let (Primitive::Polygon { wall_id, ceiling_id, roof_id, stair_id, column_id, extruded_solid_id, context_object_id, .. }, Some(r)) = (&mut prim, owner(*o)) {
|
||||
let id = r.id.clone();
|
||||
match r.kind {
|
||||
Kind::Wall => *wall_id = id,
|
||||
Kind::Roof => *roof_id = id,
|
||||
Kind::Body => *extruded_solid_id = id,
|
||||
Kind::Mesh => *context_object_id = id,
|
||||
Kind::Slab if r.stair => *stair_id = id,
|
||||
Kind::Slab if r.column => *column_id = id,
|
||||
Kind::Slab => *ceiling_id = id,
|
||||
}
|
||||
}
|
||||
prims.push(prim);
|
||||
}
|
||||
}
|
||||
for (a, b, _) in &out.hidden {
|
||||
let mut l = line(v2(a[0], a[1]), v2(b[0], b[1]), "axo-hidden", HIDDEN_MM, HIDDEN_INK);
|
||||
if let Primitive::Line { dash, .. } = &mut l {
|
||||
*dash = Some(Some(super::line_pattern::HIDDEN.to_vec()));
|
||||
}
|
||||
prims.push(l);
|
||||
}
|
||||
for pass in [false, true] {
|
||||
for (a, b, _, outline) in out.edges.iter().filter(|e| e.3 == pass) {
|
||||
acc.add(a[0], a[1]);
|
||||
acc.add(b[0], b[1]);
|
||||
prims.push(if *outline { line(v2(a[0], a[1]), v2(b[0], b[1]), "axo-outline", OUTLINE_MM, OUTLINE_INK) } else { line(v2(a[0], a[1]), v2(b[0], b[1]), "axo-edge", EDGE_MM, EDGE_INK) });
|
||||
}
|
||||
}
|
||||
if prims.is_empty() || !(acc.max_x >= acc.min_x) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some((prims, [acc.min_x, acc.min_y, acc.max_x, acc.max_y])))
|
||||
}
|
||||
|
||||
/// Abfrage `axoPlan`: `args` = `[mono, Massstab]`, `text` = JSON ([`AxoArgs::parse`]). Plan-Puffer mit einer Gruppe
|
||||
/// (Strichstärken nach Massstab wie im Schnitt); ohne Bild (leeres Projekt, unbrauchbare Kamera) ohne Gruppen.
|
||||
pub fn axo_plan_buf(p: &Project, args: &[f64], text: &str) -> Result<Vec<u8>, String> {
|
||||
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("Axonometrie-Argumente: {e}"))?;
|
||||
let mono = args.first().is_some_and(|&x| x != 0.0);
|
||||
let scale = args.get(1).copied().filter(|s| s.is_finite() && *s > 0.0).unwrap_or(100.0);
|
||||
let mut w = crate::plan::buf::Writer::new(true);
|
||||
let Some(a) = AxoArgs::parse(p, &v) else { return Ok(w.finish()) };
|
||||
if let Some((mut prims, bounds)) = axo_primitives(p, &a, mono)? {
|
||||
super::extras::scale_line_weights(p, scale, &mut prims);
|
||||
w.group(&prims);
|
||||
w.bounds = Some(bounds);
|
||||
}
|
||||
Ok(w.finish())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "axo_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Tests zur Vektor-Axonometrie ([266], `plan/axo.rs`).
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Projekt mit Würfeln aus Wänden (1 m dick, 1 m lang, 1 m hoch): je `(x, y, z)` die untere Ecke.
|
||||
fn cubes(c: &[(f64, f64, f64)]) -> Project {
|
||||
let mut levels = Vec::new();
|
||||
let mut walls = Vec::new();
|
||||
for (i, (x, y, z)) in c.iter().enumerate() {
|
||||
levels.push(serde_json::json!({"id": format!("l{i}"), "name": format!("L{i}"), "kind": "floor", "visible": true, "locked": false, "floorHeight": 1.0, "baseElevation": z}));
|
||||
walls.push(serde_json::json!({"id": format!("w{i}"), "type": "wall", "floorId": format!("l{i}"), "categoryCode": "20", "wallTypeId": "t", "start": {"x": x, "y": y + 0.5}, "end": {"x": x + 1.0, "y": y + 0.5}, "height": 1.0}));
|
||||
}
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "P", "lineStyles": [], "hatches": [], "components": [{"id": "c", "name": "C", "hatchId": ""}],
|
||||
"wallTypes": [{"id": "t", "name": "T", "layers": [{"componentId": "c", "thickness": 1.0}]}],
|
||||
"drawingLevels": levels, "layers": [{"code": "20", "name": "W", "color": "#000", "lw": 0.5, "visible": true, "locked": false}],
|
||||
"walls": walls, "drawings2d": []
|
||||
}))
|
||||
.expect("Projekt")
|
||||
}
|
||||
|
||||
fn args(v: serde_json::Value, p: &Project) -> AxoArgs {
|
||||
AxoArgs::parse(p, &v).expect("Argumente")
|
||||
}
|
||||
|
||||
/// Sichtbare Linien (a, b, Silhouette), kollineare anstossende Stücke zusammengefasst.
|
||||
fn lines(prims: &[Primitive]) -> Vec<([f64; 2], [f64; 2], bool)> {
|
||||
let mut l: Vec<([f64; 2], [f64; 2], bool)> = prims
|
||||
.iter()
|
||||
.filter_map(|q| match q {
|
||||
Primitive::Line { a, b, cls, .. } if cls == "axo-edge" || cls == "axo-outline" => Some(([a.x, a.y], [b.x, b.y], cls == "axo-outline")),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let col = |a: ([f64; 2], [f64; 2], bool), b: ([f64; 2], [f64; 2], bool)| -> Option<([f64; 2], [f64; 2], bool)> {
|
||||
let d = [a.1[0] - a.0[0], a.1[1] - a.0[1]];
|
||||
let cr = |p: [f64; 2]| (d[0] * (p[1] - a.0[1]) - d[1] * (p[0] - a.0[0])).abs();
|
||||
if cr(b.0) > 1e-6 || cr(b.1) > 1e-6 {
|
||||
return None;
|
||||
}
|
||||
let near = |p: [f64; 2], q: [f64; 2]| (p[0] - q[0]).abs() + (p[1] - q[1]).abs() < 1e-6;
|
||||
for (x, y) in [(a.0, a.1), (a.1, a.0)] {
|
||||
for (u, w) in [(b.0, b.1), (b.1, b.0)] {
|
||||
if near(y, u) {
|
||||
return Some((x, w, a.2 || b.2));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
};
|
||||
'outer: loop {
|
||||
for i in 0..l.len() {
|
||||
for j in i + 1..l.len() {
|
||||
if let Some(m) = col(l[i], l[j]) {
|
||||
l[i] = m;
|
||||
l.remove(j);
|
||||
continue 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
l
|
||||
}
|
||||
|
||||
fn prims_of(p: &Project, v: serde_json::Value) -> Vec<Primitive> {
|
||||
axo_primitives(p, &args(v, p), false).unwrap().expect("Bild").0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wuerfel_isometrie_neun_kanten() {
|
||||
let p = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
for view in ["southeast", "southwest", "northeast", "northwest"] {
|
||||
let l = lines(&prims_of(&p, serde_json::json!({"view": view})));
|
||||
assert_eq!(l.len(), 9, "{view}: {l:?}");
|
||||
assert_eq!(l.iter().filter(|e| e.2).count(), 6, "{view}: Umriss sechs Kanten");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wuerfel_flaechen_getoent_nach_lage() {
|
||||
let p = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
let prims = prims_of(&p, serde_json::json!({"view": "southeast"}));
|
||||
let fills: Vec<&String> = prims.iter().filter_map(|q| match q { Primitive::Polygon { fill, wall_id, .. } => { assert_eq!(wall_id.as_deref(), Some("w0")); Some(fill) } _ => None }).collect();
|
||||
assert_eq!(fills.len(), 3, "drei sichtbare Seiten");
|
||||
let mut f = fills.clone();
|
||||
f.sort();
|
||||
f.dedup();
|
||||
assert_eq!(f.len(), 3, "drei verschiedene Grautöne: {fills:?}");
|
||||
// Ohne Füllungen nur Linien.
|
||||
let prims = prims_of(&p, serde_json::json!({"view": "southeast", "fills": false}));
|
||||
assert!(prims.iter().all(|q| matches!(q, Primitive::Line { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verdeckter_wuerfel_entfaellt() {
|
||||
// Von Norden (vorne) gesehen: der kleinere Würfel liegt ganz hinter dem grossen.
|
||||
let mut p = cubes(&[(0.0, 0.0, 0.0), (0.0, -5.0, 0.0)]);
|
||||
p.walls[1].start.x = 0.25;
|
||||
p.walls[1].end.x = 0.75;
|
||||
p.walls[1].height = 0.5;
|
||||
let l = lines(&prims_of(&p, serde_json::json!({"view": "front"})));
|
||||
assert_eq!(l.len(), 4, "nur das Quadrat vorne: {l:?}");
|
||||
// Mit verdeckten Kanten: die Kanten des hinteren Würfels gestrichelt.
|
||||
let prims = prims_of(&p, serde_json::json!({"view": "front", "hidden": true}));
|
||||
let hidden = prims.iter().filter(|q| matches!(q, Primitive::Line { cls, dash: Some(Some(_)), .. } if cls == "axo-hidden")).count();
|
||||
assert!(hidden >= 3, "verdeckte Kanten: {hidden}");
|
||||
// In der Isometrie zwei Würfel hintereinander: der hintere wird teilweise verdeckt, keine Linie quert den vorderen.
|
||||
let p = cubes(&[(0.0, 0.0, 0.0), (-1.5, 1.5, 0.0)]);
|
||||
// 9 Kanten des vorderen und 9 sichtbare Teilstücke des hinteren (an den vorderen anstossend, nicht darüber).
|
||||
let l = lines(&prims_of(&p, serde_json::json!({"view": "southeast"})));
|
||||
assert_eq!(l.len(), 18, "{l:?}");
|
||||
let a = lines(&prims_of(&cubes(&[(0.0, 0.0, 0.0)]), serde_json::json!({"view": "southeast"})));
|
||||
let hull: Vec<[f64; 2]> = a.iter().filter(|e| e.2).flat_map(|e| [e.0, e.1]).collect();
|
||||
let (cx, cy) = (hull.iter().map(|q| q[0]).sum::<f64>() / hull.len() as f64, hull.iter().map(|q| q[1]).sum::<f64>() / hull.len() as f64);
|
||||
for e in l.iter().filter(|e| !a.iter().any(|f| f.0 == e.0 && f.1 == e.1)) {
|
||||
// Mitte eines Stücks des hinteren Würfels: nicht im Innern des vorderen (Sechseck um die Mitte, Radius < 0.8).
|
||||
let m = [(e.0[0] + e.1[0]) / 2.0, (e.0[1] + e.1[1]) / 2.0];
|
||||
assert!(((m[0] - cx).powi(2) + (m[1] - cy).powi(2)).sqrt() > 0.35, "Linie im vorderen Würfel: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn militaer_grundriss_unverzerrt_senkrechte_unverkuerzt() {
|
||||
let p = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
for kind in ["military", "military30"] {
|
||||
let l = lines(&prims_of(&p, serde_json::json!({"view": "southeast", "projection": kind})));
|
||||
let len = |e: &([f64; 2], [f64; 2], bool)| ((e.1[0] - e.0[0]).powi(2) + (e.1[1] - e.0[1]).powi(2)).sqrt();
|
||||
assert!(l.iter().all(|e| (len(e) - 1.0).abs() < 1e-6), "{kind}: alle Kanten 1 m: {l:?}");
|
||||
assert!(l.iter().filter(|e| (e.0[0] - e.1[0]).abs() < 1e-9).count() >= 3, "{kind}: Senkrechte senkrecht");
|
||||
assert_eq!(l.len(), 9, "{kind}");
|
||||
}
|
||||
// 30/60: die Süd-/Nordkanten (x) liegen 30° geneigt.
|
||||
let l = lines(&prims_of(&p, serde_json::json!({"view": "southeast", "projection": "military30"})));
|
||||
let ang = |e: &([f64; 2], [f64; 2], bool)| (e.1[1] - e.0[1]).abs().atan2((e.1[0] - e.0[0]).abs()).to_degrees();
|
||||
assert!(l.iter().any(|e| (ang(e) - 30.0).abs() < 1e-6) && l.iter().any(|e| (ang(e) - 60.0).abs() < 1e-6));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kamera_parallel_und_perspektive() {
|
||||
let p = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
let cam = |kind: &str| serde_json::json!({"camera": {"kind": kind, "position": [6.0, -5.0, 4.0], "direction": [-5.5, 5.5, -3.5], "up": [0.0, 0.0, 1.0], "fovDeg": 40.0}});
|
||||
for kind in ["orthogonal", "perspective"] {
|
||||
let l = lines(&prims_of(&p, cam(kind)));
|
||||
assert_eq!(l.len(), 9, "{kind}: {l:?}");
|
||||
assert!(l.iter().all(|e| e.0.iter().chain(e.1.iter()).all(|v| v.is_finite())));
|
||||
}
|
||||
// Perspektive: die senkrechten Kanten laufen nach unten zusammen (Blick von oben), sie sind nicht parallel.
|
||||
let l = lines(&prims_of(&p, cam("perspective")));
|
||||
let vert: Vec<_> = l.iter().filter(|e| (e.1[1] - e.0[1]).abs() > 3.0 * (e.1[0] - e.0[0]).abs()).collect();
|
||||
assert!(vert.len() >= 3);
|
||||
assert!(vert.iter().any(|e| (e.1[0] - e.0[0]).abs() > 1e-3), "Fluchten: {vert:?}");
|
||||
// Kamera im Würfel bzw. hinter dem Blick: kein Absturz, kein Unsinn.
|
||||
let inside = serde_json::json!({"camera": {"kind": "perspective", "position": [0.5, 0.5, 0.5], "direction": [1.0, 0.0, 0.0], "up": [0.0, 0.0, 1.0], "fovDeg": 60.0}});
|
||||
let r = axo_primitives(&p, &args(inside, &p), false).unwrap();
|
||||
if let Some((prims, b)) = r {
|
||||
assert!(b.iter().all(|v| v.is_finite()) && !prims.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn satteldach_first_und_traufe() {
|
||||
let p: Project = serde_json::from_value(serde_json::json!({
|
||||
"id": "p", "name": "t", "lineStyles": [], "hatches": [], "components": [], "wallTypes": [],
|
||||
"drawingLevels": [], "layers": [], "walls": [], "drawings2d": [],
|
||||
"roofs": [{"id": "R", "type": "roof", "floorId": "F", "categoryCode": "35",
|
||||
"outline": [{"x": 0, "y": 0}, {"x": 12, "y": 0}, {"x": 12, "y": 8}, {"x": 0, "y": 8}],
|
||||
"shape": "sattel", "pitchDeg": 50, "overhang": 0.0, "ridgeAxis": "x", "baseElevation": 3.0, "thickness": 0.25}]
|
||||
}))
|
||||
.unwrap();
|
||||
let a = args(serde_json::json!({"view": "southeast"}), &p);
|
||||
let (prims, b) = axo_primitives(&p, &a, false).unwrap().expect("Dach");
|
||||
let l = lines(&prims);
|
||||
// Isometrie Südost, Dach 50° (steiler als der Blick): die Nordfläche ist abgewandt, der First Umriss.
|
||||
let Projection::Parallel { m, .. } = a.proj else { panic!() };
|
||||
let pv = |q: V3| [dot(m[0], q), dot(m[1], q)];
|
||||
let ridge_z = 3.0 + 4.0 * 50f64.to_radians().tan();
|
||||
let (r0, r1) = (pv([0.0, 4.0, ridge_z]), pv([12.0, 4.0, ridge_z]));
|
||||
let on = |e: &([f64; 2], [f64; 2], bool), q: [f64; 2], tol: f64| {
|
||||
let d = [e.1[0] - e.0[0], e.1[1] - e.0[1]];
|
||||
let len = (d[0] * d[0] + d[1] * d[1]).sqrt();
|
||||
let t = ((q[0] - e.0[0]) * d[0] + (q[1] - e.0[1]) * d[1]) / (len * len);
|
||||
let c = [e.0[0] + d[0] * t, e.0[1] + d[1] * t];
|
||||
t > -1e-6 && t < 1.0 + 1e-6 && ((c[0] - q[0]).powi(2) + (c[1] - q[1]).powi(2)).sqrt() < tol
|
||||
};
|
||||
let mid = [(r0[0] + r1[0]) / 2.0, (r0[1] + r1[1]) / 2.0];
|
||||
assert!(l.iter().any(|e| on(e, mid, 0.4)), "First fehlt: {l:?}");
|
||||
// Traufe Süd (y = 0, z = 3) sichtbar, die Nordtraufe (hinter dem First) verdeckt.
|
||||
let s_mid = pv([6.0, 0.0, 3.0]);
|
||||
let n_mid = pv([6.0, 8.0, 3.0]);
|
||||
assert!(l.iter().any(|e| on(e, s_mid, 0.4)), "Traufe Süd fehlt");
|
||||
assert!(!l.iter().any(|e| on(e, n_mid, 0.05)), "Traufe Nord müsste verdeckt sein");
|
||||
assert!(b[3] > b[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leeres_projekt_und_unsinn_ohne_absturz() {
|
||||
let empty = Project::default();
|
||||
let buf = axo_plan_buf(&empty, &[0.0, 100.0], r#"{"view":"southeast"}"#).unwrap();
|
||||
let v = crate::plan::buf::View::parse(&buf).unwrap();
|
||||
assert!(v.groups().unwrap_or_default().is_empty());
|
||||
let p = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
for t in [
|
||||
r#"{"camera":{"kind":"perspective","position":[NaN,0,0],"direction":[1,0,0]}}"#,
|
||||
r#"{"camera":{"kind":"perspective","position":[1e300,-1e300,1e300],"direction":[-1,1,-1],"fovDeg":1e308}}"#,
|
||||
r#"{"camera":{"kind":"orthogonal","position":[0,0,0],"direction":[0,0,0]}}"#,
|
||||
r#"{"camera":{"kind":"perspective","position":[0,0,0],"direction":[0,0,1],"up":[0,0,1]}}"#,
|
||||
r#"{"view":"gibtsnicht"}"#,
|
||||
r#"{"cameraId":"fehlt"}"#,
|
||||
r#"{"view":"southeast","projection":"military30","aspect":-1}"#,
|
||||
"{}",
|
||||
] {
|
||||
// NaN ist kein JSON: Fehler statt Absturz.
|
||||
let _ = axo_plan_buf(&p, &[f64::NAN, f64::INFINITY], t);
|
||||
}
|
||||
assert!(axo_plan_buf(&p, &[0.0, 100.0], "kein json").is_err());
|
||||
// Riesige Koordinaten im Modell.
|
||||
let mut big = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
big.walls[0].start.x = 1e200;
|
||||
let _ = axo_plan_buf(&big, &[0.0, 100.0], r#"{"view":"southeast"}"#);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn klassen_ausgeblendet() {
|
||||
let p = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
let a = args(serde_json::json!({"view": "southeast", "hasVis": true, "invisible": ["20"]}), &p);
|
||||
assert!(axo_primitives(&p, &a, false).unwrap().is_none(), "Klasse 20 aus: kein Bauteil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kamera_element_des_projekts() {
|
||||
let mut p = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
p.cameras = Some(vec![serde_json::from_value(serde_json::json!({"id": "k", "type": "camera", "name": "K", "floorId": "l0", "categoryCode": "92", "position": {"x": 6, "y": -5}, "eyeHeight": 3.0, "target": {"x": 0.5, "y": 0.5}, "targetHeight": 0.5, "fovDeg": 40, "projection": "perspective"})).unwrap()]);
|
||||
let l = lines(&prims_of(&p, serde_json::json!({"cameraId": "k"})));
|
||||
assert_eq!(l.len(), 9, "{l:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ausschnitt_3d_auf_dem_blatt() {
|
||||
let mut p = cubes(&[(0.0, 0.0, 0.0)]);
|
||||
let snap: ViewSnapshot = serde_json::from_value(serde_json::json!({"id": "s3", "name": "3D", "viewType": "perspektive", "view3d": "isoBackRight", "scaleDenominator": 50, "detail": "mittel", "activeLevelId": "l0", "layerVisibility": {"20": true}, "drawingVisibility": {}})).unwrap();
|
||||
p.view_snapshots = Some(vec![snap.clone()]);
|
||||
let buf = crate::sheet_viewports::snapshot_buf(&p, &snap, 50.0, None).expect("3D-Dokument");
|
||||
let prims = crate::plan::buf::View::parse(&buf).unwrap().prims().unwrap();
|
||||
assert_eq!(lines(&prims).len(), 9);
|
||||
// Klasse aus: kein Inhalt.
|
||||
let mut off = snap.clone();
|
||||
off.layer_visibility.insert("20".into(), false);
|
||||
assert!(crate::sheet_viewports::snapshot_buf(&p, &off, 50.0, None).is_none());
|
||||
// Militär mit verdeckten Kanten über `doc3d` (zwei Würfel: der hintere teils verdeckt; Rückseiten zeigt die
|
||||
// Zeichnung nicht, nur verdeckte Teile zugewandter Flächen).
|
||||
let p = cubes(&[(0.0, 0.0, 0.0), (-1.5, 1.5, 0.0)]);
|
||||
let mut mil = snap.clone();
|
||||
mil.doc3d = Some(serde_json::from_value(serde_json::json!({"projection": "military", "hiddenLines": true, "fills": false})).unwrap());
|
||||
let buf = crate::sheet_viewports::snapshot_buf(&p, &mil, 50.0, None).unwrap();
|
||||
let prims = crate::plan::buf::View::parse(&buf).unwrap().prims().unwrap();
|
||||
assert!(prims.iter().all(|q| matches!(q, Primitive::Line { .. })));
|
||||
assert!(prims.iter().any(|q| matches!(q, Primitive::Line { cls, .. } if cls == "axo-hidden")));
|
||||
}
|
||||
|
||||
/// Zeitprofil von Hand: `AXO_OBP=mk.obp cargo test --release --lib axo_zeit -- --ignored --nocapture`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn axo_zeit() {
|
||||
let Ok(path) = std::env::var("AXO_OBP") else { return };
|
||||
let p: Project = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
|
||||
let a = args(serde_json::json!({"view": "southeast"}), &p);
|
||||
let t = std::time::Instant::now();
|
||||
let (prep, refs) = prepare(&p, &a.proj, &a.vis, false).unwrap().unwrap();
|
||||
eprintln!("Flächen: {} in {:?}", prep.faces.len(), t.elapsed());
|
||||
let t = std::time::Instant::now();
|
||||
let segs = hlr::hidden_lines(&prep.faces, &hlr::Opts { tol: 1e-4, depth_eps: 1e-4, hidden: false, ..hlr::Opts::default() });
|
||||
eprintln!("Kanten: {} in {:?}", segs.len(), t.elapsed());
|
||||
let t = std::time::Instant::now();
|
||||
let out = compute(&prep.faces, &prep.model_n, light_of(&a.proj), AxoOpts { hidden: false, fills: false });
|
||||
eprintln!("ohne Füllung: {} in {:?}", out.edges.len(), t.elapsed());
|
||||
let t = std::time::Instant::now();
|
||||
let out = compute(&prep.faces, &prep.model_n, light_of(&a.proj), AxoOpts { hidden: false, fills: true });
|
||||
eprintln!("mit Füllung: {} in {:?}", out.fills.len(), t.elapsed());
|
||||
let area = |r: &[[f64; 2]]| r.iter().zip(r.iter().cycle().skip(1)).map(|(a, b)| a[0] * b[1] - b[0] * a[1]).sum::<f64>() / 2.0;
|
||||
for (polys, _, o) in &out.fills {
|
||||
for poly in polys {
|
||||
let ring = if poly.len() > 1 { crate::voids::keyhole(poly).0 } else { poly[0].clone() };
|
||||
let s = simplify(&ring);
|
||||
assert!((area(&ring) - area(&s)).abs() < 1e-6, "simplify ändert die Fläche von {:?}", refs.get(*o as usize).and_then(|r| r.id.clone()));
|
||||
let whole: f64 = poly.iter().enumerate().map(|(k, r)| if k == 0 { area(r).abs() } else { -area(r).abs() }).sum();
|
||||
assert!((area(&ring).abs() - whole).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Zwischenpunkte auf Geraden fallen weg, die Fläche bleibt; ein doppelter Schlusspunkt nimmt nicht beide Ecken mit.
|
||||
#[test]
|
||||
fn ringe_vereinfachen_ohne_flaechenverlust() {
|
||||
let area = |r: &[[f64; 2]]| r.iter().zip(r.iter().cycle().skip(1)).map(|(a, b)| a[0] * b[1] - b[0] * a[1]).sum::<f64>() / 2.0;
|
||||
let r = vec![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]];
|
||||
let s = simplify(&r);
|
||||
assert_eq!(s.len(), 4, "{s:?}");
|
||||
assert!((area(&s) - 2.0).abs() < 1e-12);
|
||||
let tri = vec![[0.0, 0.0], [2.0, 0.0], [1.0, 2.0], [0.0, 0.0], [0.0, 0.0]];
|
||||
assert!((area(&simplify(&tri)) - 2.0).abs() < 1e-12);
|
||||
}
|
||||
@@ -43,6 +43,7 @@ pub mod trees;
|
||||
pub mod cameras;
|
||||
pub mod mesh_plan;
|
||||
pub mod situation;
|
||||
pub mod axo;
|
||||
pub mod contrast;
|
||||
pub mod arc_fit;
|
||||
pub(crate) mod seams;
|
||||
|
||||
@@ -111,7 +111,7 @@ pub(super) fn merge_arc_wall_cuts(cuts: Vec<Cut>, p: &Project, walls_r: &[RWall]
|
||||
}
|
||||
|
||||
/// Je emittiertem Wand-Teilquader die Quellwand (über `RWall::wall_id`).
|
||||
pub(super) fn wall_owners<'a>(p: &'a Project, walls: &[RWall]) -> Vec<Option<&'a Wall>> {
|
||||
pub(crate) fn wall_owners<'a>(p: &'a Project, walls: &[RWall]) -> Vec<Option<&'a Wall>> {
|
||||
let mut by_id: HashMap<&str, &Wall> = HashMap::with_capacity(p.walls.len());
|
||||
for w in &p.walls {
|
||||
by_id.entry(w.id.as_str()).or_insert(w);
|
||||
|
||||
@@ -93,7 +93,7 @@ fn f32s3(v: [f64; 3]) -> [f32; 3] {
|
||||
[json_f32(v[0]), json_f32(v[1]), json_f32(v[2])]
|
||||
}
|
||||
|
||||
pub(super) fn wall_input(w: &RWall) -> render3d::WallInput {
|
||||
pub(crate) fn wall_input(w: &RWall) -> render3d::WallInput {
|
||||
render3d::WallInput {
|
||||
start: f32s2(w.start),
|
||||
end: f32s2(w.end),
|
||||
|
||||
@@ -34,6 +34,7 @@ pub use bands::*;
|
||||
use shapes::*;
|
||||
use voids::*;
|
||||
pub(crate) use meshes::*;
|
||||
pub(crate) use projection::{model_view_faces, OwnerRef};
|
||||
use projection::*;
|
||||
pub use primitives::*;
|
||||
pub use openings::*;
|
||||
@@ -524,7 +525,7 @@ pub struct Output {
|
||||
|
||||
/// [180] Klassen der Projektions-Besitzer: Wände (Index in `walls_r`), Platten (Decken, Treppen, Stützen; Index in
|
||||
/// `slabs_r`), Dächer, Körper (Index in `extrudedSolids`).
|
||||
fn edge_categories(p: &Project, walls: &[Option<&Wall>], slabs: &[bands::SlabOwner]) -> HashMap<(Kind, usize), String> {
|
||||
pub(crate) fn edge_categories(p: &Project, walls: &[Option<&Wall>], slabs: &[bands::SlabOwner]) -> HashMap<(Kind, usize), String> {
|
||||
let mut m = HashMap::new();
|
||||
for (i, w) in walls.iter().enumerate() {
|
||||
if let Some(w) = w {
|
||||
|
||||
@@ -44,37 +44,37 @@ fn quad_of(t: &[[f64; 3]; 3], n: [f64; 3], next: &[u32], vert: &dyn Fn(u32) -> (
|
||||
Some(q)
|
||||
}
|
||||
|
||||
/// Ansichtskanten hinter der Schnittebene mit exakter Sichtbarkeit ([G4], `hlr.rs`; verdeckte nur mit
|
||||
/// `hidden`, wie `hiddenLines` der Ebene): die Körper als
|
||||
/// Dreiecke (Wände samt Gehrung und Löchern wie im 3D-Modell, Platten, Treppen, Dächer, Körper),
|
||||
/// auf die Seite hinter der Ebene zugeschnitten; die Schnittflächen verdecken in Tiefe 0. Bogenwände,
|
||||
/// verschnittene Dächer und Körper glätten ihre Facetten (keine Fugen, nur Knicke und Silhouetten).
|
||||
/// Flächen des Modells in Ansichtskoordinaten ([G4]), gemeinsam für den Schnitt (Projektion hinter der Ebene) und
|
||||
/// [266] die Vektor-Axonometrie (`plan/axo.rs`): Wände samt Gehrung und Löchern wie im 3D-Modell, Platten, Treppen
|
||||
/// (mit Wangen und Geländer), Dächer, freie Körper und importierte Netze (`mesh_keep`). `view`: Welt (x, Höhe, y) →
|
||||
/// Ansicht (u, v, Tiefe), affin; `view_normal`: Normale dazu (zugewandt bei Tiefe-Anteil < 0); `clip`: auf Tiefe ≥ 0
|
||||
/// zuschneiden (Schnitt). Bauteile ausgeblendeter Klassen (`skip`) entfallen.
|
||||
pub(crate) struct ViewFaces {
|
||||
pub faces: Vec<crate::hlr::Face>,
|
||||
/// Besitzer je `Face::owner`.
|
||||
pub owners: Vec<(Kind, usize)>,
|
||||
/// Besitzer, die Treppengeländer sind.
|
||||
pub rail_owners: HashSet<u32>,
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn projection_edges(p: &Project, plane: &Plane, walls_r: &[RWall], wi: &[render3d::WallInput], slabs_r: &[RSlab], bodies: &[&BodyMesh], meshes: &[crate::mesh_view::MeshRef], cuts: &[Cut], hidden: bool, max_depth: Option<f64>, strip: &[[f64; 3]], skip: &dyn Fn(Kind, usize) -> bool) -> (Vec<Edge>, Vec<Edge>) {
|
||||
pub(crate) fn view_faces(p: &Project, view: &dyn Fn([f64; 3]) -> [f64; 3], view_normal: &dyn Fn([f64; 3]) -> [f64; 3], clip: bool, walls_r: &[RWall], wi: &[render3d::WallInput], slabs_r: &[RSlab], bodies: &[&BodyMesh], meshes: &[crate::mesh_view::MeshRef], mesh_keep: &dyn Fn(&crate::mesh_view::MeshRef) -> bool, skip: &dyn Fn(Kind, usize) -> bool) -> ViewFaces {
|
||||
use crate::hlr;
|
||||
let nl = crate::jsmath::hypot(&plane.normal);
|
||||
if !(nl > 1e-12) {
|
||||
return (Vec::new(), Vec::new());
|
||||
}
|
||||
let n = [plane.normal[0] / nl, plane.normal[1] / nl, plane.normal[2] / nl];
|
||||
let ul = hypot2(n[2], n[0]);
|
||||
let u = if ul > 1e-12 { [n[2] / ul, 0.0, -n[0] / ul] } else { [1.0, 0.0, 0.0] };
|
||||
let o = plane.point;
|
||||
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
let view = |w: [f64; 3]| {
|
||||
let r = [w[0] - o[0], w[1] - o[1], w[2] - o[2]];
|
||||
[dot(r, u), w[1], dot(r, n)]
|
||||
};
|
||||
let mut faces: Vec<hlr::Face> = Vec::new();
|
||||
let mut owners: Vec<(Kind, usize)> = Vec::new();
|
||||
// Fläche (Welt, Y oben) hinter die Ebene zuschneiden und anhängen.
|
||||
let mut push = |faces: &mut Vec<hlr::Face>, world: &[[f64; 3]], normal: [f64; 3], owner: u32, smooth: u32, two_sided: bool| {
|
||||
let pts: Vec<[f64; 3]> = world.iter().map(|&w| view(w)).collect();
|
||||
if pts.iter().all(|q| q[2] <= 0.0) {
|
||||
return;
|
||||
}
|
||||
let Some((pts, no_edge)) = hlr::clip_front(&pts) else { return };
|
||||
let mut f = hlr::Face::new(pts, [dot(normal, u), normal[1], dot(normal, n)], owner);
|
||||
let (pts, no_edge) = if clip {
|
||||
if pts.iter().all(|q| q[2] <= 0.0) {
|
||||
return;
|
||||
}
|
||||
let Some(x) = hlr::clip_front(&pts) else { return };
|
||||
x
|
||||
} else {
|
||||
(pts, Vec::new())
|
||||
};
|
||||
let mut f = hlr::Face::new(pts, view_normal(normal), owner);
|
||||
f.no_edge = no_edge;
|
||||
f.smooth = smooth;
|
||||
f.two_sided = two_sided;
|
||||
@@ -221,19 +221,47 @@ pub(super) fn projection_edges(p: &Project, plane: &Plane, walls_r: &[RWall], wi
|
||||
}
|
||||
// [152] Importierte Netze hinter der Ebene (Hüllbox vorgefiltert): Facetten innerhalb des Knickwinkels
|
||||
// glätten (eine Gruppe je Netz), offene Netze beidseitig.
|
||||
let (base, um) = (plane.base(), plane.u_model());
|
||||
for (k, m) in meshes.iter().enumerate() {
|
||||
let (lo, hi) = mesh_depth_range(m, base, um);
|
||||
if !(hi > 0.0) || max_depth.is_some_and(|d| d > 0.0 && lo > d + 1e-6) {
|
||||
if !mesh_keep(m) {
|
||||
continue;
|
||||
}
|
||||
owners.push((Kind::Mesh, k));
|
||||
let owner = owners.len() as u32 - 1;
|
||||
crate::mesh_view::hlr_faces(m, &|q| view([q[0], q[2], q[1]]), owner, group, true, &mut faces);
|
||||
crate::mesh_view::hlr_faces(m, &|q| view([q[0], q[2], q[1]]), owner, group, clip, &mut faces);
|
||||
group += 1;
|
||||
}
|
||||
// [180] Bauteile ausgeblendeter Klassen: weder Kanten noch Verdecker.
|
||||
faces.retain(|f| owners.get(f.owner as usize).is_none_or(|&(k, i)| !skip(k, i)));
|
||||
ViewFaces { faces, owners, rail_owners }
|
||||
}
|
||||
|
||||
/// Ansichtskanten hinter der Schnittebene mit exakter Sichtbarkeit ([G4], `hlr.rs`; verdeckte nur mit
|
||||
/// `hidden`, wie `hiddenLines` der Ebene): die Körper als
|
||||
/// Dreiecke (Wände samt Gehrung und Löchern wie im 3D-Modell, Platten, Treppen, Dächer, Körper),
|
||||
/// auf die Seite hinter der Ebene zugeschnitten; die Schnittflächen verdecken in Tiefe 0. Bogenwände,
|
||||
/// verschnittene Dächer und Körper glätten ihre Facetten (keine Fugen, nur Knicke und Silhouetten).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn projection_edges(p: &Project, plane: &Plane, walls_r: &[RWall], wi: &[render3d::WallInput], slabs_r: &[RSlab], bodies: &[&BodyMesh], meshes: &[crate::mesh_view::MeshRef], cuts: &[Cut], hidden: bool, max_depth: Option<f64>, strip: &[[f64; 3]], skip: &dyn Fn(Kind, usize) -> bool) -> (Vec<Edge>, Vec<Edge>) {
|
||||
use crate::hlr;
|
||||
let nl = crate::jsmath::hypot(&plane.normal);
|
||||
if !(nl > 1e-12) {
|
||||
return (Vec::new(), Vec::new());
|
||||
}
|
||||
let n = [plane.normal[0] / nl, plane.normal[1] / nl, plane.normal[2] / nl];
|
||||
let ul = hypot2(n[2], n[0]);
|
||||
let u = if ul > 1e-12 { [n[2] / ul, 0.0, -n[0] / ul] } else { [1.0, 0.0, 0.0] };
|
||||
let o = plane.point;
|
||||
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
let view = |w: [f64; 3]| {
|
||||
let r = [w[0] - o[0], w[1] - o[1], w[2] - o[2]];
|
||||
[dot(r, u), w[1], dot(r, n)]
|
||||
};
|
||||
let mesh_keep = |m: &crate::mesh_view::MeshRef| {
|
||||
let (lo, hi) = mesh_depth_range(m, plane.base(), plane.u_model());
|
||||
hi > 0.0 && !max_depth.is_some_and(|d| d > 0.0 && lo > d + 1e-6)
|
||||
};
|
||||
let view_normal = |normal: [f64; 3]| [dot(normal, u), normal[1], dot(normal, n)];
|
||||
let ViewFaces { mut faces, owners, rail_owners } = view_faces(p, &view, &view_normal, true, walls_r, wi, slabs_r, bodies, meshes, &mesh_keep, skip);
|
||||
// [176] Segment eines geknickten Schnitts: nur, was in seinem Streifen liegt (Winkelhalbierende).
|
||||
if !strip.is_empty() {
|
||||
faces = faces.into_iter().filter_map(|f| super::unfold::clip_face(f, strip)).collect();
|
||||
@@ -271,3 +299,56 @@ pub(super) fn projection_edges(p: &Project, plane: &Plane, walls_r: &[RWall], wi
|
||||
}
|
||||
(visible, hidden)
|
||||
}
|
||||
|
||||
/// [266] Besitzer einer Fläche aus [`model_view_faces`]: Art und Element-Id (für die Auswahl im Plan).
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct OwnerRef {
|
||||
pub kind: Kind,
|
||||
pub id: Option<String>,
|
||||
/// Treppe (Stufen, Wangen, Geländer) bzw. Stütze statt Decke, wenn `kind` = `Slab`.
|
||||
pub stair: bool,
|
||||
pub column: bool,
|
||||
}
|
||||
|
||||
/// [266] Alle Flächen des Modells für eine beliebige Ansicht (Vektor-Axonometrie, `plan/axo.rs`): dieselben Körper wie
|
||||
/// die Projektion des Schnitts ([`view_faces`]), ohne Zuschnitt; Bauteile ausgeblendeter Klassen entfallen ([180]),
|
||||
/// Abzugskörper ebenso (sie sind in den Wänden schon ausgespart). `meshes`: importierte Netze (Kontext) mitnehmen.
|
||||
pub(crate) fn model_view_faces(p: &Project, vis: &Visibility, view: &dyn Fn([f64; 3]) -> [f64; 3], view_normal: &dyn Fn([f64; 3]) -> [f64; 3], meshes: bool) -> Result<(ViewFaces, Vec<OwnerRef>), String> {
|
||||
let walls_r = model3d::emit_walls_with(p, false, false)?;
|
||||
let mut slabs_r = model3d::emit_slabs(p);
|
||||
slabs_r.extend(model3d::emit_stairs(p, true));
|
||||
slabs_r.extend(model3d::column_slabs(p));
|
||||
let wi: Vec<render3d::WallInput> = walls_r.iter().map(wall_input).collect();
|
||||
let walls = wall_owners(p, &walls_r);
|
||||
let slabs = slab_owners(p, &slabs_r);
|
||||
let cats = edge_categories(p, &walls, &slabs);
|
||||
let shown = |c: &str| vis.visible(c) && vis.render(c);
|
||||
let skip = |k: Kind, i: usize| cats.get(&(k, i)).is_some_and(|c| !shown(c));
|
||||
let all = crate::solid_mesh::body_meshes(p);
|
||||
let bodies: Vec<&BodyMesh> = all.iter().filter(|b| !is_subtract_body(p, b) && !skip(Kind::Body, b.index)).collect();
|
||||
let mut mrefs = if meshes { crate::mesh_view::meshes(p) } else { Vec::new() };
|
||||
mrefs.retain(|m| shown(&m.mesh.category_code));
|
||||
let vf = view_faces(p, view, view_normal, false, &walls_r, &wi, &slabs_r, &bodies, &mrefs, &|_| true, &skip);
|
||||
let roofs = p.roofs.as_deref().unwrap_or(&[]);
|
||||
let solids = p.extruded_solids.as_deref().unwrap_or(&[]);
|
||||
let refs = vf
|
||||
.owners
|
||||
.iter()
|
||||
.map(|&(kind, i)| {
|
||||
let (id, stair, column) = match kind {
|
||||
Kind::Wall => (walls_r.get(i).map(|w| w.wall_id.clone()), false, false),
|
||||
Kind::Slab => match slabs.get(i) {
|
||||
Some(SlabOwner::Ceiling(c, _)) => (Some(c.id.clone()), false, false),
|
||||
Some(SlabOwner::Stair(s)) => (Some(s.id.clone()), true, false),
|
||||
Some(SlabOwner::Column(c)) => (Some(c.id.clone()), false, true),
|
||||
_ => (None, false, false),
|
||||
},
|
||||
Kind::Roof => (roofs.get(i).map(|r| r.id.clone()), false, false),
|
||||
Kind::Body => (solids.get(i).map(|s| s.id.clone()), false, false),
|
||||
Kind::Mesh => (mrefs.get(i).map(|m| m.mesh.id.clone()), false, false),
|
||||
};
|
||||
OwnerRef { kind, id, stair, column }
|
||||
})
|
||||
.collect();
|
||||
Ok((vf, refs))
|
||||
}
|
||||
@@ -43,7 +43,7 @@ pub(super) fn subtract_voids_in_section(cuts: Vec<Cut>, p: &Project, base: (f64,
|
||||
}
|
||||
|
||||
/// [G1] Ob ein Körper-Netz zu einem Abzugskörper gehört.
|
||||
pub(super) fn is_subtract_body(p: &Project, b: &BodyMesh) -> bool {
|
||||
pub(crate) fn is_subtract_body(p: &Project, b: &BodyMesh) -> bool {
|
||||
p.extruded_solids.as_deref().and_then(|s| s.get(b.index)).is_some_and(|s| s.operation.as_deref() == Some("subtract"))
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user