[K3a][K3d][K4] generatePlan ganz im Kern: Schatten, Baurecht, Abzugskörper, Mono, Strichstärken
core/src/plan/extras.rs rechnet Schattenstudie und Baurecht (unterste
Gruppe, Verstösse zuoberst), zieht Abzugskörper von Wand-/Stützen-/
Decken-Poché ab, setzt Schwarz-Weiss und Strichstärken nach Massstab
beim Schreiben (Writer::post, auch drawingLines) und das Ausmass samt
Kontext. planDomains liefert 12 Gruppen; generatePlan reicht nur noch
Sichtbarkeit und Optionen weiter, der Plan bleibt immer lazy aus
Kern-Puffern. Gelöscht: generatePlan/{sunShadow,siteRules}.ts,
lineWeightScale.ts, subtractVoidsInPlan/segmentOutside (samt Bindung),
toMono, computeBounds, realignRuns.
Gleichheit: temporärer Test (gelöscht) 481 000 Primitive Feld für Feld
gegen die alte TS-Fassung (Beispiel alle Ebenen, bigSample, 120
Zufallsprojekte mit Schatten/Baurecht/Abzugskörpern/Mono/Massstab,
Kataster); CLI byte-gleich zum Stand vor beiden Schritten (96 Ausgaben).
generatePlan unverändert mit Studie/Baurecht/40 Abzugskörpern 237 ->
2,3 ms. geomTransform bleibt in TS (Begründung in TODO.md). Nicht in der
Tauri-App angesehen.
Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
21 files changed
+769
-491
No files matched your search
@@ -333,6 +333,26 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
|
||||
20k Linien 31 → 6 ms / 63 → 7 ms; Kataster 150k 533 → 59 ms / 862 → 39 ms; Plan + WASM-Renderer nach Änderung katbig 90 →
|
||||
38 ms, Kataster 1,8 → 0,6 s. Erstes Öffnen 200 000 Zeichnungen (`doc_open`) 9,6 → 1,8 s, Speicher 953 → 840 MB.
|
||||
Nicht in der Tauri-App/im nativen Renderer angesehen.
|
||||
✅ (29.10.) **`generatePlan` ganz im Kern** ([K3a]/[K3d]/[K4]): `core/src/plan/extras.rs` rechnet Schattenstudie und Baurecht
|
||||
(unterste Gruppe; Verstösse zuoberst), Abzugskörper (aus Wand-/Stützen-/Decken-Poché, über dieselben flachen Funktionen wie
|
||||
vorher), Schwarz-Weiss und Strichstärken nach Massstab (beim Schreiben, `plan_buf::Writer::post`, auch für die kompakte
|
||||
Unterlage `drawingLines`) und das Ausmass samt Kontext. `planDomains` liefert 12 Gruppen; `generatePlan` reicht nur noch
|
||||
Sichtbarkeit, Optionen und den Zeitpunkt der Studie (`Date` in TS: Ortszeit wie bisher) weiter — der Plan bleibt immer lazy
|
||||
und aus Kern-Puffern (auch mit Mono/Abzugskörpern/Massstab: GPU-Chunks aus dem Puffer, Stücke wiederverwendet). Gelöscht:
|
||||
`generatePlan/{sunShadow,siteRules}.ts`, `lineWeightScale.ts`, `subtractVoidsInPlan`/`segmentOutside` (samt Bindung
|
||||
`voids_segment_outside_flat`), `toMono`, `computeBounds`, `realignRuns`. Gleichheit (temporärer Test, gelöscht): 481 000
|
||||
Primitive Feld für Feld (Zahlen per `Object.is`) samt Ausmass, Luftbildern, gedimmten Bereichen und Unterlage gegen die alte
|
||||
TS-Fassung: Beispielprojekt alle Ebenen × 180 Varianten (Detail, Mono, global, Massstab 1:20–1:500, Druck, kompakt, Sichtbarkeit/
|
||||
Dimmen zufällig, mit/ohne Studie und Strichstärken-Option), bigSample, 120 Zufallsprojekte mit Abzugskörpern, Stützen, Schatten
|
||||
(auch ungültige Zeitpunkte, LV95-Anker), Baurecht (Baulinien, Höhe, `show: false`), Kontext; Kataster 30 000 Zeichnungen;
|
||||
`generateVisibleLevelsPlan` stichprobenweise. CLI byte-gleich zum Stand vor beiden Schritten (96 Ausgaben: `plan` SVG 1:100/1:50,
|
||||
JSON 1:100/1:200, `dxf` 1:100/1:50 für 16 Projekte, davon 7 mit Schatten/Baurecht/Abzugskörpern/Strichstärken). Messung
|
||||
(CLI `bench`, unverändertes Projekt): 36 Häuser mit 40 Abzugskörpern, Studie und Baurecht 237 → 2,3 ms, Beispiel mit
|
||||
Abzugskörpern 9 → 0,4 ms. Nicht in der Tauri-App angesehen.
|
||||
Bleibt: `geometry/geomTransform.ts` (`mvGeom`/`scaleGeom`) in TS — die Werkzeuge (Verschieben/Drehen/Skalieren mit
|
||||
Vorschau je Mausschritt, Ausrichten, Block definieren, Griffe) bilden mit Funktionen ab, die zwar affin sind, aber je Element
|
||||
und Frame aufgerufen werden; über die Grenze müsste jede Zeichnungsform (18 Varianten) flach hin und zurück — das lohnt erst,
|
||||
wenn die Werkzeuge selbst im Kern laufen ([K4] S3). Der Kern hat seine Fassung für Blöcke (`plan/drawings.rs::mv_geom`).
|
||||
- ◐ **S3 Änderungen kommen aus Rust**: Befehle (Zustandsautomaten, Werkzeuge) erzeugen Ops im Kern; Undo/Redo, Validierung
|
||||
(`validateOps`) und Gruppen/Ebenen-Logik wandern nach Rust; `diffToOps` entfällt, TS hält nur noch eine Leseansicht.
|
||||
**Erste Etappe (28.10.): Ops, Prüfung, Undo/Redo im Kern.** `core/src/ops.rs` (Op, Prüfung bitgleich zur TS-Fassung — gleiche
|
||||
|
||||
@@ -77,9 +77,11 @@ pub struct DrawCache {
|
||||
pub struct RestEntry {
|
||||
/// (Stand aller Felder ausser [`NOT_FOR_REST`], Sichtbarkeit/Dimmen).
|
||||
pub sig: (u64, String),
|
||||
/// Abschnitte in Puffer-Reihenfolge ohne die Zeichnungen.
|
||||
/// Abschnitte in Puffer-Reihenfolge ohne die Zeichnungen (Zutaten unten, Domänen, Verstösse).
|
||||
pub groups: Vec<Segment>,
|
||||
pub bounds: [f64; 4],
|
||||
/// Ausmass der Zutaten (Schatten, Baurecht, Kontext), s. `extras::extra_bounds`.
|
||||
pub extra: [f64; 4],
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -130,7 +132,7 @@ impl Clone for PlanCache {
|
||||
|
||||
/// Schlüssel eines Argument-Satzes ohne Sichtbarkeit/Dimmen (die wirken je Element).
|
||||
pub fn ctx_key(a: &PlanArgs) -> String {
|
||||
format!("{}\u{1}{:?}\u{1}{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}", a.floor, a.detail, a.reference_lines, a.global, a.scale.to_bits(), a.for_print, a.compact)
|
||||
format!("{}\u{1}{:?}\u{1}{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}\u{1}{}", a.floor, a.detail, a.reference_lines, a.global, a.scale.to_bits(), a.for_print, a.compact, a.mono)
|
||||
}
|
||||
|
||||
/// Sichtbarkeit und Dimmen als vergleichbarer Text (Mengen sortiert).
|
||||
@@ -210,10 +212,12 @@ pub(crate) mod tests {
|
||||
pub(crate) fn assembled(out: &PlanOut, store: &mut HashMap<u64, Vec<u8>>) -> (String, Vec<f64>, Vec<bool>, Option<[f64; 4]>) {
|
||||
let v = View::parse(&out.main).unwrap();
|
||||
let g = v.groups().unwrap();
|
||||
assert_eq!(g.len(), 10);
|
||||
assert_eq!(g[6].0, g[6].1, "Gruppe 6 im Haupt-Puffer leer");
|
||||
// Gruppe der Zeichnungen (nach Schatten/Baurecht und Decken … Stützen).
|
||||
assert_eq!(g.len(), 12);
|
||||
let dg = 7;
|
||||
assert_eq!(g[dg].0, g[dg].1, "Gruppe der Zeichnungen im Haupt-Puffer leer");
|
||||
let mut o = (vec![], vec![], vec![]);
|
||||
range(&out.main, 0, g[6].0, &mut o);
|
||||
range(&out.main, 0, g[dg].0, &mut o);
|
||||
let mut next = HashMap::new();
|
||||
for (k, b) in &out.chunks {
|
||||
let bytes = b.clone().unwrap_or_else(|| store.get(k).expect("Stück fehlt beim Aufrufer").clone());
|
||||
@@ -221,7 +225,7 @@ pub(crate) mod tests {
|
||||
range(&bytes, 0, n, &mut o);
|
||||
next.insert(*k, bytes);
|
||||
}
|
||||
range(&out.main, g[7].0, v.len(), &mut o);
|
||||
range(&out.main, g[dg + 1].0, v.len(), &mut o);
|
||||
*store = next;
|
||||
(serde_json::to_string(&o.0).unwrap(), o.1, o.2, v.bounds())
|
||||
}
|
||||
@@ -306,6 +310,8 @@ pub(crate) mod tests {
|
||||
"referenceLines": r.next() < 0.3, "global": r.next() < 0.7,
|
||||
"scale": ([100.0, 50.0, 200.0][r.below(3)]),
|
||||
"forPrint": r.next() < 0.2, "compact": r.next() < 0.4,
|
||||
"mono": r.next() < 0.25,
|
||||
"sunWhen": (if r.next() < 0.7 { json!(1_750_000_000_000.0 + r.next() * 3e10) } else { Value::Null }),
|
||||
});
|
||||
PlanArgs::parse([0.0, 1.0, 2.0][r.below(3)], &t.to_string()).unwrap()
|
||||
}
|
||||
@@ -317,6 +323,17 @@ pub(crate) mod tests {
|
||||
base["blockDefs"] = json!([{"id": "blk", "name": "B", "geom2d": [
|
||||
{"shape": "line", "a": {"x": 0, "y": 0}, "b": {"x": 1, "y": 0}},
|
||||
{"shape": "circle", "center": {"x": 0, "y": 0}, "r": 0.3}]}]);
|
||||
// Abzugskörper durch Wand und Decke, Schattenstudie, Baurecht, Strichstärken nach Massstab.
|
||||
base["extrudedSolids"] = json!([
|
||||
{"id": "v1", "type": "extrudedSolid", "levelId": "eg", "operation": "subtract", "height": 3,
|
||||
"points": [{"x": 1, "y": -0.5}, {"x": 1.4, "y": -0.5}, {"x": 1.4, "y": 0.5}, {"x": 1, "y": 0.5}]},
|
||||
{"id": "v2", "type": "extrudedSolid", "levelId": "eg", "operation": "subtract", "height": 0.5, "baseOffset": 2.6,
|
||||
"points": [{"x": 3, "y": 1}, {"x": 3.6, "y": 1}, {"x": 3.6, "y": 2}, {"x": 3, "y": 2}]},
|
||||
{"id": "s1", "type": "extrudedSolid", "levelId": "eg", "height": 2,
|
||||
"points": [{"x": 7, "y": 0}, {"x": 9, "y": 0}, {"x": 9, "y": 2}, {"x": 7, "y": 2}]}]);
|
||||
base["sunStudy"] = json!({"when": "2026-06-21T12:00:00Z", "show": true});
|
||||
base["siteRules"] = json!({"parcel": [{"x": -3, "y": -3}, {"x": 8, "y": -3}, {"x": 8, "y": 7}, {"x": -3, "y": 7}], "defaultSetback": 2.5});
|
||||
base["scaleLineWeights"] = json!(r.next() < 0.5);
|
||||
Document::from_json(&base.to_string()).unwrap()
|
||||
}
|
||||
|
||||
|
||||
@@ -43,11 +43,16 @@ pub struct PlanArgs {
|
||||
pub for_print: bool,
|
||||
/// Kompakte Linien-Unterlage: Linien der einfachen Zeichnungen entstehen bei Bedarf (`drawings.rs`).
|
||||
pub compact: bool,
|
||||
/// Schwarz-Weiss (`extras.rs`).
|
||||
pub mono: bool,
|
||||
/// Zeitpunkt der Schattenstudie (Unix-ms; fehlt/ungültig = kein Schatten).
|
||||
pub sun_when: Option<f64>,
|
||||
}
|
||||
|
||||
impl PlanArgs {
|
||||
/// `detail`: 0 grob, 1 mittel, 2 fein; `text`: `{"floor": id, "show": [code…], "grey": [code…],
|
||||
/// "referenceLines": bool, "global": bool, "scale": N, "forPrint": bool, "compact": bool}`.
|
||||
/// "referenceLines": bool, "global": bool, "scale": N, "forPrint": bool, "compact": bool,
|
||||
/// "mono": bool, "sunWhen": ms | null}`.
|
||||
pub fn parse(detail: f64, text: &str) -> Result<PlanArgs, String> {
|
||||
let v: serde_json::Value = serde_json::from_str(text).map_err(|e| format!("Plan-Argumente: {e}"))?;
|
||||
let set = |k: &str| -> HashSet<String> { v.get(k).and_then(|a| a.as_array()).map(|a| a.iter().filter_map(|s| s.as_str().map(String::from)).collect()).unwrap_or_default() };
|
||||
@@ -65,6 +70,8 @@ impl PlanArgs {
|
||||
scale: v.get("scale").and_then(|b| b.as_f64()).unwrap_or(super::drawings::DEFAULT_SCALE_DENOMINATOR),
|
||||
for_print: v.get("forPrint").and_then(|b| b.as_bool()).unwrap_or(false),
|
||||
compact: v.get("compact").and_then(|b| b.as_bool()).unwrap_or(false),
|
||||
mono: v.get("mono").and_then(|b| b.as_bool()).unwrap_or(false),
|
||||
sun_when: v.get("sunWhen").and_then(|b| b.as_f64()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -140,7 +147,7 @@ impl Bounds {
|
||||
b[2] = max(b[2], x);
|
||||
b[3] = max(b[3], y);
|
||||
}
|
||||
fn get(&self) -> Option<[f64; 4]> {
|
||||
pub(crate) fn get(&self) -> Option<[f64; 4]> {
|
||||
self.0[0].is_finite().then_some(self.0)
|
||||
}
|
||||
/// Rohwerte (auch ohne Punkte), s. [`Bounds::merge`].
|
||||
@@ -562,8 +569,9 @@ fn domains_after(c: &Ctx, out: &mut DomainPrims) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reihenfolge der Gruppen im Plan-Puffer der Abfrage `planDomains`.
|
||||
pub const GROUPS: [&str; 10] = ["ceilings", "roofs", "rooms", "walls", "stairs", "columns", "drawings", "solids", "context", "sections"];
|
||||
/// Reihenfolge der Gruppen im Plan-Puffer der Abfrage `planDomains`: Schatten und Baurecht
|
||||
/// zuunterst, die Domänen, die Baurechts-Verstösse zuoberst (`extras.rs`).
|
||||
pub const GROUPS: [&str; 12] = ["under", "ceilings", "roofs", "rooms", "walls", "stairs", "columns", "drawings", "solids", "context", "sections", "violations"];
|
||||
|
||||
/// Abfrage `planDomains` als Plan-Puffer v2 (s. `plan_buf.rs`): eine Gruppe je Domäne in der
|
||||
/// Reihenfolge [`GROUPS`], Ausmass im Kopf, Inhalts-Hashes für den GPU-Chunk-Cache. Die
|
||||
@@ -574,6 +582,10 @@ pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result<Vec<u8>, String> {
|
||||
let mut bounds = Bounds::new();
|
||||
domains_before(&c, &mut d, &mut bounds)?;
|
||||
let mut w = crate::plan_buf::Writer::new(true);
|
||||
w.post = super::extras::post_for(p, a);
|
||||
let (under, violations) = extras_of(p, a);
|
||||
group_refs(&mut w, &under);
|
||||
apply_voids(p, a, &mut d);
|
||||
for g in [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns] {
|
||||
w.group(g);
|
||||
}
|
||||
@@ -581,13 +593,42 @@ pub fn plan_domains_buf(p: &Project, a: &PlanArgs) -> Result<Vec<u8>, String> {
|
||||
super::drawings::plan_drawings(&c, &mut super::drawings::Sink::new(super::drawings::Target::Buf(&mut w), super::drawings::Keep::All), &mut bounds)?;
|
||||
w.end_group(start);
|
||||
domains_after(&c, &mut d);
|
||||
apply_voids(p, a, &mut d);
|
||||
for g in [&d.solids, &d.context, &d.sections] {
|
||||
w.group(g);
|
||||
}
|
||||
w.bounds = bounds.get();
|
||||
w.group(&violations);
|
||||
w.bounds = Some(super::extras::plan_bounds(&bounds, &super::extras::extra_bounds(p, &under)));
|
||||
Ok(w.finish())
|
||||
}
|
||||
|
||||
/// Schatten/Baurecht (unterste Gruppe, mit Strichmuster-Kennungen) und Verstösse (oberste); nur
|
||||
/// beim projektglobalen Aufruf (`global`).
|
||||
fn extras_of(p: &Project, a: &PlanArgs) -> (Vec<(Primitive, u32)>, Vec<Primitive>) {
|
||||
if a.global {
|
||||
super::extras::site_and_shadow(p, &a.floor, a.sun_when)
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// Eine Gruppe aus Primitiven mit Strichmuster-Kennung.
|
||||
fn group_refs(w: &mut crate::plan_buf::Writer, prims: &[(Primitive, u32)]) {
|
||||
let start = w.begin_group();
|
||||
for (q, r) in prims {
|
||||
w.push_ref(q, *r);
|
||||
}
|
||||
w.end_group(start);
|
||||
}
|
||||
|
||||
/// Abzugskörper von allen Domänen-Listen abziehen (`extras::subtract_voids`).
|
||||
fn apply_voids(p: &Project, a: &PlanArgs, d: &mut DomainPrims) {
|
||||
let z = super::extras::cut_z(p, &a.floor);
|
||||
for g in [&mut d.ceilings, &mut d.roofs, &mut d.rooms, &mut d.walls, &mut d.stairs, &mut d.columns, &mut d.solids, &mut d.context, &mut d.sections] {
|
||||
*g = super::extras::subtract_voids(std::mem::take(g), p, z);
|
||||
}
|
||||
}
|
||||
|
||||
/// Kennung der Antwort von `planDomains` mit Cache ("PLBm").
|
||||
pub const MULTI_MAGIC: f64 = 1_347_175_021.0;
|
||||
|
||||
@@ -641,6 +682,7 @@ pub fn plan_domains_cached(p: &Project, revs: &crate::document::Revs, cache: &mu
|
||||
}
|
||||
let fresh = cc.tables.units_len() == 0;
|
||||
let mut w = Writer::with_tables(std::mem::take(&mut cc.tables), true);
|
||||
w.post = super::extras::post_for(p, a);
|
||||
let r = assemble_cached(&c, revs, cc, &mut w, have);
|
||||
let (main, tables) = w.finish_keep();
|
||||
cc.tables = tables;
|
||||
@@ -661,28 +703,38 @@ pub fn plan_domains_cached(p: &Project, revs: &crate::document::Revs, cache: &mu
|
||||
/// Cache bzw. neu (dann aufgenommen).
|
||||
fn assemble_cached(c: &Ctx, revs: &crate::document::Revs, cc: &mut super::cache::CtxCache, w: &mut crate::plan_buf::Writer, have: &HashSet<u64>) -> Result<Vec<super::drawings::ChunkOut>, String> {
|
||||
use super::cache::{selection_sig, RestEntry, NOT_FOR_REST};
|
||||
let sig = (revs.max_except(NOT_FOR_REST), selection_sig(c.a));
|
||||
let sig = (revs.max_except(NOT_FOR_REST), format!("{}\u{3}{}", selection_sig(c.a), c.a.sun_when.unwrap_or(f64::NAN).to_bits()));
|
||||
if cc.rest.as_ref().is_some_and(|r| r.sig != sig) {
|
||||
cc.rest = None;
|
||||
}
|
||||
let mut bounds = Bounds::new();
|
||||
let mut fresh: Option<(DomainPrims, Bounds)> = None;
|
||||
// Neu zu erzeugen: Domänen-Listen (mit Strichmuster-Kennung), Ausmass der Domänen und der Zutaten.
|
||||
let mut fresh: Option<(Vec<Vec<(Primitive, u32)>>, Bounds, Bounds)> = None;
|
||||
if cc.rest.is_none() {
|
||||
let mut d = DomainPrims::default();
|
||||
let mut b = Bounds::new();
|
||||
domains_before(c, &mut d, &mut b)?;
|
||||
domains_after(c, &mut d);
|
||||
fresh = Some((d, b));
|
||||
let (under, violations) = extras_of(c.p, c.a);
|
||||
let extra = super::extras::extra_bounds(c.p, &under);
|
||||
apply_voids(c.p, c.a, &mut d);
|
||||
let plain = |g: Vec<Primitive>| g.into_iter().map(|q| (q, 0)).collect::<Vec<_>>();
|
||||
let mut lists = vec![under];
|
||||
for g in [d.ceilings, d.roofs, d.rooms, d.walls, d.stairs, d.columns, d.solids, d.context, d.sections] {
|
||||
lists.push(plain(g));
|
||||
}
|
||||
lists.push(plain(violations));
|
||||
fresh = Some((lists, b, extra));
|
||||
}
|
||||
let mut segs: Vec<crate::plan_buf::Segment> = Vec::new();
|
||||
// Liste `k`: 0 Schatten/Baurecht, 1–9 Domänen (ohne Zeichnungen), 10 Verstösse.
|
||||
let put = |w: &mut crate::plan_buf::Writer, k: usize, segs: &mut Vec<crate::plan_buf::Segment>| {
|
||||
let start = w.begin_group();
|
||||
match (&fresh, &cc.rest) {
|
||||
(Some((d, _)), _) => {
|
||||
let g = [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.solids, &d.context, &d.sections][k];
|
||||
(Some((lists, _, _)), _) => {
|
||||
w.mark();
|
||||
for x in g.iter() {
|
||||
w.push(x);
|
||||
for (x, r) in lists[k].iter() {
|
||||
w.push_ref(x, *r);
|
||||
}
|
||||
segs.push(w.take_segment());
|
||||
}
|
||||
@@ -691,7 +743,7 @@ fn assemble_cached(c: &Ctx, revs: &crate::document::Revs, cc: &mut super::cache:
|
||||
}
|
||||
w.end_group(start);
|
||||
};
|
||||
for k in 0..6 {
|
||||
for k in 0..7 {
|
||||
put(w, k, &mut segs);
|
||||
}
|
||||
// Gruppe 6 bleibt im Haupt-Puffer leer; die Zeichnungen kommen als Stücke.
|
||||
@@ -705,17 +757,24 @@ fn assemble_cached(c: &Ctx, revs: &crate::document::Revs, cc: &mut super::cache:
|
||||
h ^ cc.drawings.sig.wrapping_mul(0xff51_afd7_ed55_8ccd)
|
||||
};
|
||||
let chunks = super::drawings::plan_drawings_chunked(c, revs.item_stamps("drawings2d").unwrap_or(&[]), &mut cc.drawings, salt, have, &mut bounds)?;
|
||||
for k in 6..9 {
|
||||
for k in 7..11 {
|
||||
put(w, k, &mut segs);
|
||||
}
|
||||
match fresh {
|
||||
Some((_, b)) => {
|
||||
let extra = match fresh {
|
||||
Some((_, b, extra)) => {
|
||||
bounds.merge(b.raw());
|
||||
cc.rest = Some(RestEntry { sig, groups: segs, bounds: b.raw() });
|
||||
cc.rest = Some(RestEntry { sig, groups: segs, bounds: b.raw(), extra: extra.raw() });
|
||||
extra.raw()
|
||||
}
|
||||
None => bounds.merge(cc.rest.as_ref().map_or(Bounds::new().raw(), |r| r.bounds)),
|
||||
}
|
||||
w.bounds = bounds.get();
|
||||
None => {
|
||||
let r = cc.rest.as_ref().expect("Cache vorhanden");
|
||||
bounds.merge(r.bounds);
|
||||
r.extra
|
||||
}
|
||||
};
|
||||
let mut e = Bounds::new();
|
||||
e.merge(extra);
|
||||
w.bounds = Some(super::extras::plan_bounds(&bounds, &e));
|
||||
Ok(chunks)
|
||||
}
|
||||
|
||||
@@ -756,11 +815,15 @@ mod tests {
|
||||
let (prims, groups, bounds) = crate::plan_buf::decode(&buf).unwrap();
|
||||
assert_eq!(groups.len(), GROUPS.len());
|
||||
let lists = [&d.ceilings, &d.roofs, &d.rooms, &d.walls, &d.stairs, &d.columns, &d.drawings.prims, &d.solids, &d.context, &d.sections];
|
||||
for ((a, b), l) in groups.iter().zip(lists) {
|
||||
for ((a, b), l) in groups[1..11].iter().zip(lists) {
|
||||
assert_eq!(serde_json::to_string(&prims[*a..*b]).unwrap(), serde_json::to_string(l).unwrap());
|
||||
}
|
||||
assert!(groups[0].0 == groups[0].1 && groups[11].0 == groups[11].1, "ohne Studie und Baurecht leer");
|
||||
assert!(!d.walls.is_empty() && !d.rooms.is_empty());
|
||||
assert_eq!(bounds, d.bounds);
|
||||
// Ausmass: Domänen und Kontext.
|
||||
let mut db = Bounds::new();
|
||||
db.merge(d.bounds.unwrap());
|
||||
assert_eq!(bounds, Some(super::super::extras::plan_bounds(&db, &super::super::extras::extra_bounds(&p, &[]))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -1228,6 +1228,7 @@ fn build_chunk<'a>(
|
||||
let base_key = part.iter().find_map(|(_, s, _)| owner.get(s).copied());
|
||||
let base = base_key.and_then(|k| old.get(&k).or_else(|| new.get(&k)));
|
||||
let mut w = Writer::with_tables(base.map_or_else(Default::default, |b| b.tables.clone()), true);
|
||||
w.post = super::extras::post_for(c.p, c.a);
|
||||
let g = w.begin_group();
|
||||
w.begin_kept();
|
||||
if let Some(b) = base {
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
//! Grundriss-Zutaten rund um die Domänen ([K3a]/[K4]): Schattenstudie und Baurecht (zuunterst; die
|
||||
//! Verstösse zuoberst), Abzugskörper (aus Wand-, Stützen- und Decken-Poché), Schwarz-Weiss und
|
||||
//! Strichstärken nach Massstab sowie das Ausmass des Plans — früher in TS
|
||||
//! (`generatePlan/{sunShadow,siteRules}.ts`, `voids.ts::subtractVoidsInPlan`, `toMono`,
|
||||
//! `lineWeightScale.ts`, `computeBounds`). Rechenreihenfolge wie dort.
|
||||
|
||||
use super::domains::Bounds;
|
||||
use super::prim::{HatchRender, Primitive};
|
||||
use super::style::*;
|
||||
use crate::jsnum;
|
||||
use crate::model::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Füllfarbe der Schattenflächen.
|
||||
pub const SUN_SHADOW_FILL: &str = "#3a4a66";
|
||||
const SUN_SHADOW_OPACITY: f64 = 0.28;
|
||||
/// Linien-Klassen und Füllfarbe des Baurechts.
|
||||
pub const SITE_PARCEL_CLS: &str = "site-parcel";
|
||||
pub const SITE_ALLOWED_CLS: &str = "site-allowed";
|
||||
pub const SITE_VIOLATION_FILL: &str = "#d0342c";
|
||||
const SITE_VIOLATION_OPACITY: f64 = 0.45;
|
||||
const PARCEL_COLOR: &str = "#1f6f3f";
|
||||
const ALLOWED_COLOR: &str = "#2b5fae";
|
||||
const PARCEL_DASH: [f64; 4] = [6.0, 1.5, 0.5, 1.5];
|
||||
const ALLOWED_DASH: [f64; 2] = [2.0, 1.0];
|
||||
|
||||
/// Geschoss, auf dem Boden-Schatten und Baurecht erscheinen: Basishöhe am nächsten bei 0 (das erste
|
||||
/// bei Gleichstand).
|
||||
pub fn ground_floor_id(p: &Project) -> Option<&str> {
|
||||
let mut best: Option<(&str, f64)> = None;
|
||||
for l in &p.drawing_levels {
|
||||
if l.kind != DrawingLevelKind::Floor {
|
||||
continue;
|
||||
}
|
||||
let d = l.base_elevation.unwrap_or(0.0).abs();
|
||||
if best.is_none_or(|b| d < b.1) {
|
||||
best = Some((&l.id, d));
|
||||
}
|
||||
}
|
||||
best.map(|b| b.0)
|
||||
}
|
||||
|
||||
/// Fläche ohne Strich, mit Deckkraft (Schatten, Baurechts-Verstoss).
|
||||
fn flat_polygon(pts: Vec<Vec2>, fill: &str, opacity: f64) -> Primitive {
|
||||
Primitive::Polygon {
|
||||
pts,
|
||||
fill: fill.into(),
|
||||
stroke: "none".into(),
|
||||
stroke_width_mm: 0.0,
|
||||
hatch: no_hatch(),
|
||||
greyed: None,
|
||||
opacity: Some(opacity),
|
||||
no_stroke_edges: None,
|
||||
wall_id: None,
|
||||
drawing_id: None,
|
||||
ceiling_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
room_id: None,
|
||||
extruded_solid_id: None,
|
||||
context_object_id: None,
|
||||
column_id: None,
|
||||
roof_id: None,
|
||||
section_line_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ring_pts(r: &[[f64; 2]]) -> Vec<Vec2> {
|
||||
r.iter().map(|q| Vec2 { x: q[0], y: q[1] }).collect()
|
||||
}
|
||||
|
||||
/// Breite/Länge des Projekts aus `geoAnchor` (LV95), sonst Zürich.
|
||||
fn project_lat_lon(p: &Project) -> (f64, f64) {
|
||||
match &p.geo_anchor {
|
||||
Some(a) => crate::geo_rebase::lv95_to_wgs84(a.lv95.e, a.lv95.n),
|
||||
None => (47.3769, 8.5417),
|
||||
}
|
||||
}
|
||||
|
||||
/// Boden-Schatten zum Zeitpunkt `when_ms` (Unix-ms der Studie, `None`/NaN = ungültig) als
|
||||
/// halbtransparente Flächen; nur mit sichtbarer Studie und im Geschoss nächst ±0.00.
|
||||
pub fn sun_shadow(p: &Project, floor: &str, when_ms: Option<f64>, out: &mut Vec<Primitive>) {
|
||||
let Some(study) = &p.sun_study else { return };
|
||||
if !study.show || ground_floor_id(p) != Some(floor) {
|
||||
return;
|
||||
}
|
||||
let Some(t) = when_ms.filter(|t| !t.is_nan()) else { return };
|
||||
let (lat, lon) = project_lat_lon(p);
|
||||
let sun = crate::sun::sun_position(lat, lon, t);
|
||||
for poly in crate::sun::shadow_polygons_project(p, sun) {
|
||||
for r in crate::sun::without_holes(&poly) {
|
||||
out.push(flat_polygon(ring_pts(&r), SUN_SHADOW_FILL, SUN_SHADOW_OPACITY));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Baurecht im Geschoss nächst ±0.00 (ohne `show: false`): Prüfung des Modells, `None` ohne
|
||||
/// gültiges Baurecht.
|
||||
fn site_check(p: &Project, floor: &str) -> Option<crate::site_rules::SiteCheckOut> {
|
||||
let rules = p.site_rules.as_ref()?;
|
||||
if rules.show == Some(false) || ground_floor_id(p) != Some(floor) {
|
||||
return None;
|
||||
}
|
||||
crate::site_rules::check_project(p)
|
||||
}
|
||||
|
||||
/// Linien eines geschlossenen Rings (ein Strichmuster je Ring: Linienzug über die Ecken).
|
||||
fn ring_lines(out: &mut Vec<(Primitive, u32)>, pts: &[Vec2], cls: &str, color: &str, w: f64, dash: &[f64], dash_ref: u32) {
|
||||
let n = pts.len();
|
||||
for i in 0..n {
|
||||
let line = Primitive::Line {
|
||||
a: pts[i],
|
||||
b: pts[(i + 1) % n],
|
||||
cls: cls.into(),
|
||||
weight_mm: w,
|
||||
dash: Some(Some(dash.to_vec())),
|
||||
zigzag: None,
|
||||
motif: None,
|
||||
color: Some(color.into()),
|
||||
drawing_id: None,
|
||||
opening_id: None,
|
||||
stair_id: None,
|
||||
greyed: None,
|
||||
opacity: None,
|
||||
};
|
||||
out.push((line, dash_ref));
|
||||
}
|
||||
}
|
||||
|
||||
/// Unterste Gruppe: Schatten, dann Parzellengrenze (Strich-Punkt) und zulässige Fläche
|
||||
/// (gestrichelt); mit Strichmuster-Kennung je Primitiv. Dazu die Verstösse (Gebäude-Grundfläche
|
||||
/// ausserhalb der zulässigen Fläche) für die oberste Gruppe.
|
||||
pub fn site_and_shadow(p: &Project, floor: &str, when_ms: Option<f64>) -> (Vec<(Primitive, u32)>, Vec<Primitive>) {
|
||||
let mut shadow = Vec::new();
|
||||
sun_shadow(p, floor, when_ms, &mut shadow);
|
||||
let mut under: Vec<(Primitive, u32)> = shadow.into_iter().map(|q| (q, 0)).collect();
|
||||
let mut violations = Vec::new();
|
||||
if let (Some(check), Some(rules)) = (site_check(p, floor), p.site_rules.as_ref()) {
|
||||
let mut r = 1;
|
||||
ring_lines(&mut under, &rules.parcel, SITE_PARCEL_CLS, PARCEL_COLOR, 0.35, &PARCEL_DASH, r);
|
||||
for poly in &check.allowed {
|
||||
for ring in poly {
|
||||
r += 1;
|
||||
ring_lines(&mut under, ring, SITE_ALLOWED_CLS, ALLOWED_COLOR, 0.25, &ALLOWED_DASH, r);
|
||||
}
|
||||
}
|
||||
for poly in &check.violations {
|
||||
let rings: Vec<Vec<[f64; 2]>> = poly.iter().map(|r| r.iter().map(|q| [q.x, q.y]).collect()).collect();
|
||||
for ring in crate::sun::without_holes(&rings) {
|
||||
violations.push(flat_polygon(ring_pts(&ring), SITE_VIOLATION_FILL, SITE_VIOLATION_OPACITY));
|
||||
}
|
||||
}
|
||||
}
|
||||
(under, violations)
|
||||
}
|
||||
|
||||
// ── Abzugskörper ────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const EPS: f64 = 1e-7;
|
||||
|
||||
/// Ein Abzugskörper als Prisma (Welt-Höhen).
|
||||
struct VoidPrism {
|
||||
pts: Vec<Vec2>,
|
||||
z0: f64,
|
||||
z1: f64,
|
||||
}
|
||||
|
||||
/// Abzugskörper des Projekts (`voidPrisms`): `operation: "subtract"`, ohne B-Rep, ohne Verjüngung,
|
||||
/// gültiges Profil und Höhe.
|
||||
fn void_prisms(p: &Project) -> Vec<VoidPrism> {
|
||||
let mut out = Vec::new();
|
||||
for s in p.extruded_solids.as_deref().unwrap_or(&[]) {
|
||||
let is_void = s.operation.as_deref() == Some("subtract") && s.brep.is_none() && s.taper.unwrap_or(0.0) < 1e-6 && s.points.len() >= 3 && s.height > 0.0;
|
||||
if !is_void {
|
||||
continue;
|
||||
}
|
||||
let z0 = p.floor(&s.level_id).map_or(0.0, |f| f.base_elevation.unwrap_or(0.0)) + s.base_offset.unwrap_or(0.0);
|
||||
out.push(VoidPrism { pts: s.points.clone(), z0, z1: z0 + s.height });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Ringe flach wie `encodeRings` in TS: `[n, (k, x, y …) × n]`.
|
||||
fn encode_rings(rings: &[&[Vec2]]) -> Vec<f64> {
|
||||
let mut b = vec![rings.len() as f64];
|
||||
for r in rings {
|
||||
b.push(r.len() as f64);
|
||||
for q in r.iter() {
|
||||
b.push(q.x);
|
||||
b.push(q.y);
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// Linien-Klassen der Wand-Poché, die ein Abzugskörper auf Schnitthöhe unterbricht.
|
||||
const WALL_LINE_CLS: [&str; 3] = ["wall-outline", "layer-joint", "layer-joint-l"];
|
||||
|
||||
/// Zieht die Abzugskörper von den Bauteil-Primitiven eines Grundrisses ab (`subtractVoidsInPlan`):
|
||||
/// Wände (Poché und ihre Linien), wenn der Körper die Schnitthöhe `cut_z` durchdringt; Stützen
|
||||
/// ebenso über ihren Höhenbereich; Decken, wenn der Körper die Platte durchdringt. Ohne
|
||||
/// Abzugskörper unverändert. Gleiche Rechnung wie der frühere Weg über die flachen Bindungen.
|
||||
pub fn subtract_voids(prims: Vec<Primitive>, p: &Project, cut_z: f64) -> Vec<Primitive> {
|
||||
let voids = void_prisms(p);
|
||||
if voids.is_empty() {
|
||||
return prims;
|
||||
}
|
||||
// Maps wie in TS: bei doppelter id gewinnt der letzte Eintrag.
|
||||
let ceilings: HashMap<&str, &Ceiling> = p.ceilings.as_deref().unwrap_or(&[]).iter().map(|c| (c.id.as_str(), c)).collect();
|
||||
let columns: HashMap<&str, &Column> = p.columns.as_deref().unwrap_or(&[]).iter().map(|c| (c.id.as_str(), c)).collect();
|
||||
let cutters_for = |z0: f64, z1: f64| -> Vec<&[Vec2]> { voids.iter().filter(|v| v.z0 < z1 - EPS && v.z1 > z0 + EPS).map(|v| v.pts.as_slice()).collect() };
|
||||
let wall_cutters = cutters_for(cut_z - 1e-4, cut_z + 1e-4);
|
||||
let wall_flat = encode_rings(&wall_cutters);
|
||||
let mut out = Vec::with_capacity(prims.len());
|
||||
for pr in prims {
|
||||
if let Primitive::Line { a, b, cls, .. } = &pr {
|
||||
if WALL_LINE_CLS.contains(&cls.as_str()) && !wall_cutters.is_empty() {
|
||||
let f = crate::voids::segment_outside_flat(&[a.x, a.y, b.x, b.y], &wall_flat);
|
||||
let n = f.first().copied().unwrap_or(0.0) as usize;
|
||||
let parts: Vec<(f64, f64)> = (0..n).map(|k| (f[1 + 2 * k], f[2 + 2 * k])).collect();
|
||||
if parts.len() == 1 && parts[0].0 == 0.0 && parts[0].1 == 1.0 {
|
||||
out.push(pr);
|
||||
} else {
|
||||
let (a, b) = (*a, *b);
|
||||
let at = |t: f64| Vec2 { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
|
||||
for (t0, t1) in parts {
|
||||
let mut q = pr.clone();
|
||||
if let Primitive::Line { a: qa, b: qb, .. } = &mut q {
|
||||
*qa = at(t0);
|
||||
*qb = at(t1);
|
||||
}
|
||||
out.push(q);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let Primitive::Polygon { pts, no_stroke_edges, wall_id, ceiling_id, column_id, extruded_solid_id, .. } = &pr else {
|
||||
out.push(pr);
|
||||
continue;
|
||||
};
|
||||
// Ids zählen wie in JS nur, wenn nicht leer.
|
||||
let id = |s: &Option<String>| s.as_deref().filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
let (wall_id, ceiling_id, column_id) = (id(wall_id), id(ceiling_id), id(column_id));
|
||||
if id(extruded_solid_id).is_some() {
|
||||
out.push(pr);
|
||||
continue;
|
||||
}
|
||||
let cutters: Option<Vec<&[Vec2]>> = if wall_id.is_some() {
|
||||
Some(wall_cutters.clone())
|
||||
} else if let Some(id) = &ceiling_id {
|
||||
ceilings.get(id.as_str()).map(|c| {
|
||||
let (zb, zt) = p.ceiling_vertical_extent(c);
|
||||
cutters_for(zb, zt)
|
||||
})
|
||||
} else if let Some(id) = &column_id {
|
||||
columns.get(id.as_str()).map(|c| {
|
||||
let (zb, zt) = p.column_vertical_extent(c);
|
||||
if zb <= cut_z && zt >= cut_z {
|
||||
wall_cutters.clone()
|
||||
} else {
|
||||
cutters_for(zb, zt)
|
||||
}
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some(cutters) = cutters.filter(|c| !c.is_empty()) else {
|
||||
out.push(pr);
|
||||
continue;
|
||||
};
|
||||
if pts.len() < 3 {
|
||||
out.push(pr);
|
||||
continue;
|
||||
}
|
||||
let ring = encode_rings(&[pts]);
|
||||
let ns = no_stroke_edges.as_deref().unwrap_or(&[]);
|
||||
let mut nsf = vec![ns.len() as f64];
|
||||
nsf.extend_from_slice(ns);
|
||||
let f = crate::voids::subtract_rings_flat(&ring[1..], &encode_rings(&cutters), &nsf);
|
||||
if f.is_empty() || f[0] < 0.0 {
|
||||
out.push(pr);
|
||||
continue;
|
||||
}
|
||||
let mut i = 1;
|
||||
for _ in 0..f[0] as usize {
|
||||
let n = f[i] as usize;
|
||||
i += 1;
|
||||
let rp: Vec<Vec2> = (0..n).map(|j| Vec2 { x: f[i + 2 * j], y: f[i + 2 * j + 1] }).collect();
|
||||
i += 2 * n;
|
||||
let m = f[i] as usize;
|
||||
i += 1;
|
||||
let rn: Vec<f64> = f[i..i + m].to_vec();
|
||||
i += m;
|
||||
let mut q = pr.clone();
|
||||
if let Primitive::Polygon { pts, no_stroke_edges, .. } = &mut q {
|
||||
*pts = rp;
|
||||
*no_stroke_edges = (!rn.is_empty()).then_some(rn);
|
||||
}
|
||||
out.push(q);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Schnitthöhe des Geschosses (Welt): Basis + Schnitthöhe (Standard 1 m).
|
||||
pub fn cut_z(p: &Project, floor: &str) -> f64 {
|
||||
let l = p.floor(floor);
|
||||
l.and_then(|l| l.base_elevation).unwrap_or(0.0) + l.and_then(|l| l.cut_height).unwrap_or(1.0)
|
||||
}
|
||||
|
||||
// ── Schwarz-Weiss und Strichstärken ─────────────────────────────────────────────────────────────
|
||||
|
||||
const REFERENCE_SCALE: f64 = 100.0;
|
||||
const MIN_FACTOR: f64 = 0.5;
|
||||
const MAX_FACTOR: f64 = 1.6;
|
||||
|
||||
/// Strichstärken-Faktor für 1:`scale` ([32], nur mit `Project.scaleLineWeights`): (100/n)^0.25,
|
||||
/// begrenzt auf 0,5–1,6; sonst 1.
|
||||
pub fn line_weight_factor(p: &Project, scale: f64) -> f64 {
|
||||
if p.scale_line_weights != Some(true) || !(scale > 0.0) || !scale.is_finite() {
|
||||
return 1.0;
|
||||
}
|
||||
let f = jsnum::pow(REFERENCE_SCALE / scale, 0.25);
|
||||
jsnum::min(MAX_FACTOR, jsnum::max(MIN_FACTOR, f))
|
||||
}
|
||||
|
||||
/// Nachbearbeitung beim Schreiben (`plan_buf::Writer::post`): Schwarz-Weiss (alle Farben auf Tinte
|
||||
/// bzw. Papier; eine Vollpoché bleibt schwarz) und Strichstärken-Faktor — in dieser Reihenfolge wie
|
||||
/// früher `toMono` und `scalePrimitiveWeights`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Post {
|
||||
pub mono: bool,
|
||||
pub lw: f64,
|
||||
}
|
||||
|
||||
impl Post {
|
||||
/// Wirkt sie auf etwas?
|
||||
pub fn active(&self) -> bool {
|
||||
self.mono || self.lw != 1.0
|
||||
}
|
||||
|
||||
fn hatch(&self, h: &mut HatchRender) {
|
||||
if self.mono && h.pattern != HatchPattern::None {
|
||||
h.color = (if h.pattern == HatchPattern::Solid { HATCH_INK } else { MONO_INK }).into();
|
||||
}
|
||||
if self.lw != 1.0 {
|
||||
h.line_weight *= self.lw;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ein Primitiv (ohne Linien, die nimmt [`Post::line`]).
|
||||
pub fn apply(&self, p: &mut Primitive) {
|
||||
match p {
|
||||
Primitive::Polygon { fill, stroke, stroke_width_mm, hatch, .. } => {
|
||||
if self.mono {
|
||||
let solid = hatch.pattern == HatchPattern::Solid;
|
||||
if *fill != "none" {
|
||||
*fill = (if solid { HATCH_INK } else { "#ffffff" }).into();
|
||||
}
|
||||
*stroke = MONO_INK.into();
|
||||
}
|
||||
self.hatch(hatch);
|
||||
if self.lw != 1.0 {
|
||||
*stroke_width_mm *= self.lw;
|
||||
}
|
||||
}
|
||||
Primitive::Text { color, .. } => {
|
||||
if self.mono {
|
||||
*color = MONO_INK.into();
|
||||
}
|
||||
}
|
||||
Primitive::Line { weight_mm, color, .. } => {
|
||||
if self.mono {
|
||||
*color = Some(MONO_INK.into());
|
||||
}
|
||||
if self.lw != 1.0 {
|
||||
*weight_mm *= self.lw;
|
||||
}
|
||||
}
|
||||
Primitive::Arc { weight_mm, .. } | Primitive::DrawingCircle { weight_mm, .. } | Primitive::DrawingArc { weight_mm, .. } => {
|
||||
if self.lw != 1.0 {
|
||||
*weight_mm *= self.lw;
|
||||
}
|
||||
}
|
||||
Primitive::DrawingText { .. } | Primitive::DrawingTextPath { .. } | Primitive::DrawingImage { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Farbe und Stärke einer Linie.
|
||||
pub fn line<'a>(&self, color: Option<&'a str>, w: f64) -> (Option<&'a str>, f64) {
|
||||
(if self.mono { Some(MONO_INK) } else { color }, if self.lw != 1.0 { w * self.lw } else { w })
|
||||
}
|
||||
}
|
||||
|
||||
/// Nachbearbeitung eines Plans: Schwarz-Weiss und Strichstärken-Faktor; `None`, wenn sie nichts tut.
|
||||
pub fn post_for(p: &Project, a: &super::domains::PlanArgs) -> Option<Post> {
|
||||
Some(Post { mono: a.mono, lw: line_weight_factor(p, a.scale) }).filter(Post::active)
|
||||
}
|
||||
|
||||
// ── Ausmass ─────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Ausmass der Zutaten, die „Einpassen" und Druck ganz zeigen sollen: Schatten und Baurechts-Linien
|
||||
/// (`extra`) und die ganze Kontext-Schicht (Konturen, Netze, Luftbilder) — Rohwerte für
|
||||
/// [`plan_bounds`].
|
||||
pub fn extra_bounds(p: &Project, extra: &[(Primitive, u32)]) -> Bounds {
|
||||
let mut b = Bounds::new();
|
||||
for (e, _) in extra {
|
||||
match e {
|
||||
Primitive::Polygon { pts, .. } => {
|
||||
for q in pts {
|
||||
b.acc(q.x, q.y);
|
||||
}
|
||||
}
|
||||
Primitive::Line { a, b: e, .. } => {
|
||||
b.acc(a.x, a.y);
|
||||
b.acc(e.x, e.y);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for obj in p.context.as_deref().unwrap_or(&[]) {
|
||||
match obj {
|
||||
ContextObject::ContourSet(cs) => {
|
||||
for c in &cs.contours {
|
||||
for q in &c.pts {
|
||||
b.acc(q.x, q.y);
|
||||
}
|
||||
}
|
||||
}
|
||||
ContextObject::Image(im) => {
|
||||
b.acc(im.min.x, im.min.y);
|
||||
b.acc(im.max.x, im.max.y);
|
||||
}
|
||||
ContextObject::ImportedMesh(m) => mesh_bounds(&m.positions, &mut b),
|
||||
ContextObject::TerrainMesh(m) => mesh_bounds(&m.positions, &mut b),
|
||||
}
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
fn mesh_bounds(pos: &[f64], b: &mut Bounds) {
|
||||
let mut i = 0;
|
||||
while i + 1 < pos.len() {
|
||||
b.acc(pos[i], pos[i + 1]);
|
||||
i += 3;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ausmass des Plans (`computeBounds`): Ausmass der Domänen (falls vorhanden, als zwei Ecken), dann
|
||||
/// die Zutaten; ohne Punkte `[0, 0, 1, 1]`.
|
||||
pub fn plan_bounds(domains: &Bounds, extra: &Bounds) -> [f64; 4] {
|
||||
let mut b = Bounds::new();
|
||||
if let Some(d) = domains.get() {
|
||||
b.acc(d[0], d[1]);
|
||||
b.acc(d[2], d[3]);
|
||||
}
|
||||
b.merge(extra.raw());
|
||||
b.get().unwrap_or([0.0, 0.0, 1.0, 1.0])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample() -> Project {
|
||||
serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strichstaerken_faktor() {
|
||||
let mut on = sample();
|
||||
on.scale_line_weights = Some(true);
|
||||
assert_eq!(line_weight_factor(&on, 100.0), 1.0);
|
||||
assert!((line_weight_factor(&on, 200.0) - 0.5f64.powf(0.25)).abs() < 1e-12);
|
||||
assert!((line_weight_factor(&on, 50.0) - 2f64.powf(0.25)).abs() < 1e-12);
|
||||
assert_eq!(line_weight_factor(&on, 100000.0), 0.5);
|
||||
assert_eq!(line_weight_factor(&sample(), 200.0), 1.0);
|
||||
assert_eq!(line_weight_factor(&on, f64::NAN), 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn abzugskoerper_spart_wand_aus() {
|
||||
let mut v: serde_json::Value = serde_json::from_str(include_str!("../../tests/fixtures/sample_project.json")).unwrap();
|
||||
let walls = |v: &serde_json::Value| {
|
||||
let p: Project = serde_json::from_value(v.clone()).unwrap();
|
||||
let codes: Vec<String> = p.flat_categories().iter().map(|c| c.code.clone()).collect();
|
||||
let a = super::super::domains::PlanArgs::parse(1.0, &serde_json::json!({"floor": "eg", "show": codes}).to_string()).unwrap();
|
||||
let (prims, _, _) = crate::plan_buf::decode(&super::super::domains::plan_domains_buf(&p, &a).unwrap()).unwrap();
|
||||
prims.into_iter().filter(|q| matches!(q, Primitive::Polygon { wall_id: Some(_), .. })).collect::<Vec<_>>()
|
||||
};
|
||||
let before = walls(&v);
|
||||
v["extrudedSolids"] = serde_json::json!([{"id": "void1", "type": "extrudedSolid", "levelId": "eg", "operation": "subtract", "height": 3,
|
||||
"points": [{"x": 1.95, "y": -0.5}, {"x": 2.15, "y": -0.5}, {"x": 2.15, "y": 0.5}, {"x": 1.95, "y": 0.5}]}]);
|
||||
let after = walls(&v);
|
||||
assert_ne!(before, after);
|
||||
assert!(after.len() > before.len(), "{} → {}", before.len(), after.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erdgeschoss_naechst_null() {
|
||||
let p = sample();
|
||||
assert_eq!(ground_floor_id(&p), Some("eg"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_poche_bleibt_schwarz() {
|
||||
let post = Post { mono: true, lw: 1.0 };
|
||||
let mut solid = HatchRender { pattern: HatchPattern::Solid, ..no_hatch() };
|
||||
solid.color = "#123456".into();
|
||||
let mut p = flat_polygon(vec![], "#abcdef", 1.0);
|
||||
if let Primitive::Polygon { hatch, stroke, .. } = &mut p {
|
||||
*hatch = solid;
|
||||
*stroke = "#ff0000".into();
|
||||
}
|
||||
post.apply(&mut p);
|
||||
match &p {
|
||||
Primitive::Polygon { fill, stroke, hatch, .. } => {
|
||||
assert_eq!(fill, HATCH_INK);
|
||||
assert_eq!(stroke, MONO_INK);
|
||||
assert_eq!(hatch.color, HATCH_INK);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert_eq!(post.line(None, 0.25), (Some(MONO_INK), 0.25));
|
||||
}
|
||||
}
|
||||
@@ -10,3 +10,4 @@ pub mod stairs;
|
||||
pub mod context;
|
||||
pub mod drawings;
|
||||
pub mod cache;
|
||||
pub mod extras;
|
||||
@@ -1000,6 +1000,7 @@ struct ChainKey {
|
||||
}
|
||||
|
||||
/// Eine Linie mit geliehenen Feldern (Felder wie `Primitive::Line`), s. [`Writer::line_ref`].
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct LineRef<'a> {
|
||||
pub a: Vec2,
|
||||
pub b: Vec2,
|
||||
@@ -1066,6 +1067,8 @@ pub struct Writer {
|
||||
pub bounds: Option<[f64; 4]>,
|
||||
/// Laufende Aufnahme eines Abschnitts ([`Writer::mark`] … [`Writer::take_segment`]).
|
||||
rec: Option<Recording>,
|
||||
/// Nachbearbeitung jedes geschriebenen Primitivs (Schwarz-Weiss, Strichstärken-Faktor).
|
||||
pub post: Option<crate::plan::extras::Post>,
|
||||
}
|
||||
|
||||
/// Anfang und Merkposten eines aufgenommenen Abschnitts.
|
||||
@@ -1196,6 +1199,7 @@ impl Writer {
|
||||
h: FNV_OFFSET,
|
||||
bounds: None,
|
||||
rec: None,
|
||||
post: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1635,6 +1639,18 @@ impl Writer {
|
||||
/// Kennung): zwei Linien mit Muster-Liste setzen einen Linienzug nur bei gleicher Kennung fort
|
||||
/// (TS: dieselbe Array-Referenz), ohne Kennung nie.
|
||||
pub fn push_ref(&mut self, p: &Primitive, dash_ref: u32) {
|
||||
// Linien bearbeitet `line_ref`.
|
||||
if let Some(post) = self.post.filter(|q| q.active()) {
|
||||
if !matches!(p, Primitive::Line { .. }) {
|
||||
let mut q = p.clone();
|
||||
post.apply(&mut q);
|
||||
return self.push_ref_raw(&q, dash_ref);
|
||||
}
|
||||
}
|
||||
self.push_ref_raw(p, dash_ref)
|
||||
}
|
||||
|
||||
fn push_ref_raw(&mut self, p: &Primitive, dash_ref: u32) {
|
||||
match p {
|
||||
Primitive::Polygon {
|
||||
pts,
|
||||
@@ -1754,6 +1770,15 @@ impl Writer {
|
||||
/// Eine Linie aus geliehenen Feldern anhängen (wie [`Writer::push_ref`] mit `Primitive::Line`,
|
||||
/// ohne das Primitiv erst zu bauen — die 2D-Zeichnungen schreiben so direkt in den Puffer).
|
||||
pub fn line_ref(&mut self, l: &LineRef, dash_ref: u32) {
|
||||
let posted;
|
||||
let l = match self.post.filter(|q| q.active()) {
|
||||
Some(q) => {
|
||||
let (color, weight_mm) = q.line(l.color, l.weight_mm);
|
||||
posted = LineRef { color, weight_mm, ..*l };
|
||||
&posted
|
||||
}
|
||||
None => l,
|
||||
};
|
||||
let plain = l.zigzag.is_none() && l.motif.is_none();
|
||||
let di = l.drawing_id.map(|s| self.intern(s).0);
|
||||
let ci = l.color.map(|s| self.intern(s).0);
|
||||
|
||||
@@ -90,7 +90,9 @@ pub fn run_bin(p: &Project, name: &str, args: &[f64], text: &str) -> Result<Vec<
|
||||
let mut a = domains::PlanArgs::parse(1.0, "{}")?;
|
||||
a.scale = args[0];
|
||||
let c = domains::Ctx::new(p, &a);
|
||||
buf_of(|sink| drawings::underlay_lines(&c, &args[2..], args[1] != 0.0, sink))
|
||||
// Strichstärken nach Massstab wie im übrigen Plan.
|
||||
let post = Some(crate::plan::extras::Post { mono: false, lw: crate::plan::extras::line_weight_factor(p, args[0]) }).filter(crate::plan::extras::Post::active);
|
||||
buf_with(post, |sink| drawings::underlay_lines(&c, &args[2..], args[1] != 0.0, sink))
|
||||
}
|
||||
// Primitive einer Zeichnung (JSON in `text`, ohne Override-Regeln) beim Massstab `args[0]`.
|
||||
("drawingPrims", 1) => {
|
||||
@@ -127,8 +129,14 @@ pub fn run_bin_doc(d: &mut crate::document::Document, name: &str, args: &[f64],
|
||||
|
||||
/// Plan-Puffer (eine Gruppe, ohne Inhalts-Hashes), in den `f` die Zeichnungs-Primitive schreibt.
|
||||
fn buf_of(f: impl FnOnce(&mut crate::plan::drawings::Sink) -> Result<(), String>) -> Result<Vec<u8>, String> {
|
||||
buf_with(None, f)
|
||||
}
|
||||
|
||||
/// Wie [`buf_of`] mit Nachbearbeitung (`extras::Post`).
|
||||
fn buf_with(post: Option<crate::plan::extras::Post>, f: impl FnOnce(&mut crate::plan::drawings::Sink) -> Result<(), String>) -> Result<Vec<u8>, String> {
|
||||
use crate::plan::drawings::{Keep, Sink, Target};
|
||||
let mut w = crate::plan_buf::Writer::new(false);
|
||||
w.post = post;
|
||||
let start = w.begin_group();
|
||||
f(&mut Sink::new(Target::Buf(&mut w), Keep::All))?;
|
||||
w.end_group(start);
|
||||
|
||||
@@ -14,12 +14,6 @@ pub fn voids_subtract_rings_flat(pts: &[f64], cutters: &[f64], no_stroke: &[f64]
|
||||
crate::voids::subtract_rings_flat(pts, cutters, no_stroke)
|
||||
}
|
||||
|
||||
/// Teile einer Strecke ausserhalb aller Ringe; Unsinn → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn voids_segment_outside_flat(seg: &[f64], cutters: &[f64]) -> Vec<f64> {
|
||||
crate::voids::segment_outside_flat(seg, cutters)
|
||||
}
|
||||
|
||||
/// Schnitt-Intervalle eines Prismas mit einer senkrechten Ebene; Unsinn → leer.
|
||||
#[wasm_bindgen]
|
||||
pub fn voids_section_rects_flat(pts: &[f64], base_u: &[f64]) -> Vec<f64> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Kern-Abschnitte im Plan ([K3d], Plan-Puffer v2): `Plan.bufRuns` zeigt auf unveränderte Primitive
|
||||
// aus dem Puffer des Kerns — auch nach Abzugskörpern, beim Überlagern mehrerer Geschosse und mit
|
||||
// der kompakten Unterlage; Mono und Strichstärken-Massstab lassen sie weg.
|
||||
// Kern-Abschnitte im Plan ([K3d], Plan-Puffer v2): `Plan.bufRuns` zeigt auf die Primitive aus den
|
||||
// Puffern des Kerns — der ganze Plan kommt aus dem Kern (auch Abzugskörper, Mono und
|
||||
// Strichstärken-Massstab), beim Überlagern mehrerer Geschosse und mit der kompakten Unterlage.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { generatePlan, generateVisibleLevelsPlan, materializeUnderlay } from "./generatePlan";
|
||||
@@ -32,26 +32,27 @@ describe("Plan.bufRuns", () => {
|
||||
expect(covered).toBe(plan.primitives.length);
|
||||
});
|
||||
|
||||
it("Abzugskörper zerlegen Polygone: Abschnitte werden neu ausgerichtet", () => {
|
||||
it("Abzugskörper zerlegen Polygone (im Kern): alles bleibt Abschnitt", () => {
|
||||
const solid: ExtrudedSolid = {
|
||||
id: "void1",
|
||||
type: "extrudedSolid",
|
||||
levelId: "eg",
|
||||
operation: "subtract",
|
||||
height: 3,
|
||||
// Durch die Wand W1 zwischen Tür und Innenwand.
|
||||
points: [
|
||||
{ x: 1, y: -0.5 },
|
||||
{ x: 1.4, y: -0.5 },
|
||||
{ x: 1.4, y: 0.5 },
|
||||
{ x: 1, y: 0.5 },
|
||||
{ x: 1.95, y: -0.5 },
|
||||
{ x: 2.15, y: -0.5 },
|
||||
{ x: 2.15, y: 0.5 },
|
||||
{ x: 1.95, y: 0.5 },
|
||||
],
|
||||
} as ExtrudedSolid;
|
||||
const p: Project = { ...sampleProject, extrudedSolids: [solid] };
|
||||
const plan = generatePlan(p, "eg", codes(p));
|
||||
const total = plan.bufRuns![0].buf.prims.length;
|
||||
const covered = checkRuns(plan);
|
||||
expect(covered).toBeGreaterThan(total / 2);
|
||||
expect(covered).toBeLessThan(total);
|
||||
expect(checkRuns(plan)).toBe(plan.primitives.length);
|
||||
// Die Wand-Poché unter dem Körper ist ausgespart.
|
||||
const walls = (q: Project) => JSON.stringify(generatePlan(q, "eg", codes(q)).primitives.filter((x) => x.kind === "polygon" && x.wallId));
|
||||
expect(walls(p)).not.toBe(walls(sampleProject));
|
||||
});
|
||||
|
||||
it("Überlagerung mehrerer Geschosse und kompakte Unterlage verschieben die Abschnitte mit", () => {
|
||||
@@ -61,10 +62,11 @@ describe("Plan.bufRuns", () => {
|
||||
checkRuns(materializeUnderlay(plan));
|
||||
});
|
||||
|
||||
it("Mono und Strichstärken-Massstab: keine Abschnitte", () => {
|
||||
expect(generatePlan(sampleProject, "eg", codes(sampleProject), undefined, "mittel", false, true).bufRuns).toBeUndefined();
|
||||
it("Mono und Strichstärken-Massstab rechnet der Kern: alles bleibt Abschnitt", () => {
|
||||
const mono = generatePlan(sampleProject, "eg", codes(sampleProject), undefined, "mittel", false, true);
|
||||
expect(checkRuns(mono)).toBe(mono.primitives.length);
|
||||
const scaled: Project = { ...sampleProject, scaleLineWeights: true };
|
||||
expect(generatePlan(scaled, "eg", codes(scaled), undefined, "mittel", false, false, true, 50).bufRuns).toBeUndefined();
|
||||
expect(generatePlan(scaled, "eg", codes(scaled), undefined, "mittel", false, false, true, 100).bufRuns?.length).toBeGreaterThanOrEqual(1);
|
||||
const s50 = generatePlan(scaled, "eg", codes(scaled), undefined, "mittel", false, false, true, 50);
|
||||
expect(checkRuns(s50)).toBe(s50.primitives.length);
|
||||
});
|
||||
});
|
||||
@@ -79,7 +79,7 @@ describe("Inhalts-Hashes der 2D-Zeichnungen (GPU-Chunk-Cache)", () => {
|
||||
expect(hashes(p2, "A")).not.toEqual(hashes(p1, "A"));
|
||||
});
|
||||
|
||||
it("mono verändert Primitive in place, ohne den normalen Plan zu vergiften", () => {
|
||||
it("mono (im Kern) lässt den normalen Plan unverändert", () => {
|
||||
const proj = project([draw("A", 0)]);
|
||||
const normal1 = generatePlan(proj, "eg", visible);
|
||||
generatePlan(proj, "eg", visible, undefined, "mittel", false, true);
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { generatePlan, materializeUnderlay } from "./generatePlan";
|
||||
import { lineWeightFactor } from "./lineWeightScale";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import type { Project } from "../model/types";
|
||||
@@ -19,14 +18,7 @@ const plan = (p: Project, n: number, compact = false) =>
|
||||
materializeUnderlay(generatePlan(p, "eg", ALL, undefined, "mittel", false, false, true, n, false, compact));
|
||||
|
||||
describe("Strichstärken nach Massstab", () => {
|
||||
it("Faktor: 1 bei 1:100, kleiner bei 1:200, grösser bei 1:50, begrenzt", () => {
|
||||
expect(lineWeightFactor(on, 100)).toBe(1);
|
||||
expect(lineWeightFactor(on, 200)).toBeCloseTo(0.5 ** 0.25, 9);
|
||||
expect(lineWeightFactor(on, 50)).toBeCloseTo(2 ** 0.25, 9);
|
||||
expect(lineWeightFactor(on, 100000)).toBe(0.5);
|
||||
expect(lineWeightFactor(sampleProject, 200)).toBe(1);
|
||||
expect(lineWeightFactor(on, Number.NaN)).toBe(1);
|
||||
});
|
||||
// Der Faktor selbst (Grenzen, ungültiger Massstab) ist im Kern geprüft (`plan/extras.rs`).
|
||||
it("Grundriss 1:200: jede Stärke × Faktor, aus → unverändert", () => {
|
||||
const base = weights(plan(sampleProject, 200).primitives);
|
||||
const scaled = weights(plan(on, 200).primitives);
|
||||
@@ -40,7 +32,7 @@ describe("Strichstärken nach Massstab", () => {
|
||||
expect(scaled.length).toBe(base.length);
|
||||
scaled.forEach((w, i) => expect(w).toBeCloseTo(base[i] * 0.5 ** 0.25, 9));
|
||||
});
|
||||
it("gleiche Eingabe → gleiche Inhalts-Hashes der Kern-Abschnitte (GPU-Cache); mit Massstab als Liste", () => {
|
||||
it("gleiche Eingabe → gleiche Inhalts-Hashes der Kern-Abschnitte (GPU-Cache), auch mit Massstab", () => {
|
||||
const line = {
|
||||
id: "z1", type: "drawing2d", levelId: "eg", categoryCode: sampleProject.drawings2d[0]?.categoryCode ?? sampleProject.layers[0].code,
|
||||
geom: { shape: "polyline", pts: [{ x: 0, y: 0 }, { x: 3, y: 0 }, { x: 3, y: 2 }], closed: false },
|
||||
@@ -53,7 +45,9 @@ describe("Strichstärken nach Massstab", () => {
|
||||
const a = hashes(base);
|
||||
expect(a.length).toBeGreaterThan(0);
|
||||
expect(hashes(base)).toEqual(a);
|
||||
// Strichstärken-Massstab ersetzt die Primitive: dann gilt der Puffer nicht mehr (Objekte, s. GpuChunkCache).
|
||||
expect(hashes({ ...on, drawings2d: base.drawings2d })).toEqual([]);
|
||||
// Der Strichstärken-Massstab rechnet der Kern in den Puffer: andere Stärken, andere Hashes.
|
||||
const scaled = hashes({ ...on, drawings2d: base.drawings2d });
|
||||
expect(scaled.length).toBe(a.length);
|
||||
expect(scaled).not.toEqual(a);
|
||||
});
|
||||
});
|
||||
@@ -5,12 +5,13 @@
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { generatePlan } from "./generatePlan";
|
||||
import { SITE_CLS } from "./generatePlan/siteRules";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import type { Project, SiteRules } from "../model/types";
|
||||
|
||||
const ALL = new Set(flattenCategories(sampleProject.layers).map((c) => c.code));
|
||||
/** Erkennungsmerkmale des Baurechts (`core/src/plan/extras.rs`). */
|
||||
const SITE_CLS = { parcel: "site-parcel", allowed: "site-allowed", violationFill: "#d0342c" } as const;
|
||||
const site: SiteRules = {
|
||||
parcel: [{ x: -10, y: -10 }, { x: 20, y: -10 }, { x: 20, y: 20 }, { x: -10, y: 20 }],
|
||||
defaultSetback: 4,
|
||||
|
||||
@@ -5,12 +5,13 @@
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { generatePlan } from "./generatePlan";
|
||||
import { SUN_SHADOW_FILL } from "./generatePlan/sunShadow";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { flattenCategories } from "../model/types";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
const ALL = new Set(flattenCategories(sampleProject.layers).map((c) => c.code));
|
||||
/** Füllfarbe der Schattenflächen (`core/src/plan/extras.rs::SUN_SHADOW_FILL`). */
|
||||
const SUN_SHADOW_FILL = "#3a4a66";
|
||||
|
||||
const withStudy = (when: string, show = true): Project => ({ ...sampleProject, sunStudy: { when, show } });
|
||||
const shadows = (p: Project, floorId: string) =>
|
||||
|
||||
+44
-201
@@ -11,8 +11,9 @@
|
||||
// Wände mit Öffnungen, Treppen, Stützen, Extrusionen, Kontext, Schnittführung)
|
||||
// rechnet der Rust-Kern auf dem Projekt-Dokument (`src-tauri/core/src/plan/`,
|
||||
// Abfrage `planDomains`, [K3d]) und liefert fertige `Primitive` — auch die freie
|
||||
// 2D-Geometrie (`plan/drawings.rs`). In TS bleiben Schattenstudie und Baurecht,
|
||||
// die Abzugskörper (`voids.ts`), Mono und der Strichstärken-Massstab.
|
||||
// 2D-Geometrie (`plan/drawings.rs`), Schattenstudie und Baurecht, Abzugskörper, Mono und
|
||||
// Strichstärken-Massstab samt Ausmass (`plan/extras.rs`). `generatePlan` reicht nur noch
|
||||
// Sichtbarkeit (UI-Zustand) und Optionen weiter und setzt den Plan aus den Puffern zusammen.
|
||||
// Das `Primitive`-Vokabular und die Attribut-Auflösung für die übrigen TS-Pfade
|
||||
// leben in `generatePlan/shared.ts`.
|
||||
|
||||
@@ -38,7 +39,6 @@ import type { SectionOutput } from "./toSection";
|
||||
import {
|
||||
HATCH_INK,
|
||||
HATCH_PAPER,
|
||||
MONO_INK,
|
||||
SHOW_ALL,
|
||||
resolveBackground,
|
||||
resolveForeground,
|
||||
@@ -49,11 +49,7 @@ import {
|
||||
type HatchRender,
|
||||
type Primitive,
|
||||
} from "./generatePlan/shared";
|
||||
import { subtractVoidsInPlan, voidPrisms } from "./voids";
|
||||
import { isBufPiece, lazyPlan, piecesOf, planCount, planFields, type PlanPiece } from "./planLazy";
|
||||
import { addSunShadow } from "./generatePlan/sunShadow";
|
||||
import { addSiteRules, addSiteViolations } from "./generatePlan/siteRules";
|
||||
import { lineWeightFactor, scalePrimitiveWeights } from "./lineWeightScale";
|
||||
import { lazyPlan, piecesOf, planCount, planFields, type PlanPiece } from "./planLazy";
|
||||
import { DEFAULT_SCALE_DENOMINATOR } from "../model/dimension";
|
||||
import { layersStyleSig } from "./generatePlan/layerSig";
|
||||
|
||||
@@ -342,54 +338,37 @@ export function generatePlan(
|
||||
/**
|
||||
* Kompakte Linien-Unterlage statt dauerhafter 'line'-Primitive (s.
|
||||
* {@link UnderlayGroup}) — NUR für die interaktive GPU-Ansicht. Aus bei
|
||||
* Export/mono (toMono mutiert Linienfarben).
|
||||
* Export/mono (reiner Schwarz-Weiss-Plan ohne Unterlage).
|
||||
*/
|
||||
compactUnderlay = false,
|
||||
): Plan {
|
||||
const primitives: Primitive[] = [];
|
||||
// Schattenstudie zuunterst (projektglobal, nur im Geschoss nächst ±0.00).
|
||||
if (includeGlobal) addSunShadow(primitives, project, floorId);
|
||||
// Baurecht (Parzelle, zulässige Fläche, Verstösse), ebenfalls zuunterst.
|
||||
if (includeGlobal) addSiteRules(primitives, project, floorId);
|
||||
const underlayCount = primitives.length;
|
||||
// Aktives Geschoss (für die Grundriss-Schnitthöhe der Treppen).
|
||||
const floor = project.drawingLevels.find((z) => z.id === floorId);
|
||||
const compact = compactUnderlay && !mono && !forPrint;
|
||||
|
||||
// Decken, Dächer, Räume, Wände mit Öffnungen, Treppen, Stützen, 2D-Zeichnungen und Extrusions-Umrisse
|
||||
// rechnet der Kern auf dem Dokument ([K3d], `plan/{domains,walls,stairs,drawings}.rs`): Filter,
|
||||
// Override-Regeln, Verschneidung, Stil und Raumstempel-Daten. Decken, Dächer und Räume liegen unter
|
||||
// der Wand-Poché; Stützen folgen nach den Treppen, die 2D-Zeichnungen darüber, Extrusionen danach.
|
||||
// Der Kern liefert alles in EINEM Plan-Puffer (Gruppen in dieser Reihenfolge); die Abschnitte
|
||||
// merkt sich der Plan (`bufRuns`), damit die GPU sie direkt aus dem Puffer kompiliert.
|
||||
// Mono färbt die gelesenen Primitive um (s. `toMono`): dann keine behaltenen Stücke.
|
||||
const dom = planDomains(project, floorId, visibleCodes, categoryDisplay, detail, showReferenceLines, includeGlobal, scaleDenominator, forPrint, compact, !mono);
|
||||
// Der Plan entsteht aus Stücken ([K3d], `planLazy.ts`): TS-Listen und Kern-Abschnitte; die
|
||||
// Kern-Primitive werden erst gelesen, wenn ein Verbraucher sie als Objekte braucht.
|
||||
const pieces: PlanPiece[] = [primitives];
|
||||
// Den ganzen Grundriss rechnet der Kern auf dem Dokument ([K3d]/[K4], `plan/{domains,walls,stairs,
|
||||
// drawings,extras}.rs`): Schattenstudie und Baurecht zuunterst, Decken, Dächer, Räume, Wände mit
|
||||
// Öffnungen, Treppen, Stützen, 2D-Zeichnungen, Extrusions-Umrisse, Kontext und Schnittführung,
|
||||
// die Baurechts-Verstösse zuoberst; dazu Abzugskörper, Schwarz-Weiss, Strichstärken nach Massstab
|
||||
// und das Ausmass. Er liefert einen Plan-Puffer (Gruppen in dieser Reihenfolge) und die
|
||||
// 2D-Zeichnungen in Stücken; der Plan liest die Primitive erst, wenn ein Verbraucher sie als
|
||||
// Objekte braucht (`planLazy.ts`), die GPU kompiliert direkt aus den Puffern (`bufRuns`).
|
||||
// Zeitpunkt der Schattenstudie: `Date` nimmt das Datum, wie es in der Datei steht (Ortszeit ohne Zone).
|
||||
const study = project.sunStudy;
|
||||
const sunWhen = includeGlobal && study?.show ? new Date(study.when).getTime() : NaN;
|
||||
const dom = planDomains(project, floorId, visibleCodes, categoryDisplay, detail, showReferenceLines, includeGlobal, scaleDenominator, forPrint, compact, mono, sunWhen);
|
||||
const pieces: PlanPiece[] = [];
|
||||
const pushGroups = (first: number, last: number): void => {
|
||||
const from = dom.buf.groups[first][0];
|
||||
const to = dom.buf.groups[last][1];
|
||||
if (to > from) pieces.push({ buf: dom.buf, from, to });
|
||||
};
|
||||
// Decken, Dächer, Räume; Wände (Poché, Referenzlinie) mit ihren Öffnungs-Symbolen, je Wand
|
||||
// nacheinander; Treppen; Stützen; 2D-Zeichnungen (über der Poché); extrudierte Körper
|
||||
// (Footprint-Umriss); Kontext-Konturen und Schnittführungs-Symbole (projektglobal, nur beim
|
||||
// aktiven Aufruf einer Mehrfach-Überlagerung).
|
||||
// Die 2D-Zeichnungen kommen als eigene Puffer-Stücke (an Stelle der Gruppe 6, s. `planDomains`).
|
||||
pushGroups(G_CEILINGS, G_COLUMNS);
|
||||
// Die 2D-Zeichnungen kommen als eigene Puffer-Stücke an Stelle ihrer (leeren) Gruppe.
|
||||
pushGroups(G_UNDER, G_COLUMNS);
|
||||
for (const c of dom.chunks) pieces.push({ buf: c, from: 0, to: c.count });
|
||||
pushGroups(G_SOLIDS, G_SECTIONS);
|
||||
pushGroups(G_SOLIDS, G_VIOLATIONS);
|
||||
// Kompakte Linien-Unterlage (s. {@link UnderlayGroup}): die Linien einfacher Zeichnungen fehlen
|
||||
// im Puffer und entstehen erst bei Bedarf, PRO KATEGORIE gruppiert — das Ein-/Ausblenden einer
|
||||
// Ebene entfernt dann nur deren Gruppe, die Chunks aller anderen Ebenen bleiben gültig.
|
||||
const underlay = compact ? underlayGroups(project, dom, scaleDenominator) : [];
|
||||
|
||||
// Baurechts-Verstösse über allem (Signal, soll nicht unter der Wand-Poché verschwinden).
|
||||
const violations: Primitive[] = [];
|
||||
if (includeGlobal) addSiteViolations(violations, project, floorId);
|
||||
pieces.push(violations);
|
||||
|
||||
// Georeferenzierte Luftbilder als Hintergrund-Ebenen (nur interaktive Ansicht,
|
||||
// nicht Teil der Vektor-Primitive) — im Mono-Modus ausgeblendet (reiner S/W-Plan).
|
||||
// Projektglobal (nicht je Geschoss), s. `includeGlobal` oben.
|
||||
@@ -405,79 +384,9 @@ export function generatePlan(
|
||||
opacity: o.opacity ?? 1,
|
||||
filters: o.filters,
|
||||
}));
|
||||
|
||||
// Strichstärken nach Massstab ([32], nur mit Projekt-Option): auf die fertigen Primitive und
|
||||
// auf die Linien der kompakten Unterlage.
|
||||
const lwf = lineWeightFactor(project, scaleDenominator);
|
||||
const scaledUnderlay =
|
||||
lwf === 1
|
||||
? underlay
|
||||
: underlay.map((g) => ({
|
||||
...g,
|
||||
ctx: [...g.ctx, lwf],
|
||||
build: (ds: Drawing2D[]) => g.build(ds).map((p) => scalePrimitiveWeights(p, lwf)),
|
||||
buildBuf: undefined,
|
||||
}));
|
||||
const rest = {
|
||||
bounds: computeBounds(project, dom.buf.bounds, primitives.slice(0, underlayCount)),
|
||||
backgroundImages,
|
||||
...(scaledUnderlay.length ? { underlay: scaledUnderlay } : {}),
|
||||
};
|
||||
const hasVoids = voidPrisms(project).length > 0;
|
||||
// Ohne Abzugskörper, Mono und Strichstärken-Massstab bleibt der Plan lazy: die Kern-Primitive
|
||||
// werden erst bei Bedarf gelesen.
|
||||
if (!hasVoids && !mono && lwf === 1) return lazyPlan(rest, pieces);
|
||||
|
||||
// Sonst wie bisher als Liste: die Schritte unten verändern Primitive.
|
||||
const all: Primitive[] = [];
|
||||
const runs: PlanBufRun[] = [];
|
||||
for (const pc of pieces) {
|
||||
if (isBufPiece(pc)) {
|
||||
runs.push({ at: all.length, buf: pc.buf, from: pc.from, to: pc.to });
|
||||
for (let i = pc.from; i < pc.to; i++) all.push(pc.buf.prim(i));
|
||||
} else for (const pr of pc) all.push(pr);
|
||||
}
|
||||
// Abzugskörper (Aussparungen/Durchbrüche): von Wand-/Stützen-/Decken-Poché abziehen.
|
||||
// Ersetzte Primitive erkennt der GPU-Pfad selbst (Identität); verschiebt das Zerlegen die
|
||||
// Indizes, werden die Kern-Abschnitte neu ausgerichtet. Die Baurechts-Verstösse liegen über
|
||||
// allem und haben keine Bauteil-Id — das Abziehen lässt sie unverändert.
|
||||
if (hasVoids && subtractVoidsInPlan(all, project, (floor?.baseElevation ?? 0) + (floor?.cutHeight ?? 1.0))) realignRuns(all, runs);
|
||||
|
||||
// Schwarz-Weiss (mono): nachträglich alle Farben auf reine Tinte zwingen.
|
||||
// Element-/Kategorie-/Hatch-Farben werden ignoriert, Füllungen werden weiss,
|
||||
// Musterlinien/Striche schwarz — so entsteht ein reiner S/W-Plan.
|
||||
if (mono) toMono(all);
|
||||
|
||||
// Mono färbt die Objekte um, der Massstab ersetzt sie: dann gilt der Puffer nicht mehr.
|
||||
const keepRuns = !mono && lwf === 1 && runs.length > 0;
|
||||
return {
|
||||
primitives: lwf === 1 ? all : all.map((p) => scalePrimitiveWeights(p, lwf)),
|
||||
...rest,
|
||||
...(keepRuns ? { bufRuns: runs } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Kern-Abschnitte nach einem Umbau der Liste (Abzugskörper zerlegen Polygone) neu ausrichten:
|
||||
* jede noch vorhandene Folge unveränderter Puffer-Objekte wird ein eigener Abschnitt.
|
||||
*/
|
||||
function realignRuns(primitives: readonly Primitive[], runs: PlanBufRun[]): void {
|
||||
if (runs.length === 0) return;
|
||||
const where = new Map<Primitive, [PlanBufRun, number]>();
|
||||
for (const r of runs) for (let i = r.from; i < r.to; i++) where.set(r.buf.prims[i], [r, i]);
|
||||
const out: PlanBufRun[] = [];
|
||||
let cur: PlanBufRun | null = null;
|
||||
for (let i = 0; i < primitives.length; i++) {
|
||||
const w = where.get(primitives[i]);
|
||||
if (w && cur && w[0].buf === cur.buf && w[1] === cur.to && i === cur.at + (cur.to - cur.from)) {
|
||||
cur.to++;
|
||||
continue;
|
||||
}
|
||||
cur = w ? { at: i, buf: w[0].buf, from: w[1], to: w[1] + 1 } : null;
|
||||
if (cur) out.push(cur);
|
||||
}
|
||||
runs.length = 0;
|
||||
for (const r of out) runs.push(r);
|
||||
// Ausmass samt Schatten, Baurecht und Kontext (immer gesetzt, ohne Punkte 0,0–1,1).
|
||||
const [minX, minY, maxX, maxY] = dom.buf.bounds ?? [0, 0, 1, 1];
|
||||
return lazyPlan({ bounds: { minX, minY, maxX, maxY }, backgroundImages, ...(underlay.length ? { underlay } : {}) }, pieces);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -795,36 +704,6 @@ export function generateSectionPlan(
|
||||
return { primitives, bounds: { minX, minY, maxX, maxY } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Post-Pass für den Schwarz-Weiss-Modus: ersetzt alle Farb-Informationen der
|
||||
* Plan-Primitive durch einheitliche Tinte/Weiss. Wirkt in-place.
|
||||
* - Polygone: Füllung → weiss, Umriss → Tinte, Schraffur-Musterlinien → Tinte
|
||||
* (Vollfüllung „solid" wird zu Weiss neutralisiert, damit keine Poché-Farbe).
|
||||
* - Linien: explizite Strichfarbe → Tinte (CSS-Klassen sind bereits neutral).
|
||||
* - Bögen tragen keine Farbe (rein CSS, neutral) → unverändert.
|
||||
*/
|
||||
function toMono(primitives: Primitive[]): void {
|
||||
for (const p of primitives) {
|
||||
if (p.kind === "polygon") {
|
||||
// SIA-Poché in mono: Vollmuster „solid" ist eine SCHWARZE Poché und bleibt
|
||||
// schwarz (Schwarz bleibt Schwarz); jede andere Füllung wird weiß, die
|
||||
// Linien-/Kreuzschraffur bleibt sichtbar, aber in Tinte.
|
||||
if (p.hatch.pattern === "solid") {
|
||||
p.hatch = { ...p.hatch, color: HATCH_INK };
|
||||
p.fill = p.fill === "none" ? "none" : HATCH_INK;
|
||||
} else {
|
||||
if (p.hatch.pattern !== "none") p.hatch = { ...p.hatch, color: MONO_INK };
|
||||
p.fill = p.fill === "none" ? "none" : "#ffffff";
|
||||
}
|
||||
p.stroke = MONO_INK;
|
||||
} else if (p.kind === "line") {
|
||||
p.color = MONO_INK;
|
||||
} else if (p.kind === "text") {
|
||||
p.color = MONO_INK;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Primitive der Kern-Domänen (`planDomains` in `queries.rs`) als gelesene Plan-Puffer v2. */
|
||||
interface DomainPrims {
|
||||
/** Haupt-Puffer: Gruppen wie `plan/domains.rs::GROUPS`, Gruppe 6 (2D-Zeichnungen) leer. */
|
||||
@@ -835,12 +714,15 @@ interface DomainPrims {
|
||||
args: string;
|
||||
}
|
||||
|
||||
/** Gruppen des Puffers (`plan/domains.rs::GROUPS`). */
|
||||
const G_CEILINGS = 0;
|
||||
const G_COLUMNS = 5;
|
||||
const G_SOLIDS = 7;
|
||||
const G_SECTIONS = 9;
|
||||
const N_GROUPS = 10;
|
||||
/**
|
||||
* Gruppen des Puffers: Schatten/Baurecht, die Domänen (`plan/domains.rs::GROUPS`: Decken … Stützen,
|
||||
* 2D-Zeichnungen — im Haupt-Puffer leer —, Körper, Kontext, Schnittlinien), Baurechts-Verstösse.
|
||||
*/
|
||||
const G_UNDER = 0;
|
||||
const G_COLUMNS = 6;
|
||||
const G_SOLIDS = 8;
|
||||
const G_VIOLATIONS = 11;
|
||||
const N_GROUPS = 12;
|
||||
|
||||
/** Kennung der Antwort mit Zeichnungs-Stücken (`plan/domains.rs::MULTI_MAGIC`, "PLBm"). */
|
||||
const PLAN_MULTI_MAGIC = 1_347_175_021;
|
||||
@@ -856,8 +738,9 @@ const MAX_CHUNK_STORES = 16;
|
||||
const DETAIL_CODE: Record<DetailLevel, number> = { grob: 0, mittel: 1, fein: 2 };
|
||||
|
||||
/**
|
||||
* Decken, Dächer, Räume, Wände mit Öffnungen, Treppen, Stützen, 2D-Zeichnungen, Extrusions-Umrisse
|
||||
* eines Geschosses und (mit `global`) Kontext-Konturen und Schnittführungs-Symbole aus dem Kern.
|
||||
* Der Grundriss eines Geschosses aus dem Kern: Decken, Dächer, Räume, Wände mit Öffnungen, Treppen,
|
||||
* Stützen, 2D-Zeichnungen, Extrusions-Umrisse und (mit `global`) Schatten, Baurecht, Kontext-Konturen
|
||||
* und Schnittführungs-Symbole; Abzugskörper, Mono und Strichstärken-Massstab sind eingerechnet.
|
||||
* Sichtbarkeit und Darstellungsmodus (UI-Zustand) gehen als Code-Mengen mit: `show` = sichtbar und
|
||||
* gezeichnet, `grey` = gedimmt.
|
||||
*/
|
||||
@@ -872,8 +755,9 @@ function planDomains(
|
||||
scale: number,
|
||||
forPrint: boolean,
|
||||
compact: boolean,
|
||||
/** Stücke vom letzten Aufruf wiederverwenden (gleiche Objekte). */
|
||||
reuse = true,
|
||||
mono: boolean,
|
||||
/** Zeitpunkt der Schattenstudie (Unix-ms, NaN = keiner). */
|
||||
sunWhen: number,
|
||||
): DomainPrims {
|
||||
// Sichtbar und gezeichnet bzw. gedimmt: über die sichtbaren Codes (wenige), nicht über alle
|
||||
// Elemente — der Kern zeichnet ein Element genau dann, wenn sein Code in `show` steht.
|
||||
@@ -885,16 +769,14 @@ function planDomains(
|
||||
show.push(c);
|
||||
if (d.greyed) grey.push(c);
|
||||
}
|
||||
const args = JSON.stringify({ floor: floorId, show, grey, referenceLines, global, scale, forPrint, compact });
|
||||
const held = reuse ? chunkStores.get(args) : undefined;
|
||||
const args = JSON.stringify({ floor: floorId, show, grey, referenceLines, global, scale, forPrint, compact, mono, sunWhen: Number.isNaN(sunWhen) ? null : sunWhen });
|
||||
const held = chunkStores.get(args);
|
||||
const query = held && held.size ? `${args.slice(0, -1)},"have":[${[...held.keys()].join(",")}]}` : args;
|
||||
const res = readPlanMulti(documentFor(project).queryBin("planDomains", [DETAIL_CODE[detail] ?? 1], query), held);
|
||||
if (res.main.groups.length !== N_GROUPS) throw new Error("planDomains: unerwartete Gruppen im Plan-Puffer");
|
||||
if (reuse) {
|
||||
chunkStores.delete(args);
|
||||
chunkStores.set(args, res.store);
|
||||
if (chunkStores.size > MAX_CHUNK_STORES) chunkStores.delete(chunkStores.keys().next().value!);
|
||||
}
|
||||
chunkStores.delete(args);
|
||||
chunkStores.set(args, res.store);
|
||||
if (chunkStores.size > MAX_CHUNK_STORES) chunkStores.delete(chunkStores.keys().next().value!);
|
||||
return { buf: res.main, chunks: res.chunks, args };
|
||||
}
|
||||
|
||||
@@ -958,7 +840,7 @@ function underlayGroups(project: Project, dom: DomainPrims, scaleDenominator: nu
|
||||
return index.get(d);
|
||||
};
|
||||
// Alles, wovon `build` abhängt: ändert sich eine davon, werden die GPU-Chunks neu erzeugt.
|
||||
const ctx = [project.lineStyles, project.hatches, layersStyleSig(project.layers), scaleDenominator, project.overrideRules];
|
||||
const ctx = [project.lineStyles, project.hatches, layersStyleSig(project.layers), scaleDenominator, project.overrideRules, project.scaleLineWeights];
|
||||
const out: UnderlayGroup[] = [];
|
||||
let k = 1;
|
||||
for (let g = 0; g < f[0]; g++) {
|
||||
@@ -988,42 +870,3 @@ function underlayGroups(project: Project, dom: DomainPrims, scaleDenominator: nu
|
||||
export function drawingPrimitives(project: Project, d: Drawing2D, scaleDenominator: number = DEFAULT_SCALE_DENOMINATOR): Primitive[] {
|
||||
return decodePlanBuf(documentFor(project).queryBin("drawingPrims", [scaleDenominator], JSON.stringify(d))).prims;
|
||||
}
|
||||
|
||||
function computeBounds(
|
||||
project: Project,
|
||||
/** Ausmass der Kern-Domänen (Wand-Ecken, Decken, Räume, Dach-Traufen, Treppen, 2D-Zeichnungen), s. `planDomains`. */
|
||||
domainBox: [number, number, number, number] | undefined = undefined,
|
||||
/** Zusätzlich einzurahmende Primitive (Schatten, Parzelle), damit Druck/Einpassen sie ganz zeigen. */
|
||||
extra: Primitive[] = [],
|
||||
) {
|
||||
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
||||
const acc = (p: Vec2) => {
|
||||
minX = Math.min(minX, p.x); minY = Math.min(minY, p.y);
|
||||
maxX = Math.max(maxX, p.x); maxY = Math.max(maxY, p.y);
|
||||
};
|
||||
if (domainBox) {
|
||||
acc({ x: domainBox[0], y: domainBox[1] });
|
||||
acc({ x: domainBox[2], y: domainBox[3] });
|
||||
}
|
||||
for (const e of extra) {
|
||||
if (e.kind === "polygon") e.pts.forEach(acc);
|
||||
else if (e.kind === "line") { acc(e.a); acc(e.b); }
|
||||
}
|
||||
// GESAMTE Kontext-Schicht (Konturen, importierte Gebäude/Terrain, Luftbild)
|
||||
// mit einrahmen, damit „Einpassen"/die Standard-Ansicht sie zeigt — sonst
|
||||
// sässe die Ansicht bei einem reinen Kontext-Import (keine Wände) leer am
|
||||
// Ursprung und der Import wäre „unsichtbar" (Nutzer-Report).
|
||||
for (const obj of project.context ?? []) {
|
||||
if (obj.type === "contourSet") {
|
||||
for (const c of obj.contours) for (const p of c.pts) acc(p);
|
||||
} else if (obj.type === "image") {
|
||||
acc(obj.min);
|
||||
acc(obj.max);
|
||||
} else {
|
||||
const pos = obj.positions;
|
||||
for (let i = 0; i + 1 < pos.length; i += 3) acc({ x: pos[i], y: pos[i + 1] });
|
||||
}
|
||||
}
|
||||
if (!isFinite(minX)) return { minX: 0, minY: 0, maxX: 1, maxY: 1 };
|
||||
return { minX, minY, maxX, maxY };
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
// Baurecht im Grundriss ([63]): Parzellengrenze (strichpunktiert), zulässige Grundfläche
|
||||
// (gestrichelt), beides zuunterst, und Gebäude-Grundfläche ausserhalb davon (rot, halbtransparent,
|
||||
// zuoberst). Nur im Geschoss
|
||||
// nächst ±0.00, wie die Schattenstudie. Rechnung in `analysis/siteRules.ts`.
|
||||
|
||||
import type { Project, Vec2 } from "../../model/types";
|
||||
import { checkSiteRules } from "../../analysis/siteRules";
|
||||
import { withoutHoles } from "../../analysis/sun";
|
||||
import { NO_HATCH, type Primitive } from "./shared";
|
||||
import { groundFloorId } from "./sunShadow";
|
||||
|
||||
/** Erkennungsmerkmale (Linien-Klassen, Füllfarbe) — auch für Tests. */
|
||||
export const SITE_CLS = {
|
||||
parcel: "site-parcel",
|
||||
allowed: "site-allowed",
|
||||
violationFill: "#d0342c",
|
||||
} as const;
|
||||
|
||||
const PARCEL_COLOR = "#1f6f3f";
|
||||
const ALLOWED_COLOR = "#2b5fae";
|
||||
|
||||
function ringLines(out: Primitive[], pts: Vec2[], cls: string, color: string, weightMm: number, dash: number[]): void {
|
||||
for (let i = 0; i < pts.length; i++) {
|
||||
out.push({ kind: "line", a: pts[i], b: pts[(i + 1) % pts.length], cls, weightMm, dash, color });
|
||||
}
|
||||
}
|
||||
|
||||
/** Parzellengrenze und zulässige Fläche (zuunterst gezeichnet). */
|
||||
export function addSiteRules(out: Primitive[], project: Project, floorId: string): void {
|
||||
const rules = project.siteRules;
|
||||
if (!rules || rules.show === false || groundFloorId(project) !== floorId) return;
|
||||
const check = checkSiteRules(project);
|
||||
if (!check) return;
|
||||
// Parzellengrenze: Strich-Punkt; zulässige Fläche: gestrichelt (Papier-mm).
|
||||
ringLines(out, rules.parcel, SITE_CLS.parcel, PARCEL_COLOR, 0.35, [6, 1.5, 0.5, 1.5]);
|
||||
for (const poly of check.allowed) for (const r of poly) ringLines(out, r, SITE_CLS.allowed, ALLOWED_COLOR, 0.25, [2, 1]);
|
||||
}
|
||||
|
||||
/** Gebäude-Grundfläche ausserhalb der zulässigen Fläche (zuoberst, damit sie über der Wand liegt). */
|
||||
export function addSiteViolations(out: Primitive[], project: Project, floorId: string): void {
|
||||
const rules = project.siteRules;
|
||||
if (!rules || rules.show === false || groundFloorId(project) !== floorId) return;
|
||||
for (const poly of checkSiteRules(project)?.violations ?? []) {
|
||||
for (const pts of withoutHoles(poly)) {
|
||||
out.push({ kind: "polygon", pts, fill: SITE_CLS.violationFill, stroke: "none", strokeWidthMm: 0, hatch: NO_HATCH, opacity: 0.45 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
// Schattenstudie im Grundriss ([64]/[59]): Boden-Schatten zum Zeitpunkt `Project.sunStudy.when`
|
||||
// als halbtransparente Flächen ZUUNTERST, nur im Geschoss nächst ±0.00 (der Schatten liegt auf
|
||||
// z = 0). Rechnung in `analysis/sun.ts`; Löcher (Höfe) werden für das Plan-Primitiv zerlegt.
|
||||
|
||||
import type { Project } from "../../model/types";
|
||||
import { projectLatLon, shadowPolygons, sunPosition, withoutHoles } from "../../analysis/sun";
|
||||
import { NO_HATCH, type Primitive } from "./shared";
|
||||
|
||||
/** Füllfarbe der Schattenflächen (Erkennungsmerkmal in Tests). */
|
||||
export const SUN_SHADOW_FILL = "#3a4a66";
|
||||
const SUN_SHADOW_OPACITY = 0.28;
|
||||
|
||||
/** Geschoss, auf dem der Boden-Schatten erscheint: Basishöhe am nächsten bei 0. */
|
||||
export function groundFloorId(project: Project): string | null {
|
||||
let best: { id: string; d: number } | null = null;
|
||||
for (const l of project.drawingLevels) {
|
||||
if (l.kind !== "floor") continue;
|
||||
const d = Math.abs(l.baseElevation ?? 0);
|
||||
if (!best || d < best.d) best = { id: l.id, d };
|
||||
}
|
||||
return best?.id ?? null;
|
||||
}
|
||||
|
||||
/** Hängt die Schattenflächen an `out` an (nichts ohne aktive Studie, nachts oder auf anderen Geschossen). */
|
||||
export function addSunShadow(out: Primitive[], project: Project, floorId: string): void {
|
||||
const study = project.sunStudy;
|
||||
if (!study?.show || groundFloorId(project) !== floorId) return;
|
||||
const when = new Date(study.when);
|
||||
if (Number.isNaN(when.getTime())) return;
|
||||
const { lat, lon } = projectLatLon(project);
|
||||
for (const poly of shadowPolygons(project, sunPosition(lat, lon, when))) {
|
||||
for (const pts of withoutHoles(poly)) {
|
||||
out.push({
|
||||
kind: "polygon",
|
||||
pts,
|
||||
fill: SUN_SHADOW_FILL,
|
||||
stroke: "none",
|
||||
strokeWidthMm: 0,
|
||||
hatch: NO_HATCH,
|
||||
opacity: SUN_SHADOW_OPACITY,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
// Strichstärken nach Massstab ([32]): mit `Project.scaleLineWeights` werden alle Papier-mm-Stärken
|
||||
// eines Grundrisses mit (100/n)^0.25 skaliert — 1:200 ≈ 84 %, 1:50 ≈ 119 % (Vorgabe wie BIMCraft
|
||||
// `pen.rs`). So bleibt ein 1:200-Plan nicht zu schwer und ein 1:50-Plan nicht zu dünn, ohne eigene
|
||||
// Stiftsätze je Massstab.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import type { Primitive } from "./generatePlan/shared";
|
||||
|
||||
const REFERENCE_SCALE = 100;
|
||||
const MIN_FACTOR = 0.5;
|
||||
const MAX_FACTOR = 1.6;
|
||||
|
||||
/** Faktor für den Massstab 1:n (1 ohne Option oder bei ungültigem n). */
|
||||
export function lineWeightFactor(project: Project, scaleDenominator: number): number {
|
||||
if (!project.scaleLineWeights || !(scaleDenominator > 0) || !Number.isFinite(scaleDenominator)) return 1;
|
||||
const f = (REFERENCE_SCALE / scaleDenominator) ** 0.25;
|
||||
return Math.min(MAX_FACTOR, Math.max(MIN_FACTOR, f));
|
||||
}
|
||||
|
||||
// Je Quell-Primitiv die zuletzt erzeugte Skalierung: gleiche Eingabe → dasselbe Objekt, damit der
|
||||
// GPU-Chunk-Cache (`glPlanChunks.ts`) Primitive wiedererkennt.
|
||||
const scaledClones = new WeakMap<Primitive, { f: number; clone: Primitive }>();
|
||||
|
||||
/** Primitiv mit skalierten Strichstärken (Original bleibt unverändert). */
|
||||
export function scalePrimitiveWeights(p: Primitive, f: number): Primitive {
|
||||
if (f === 1) return p;
|
||||
const hit = scaledClones.get(p);
|
||||
if (hit && hit.f === f) return hit.clone;
|
||||
const c = { ...p } as Record<string, unknown>;
|
||||
if (typeof c.weightMm === "number") c.weightMm = c.weightMm * f;
|
||||
if (typeof c.strokeWidthMm === "number") c.strokeWidthMm = c.strokeWidthMm * f;
|
||||
const hatch = c.hatch as { lineWeight?: unknown } | undefined;
|
||||
if (hatch && typeof hatch.lineWeight === "number") c.hatch = { ...hatch, lineWeight: hatch.lineWeight * f };
|
||||
const clone = c as unknown as Primitive;
|
||||
scaledClones.set(p, { f, clone });
|
||||
return clone;
|
||||
}
|
||||
@@ -81,8 +81,8 @@ describe("lazy Plan", () => {
|
||||
expect(plan.primitives.length).toBe(planCount(plan));
|
||||
});
|
||||
|
||||
it("Mono bleibt eine gewöhnliche Liste", () => {
|
||||
it("Mono rechnet der Kern: auch dann bleibt der Plan lazy", () => {
|
||||
const plan = generatePlan(sampleProject, "eg", codes(sampleProject), undefined, "mittel", false, true);
|
||||
expect(isLazyUnread(plan)).toBe(false);
|
||||
expect(isLazyUnread(plan)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import type { Pair } from "../geometry/polygonBool";
|
||||
import { generatePlan } from "./generatePlan";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { ExtrudedSolid, Project } from "../model/types";
|
||||
import { keyhole, segmentOutside, subtractRings, subtractVoidsInSection, voidPrisms, voidSectionRects } from "./voids";
|
||||
import { keyhole, subtractRings, subtractVoidsInSection, voidPrisms, voidSectionRects } from "./voids";
|
||||
|
||||
const sq = (x0: number, y0: number, x1: number, y1: number): Pair[] => [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
|
||||
const area = (r: Pair[]) => Math.abs(r.reduce((s, p, i) => s + p[0] * r[(i + 1) % r.length][1] - r[(i + 1) % r.length][0] * p[1], 0) / 2);
|
||||
@@ -44,10 +44,6 @@ describe("Abzugskoerper — Polygon-Kern", () => {
|
||||
const k = keyhole([sq(0, 0, 10, 2), sq(1, 0.5, 2, 1.5).reverse(), sq(5, 0.5, 6, 1.5).reverse()]);
|
||||
expect(k.bridges).toHaveLength(4);
|
||||
});
|
||||
it("segmentOutside: Linie durch Quadrat in zwei Teile", () => {
|
||||
const parts = segmentOutside({ x: 0, y: 0.5 }, { x: 4, y: 0.5 }, [sq(1, 0, 2, 1)]);
|
||||
expect(parts.map(([a, b]) => [a, b])).toEqual([[0, 0.25], [0.5, 1]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Abzugskoerper — Grundriss und Schnitt", () => {
|
||||
|
||||
+2
-88
@@ -3,7 +3,8 @@
|
||||
// Ansichten aus demselben Modell:
|
||||
//
|
||||
// • Grundriss: Poché-Polygone der getroffenen Bauteile minus Körper-Grundfläche, sofern der
|
||||
// Körper die Schnitthöhe (Wände/Stützen) bzw. die Platte (Decken) durchdringt.
|
||||
// Körper die Schnitthöhe (Wände/Stützen) bzw. die Platte (Decken) durchdringt — rechnet der
|
||||
// Kern (`core/src/plan/extras.rs::subtract_voids`).
|
||||
// • Schnitt: Cut-Polygone minus Körper-Schnitt (Grundfläche ∩ Schnittspur × Höhenbereich).
|
||||
// • 3D/STEP: Boolean-Differenz (truck, Mesh-CSG-Fallback), s. `toWalls3d/voids3d.ts`
|
||||
// bzw. `exportStep.ts`.
|
||||
@@ -19,8 +20,6 @@ import type { Pair } from "../geometry/polygonBool";
|
||||
import { core } from "../engine/coreWasm";
|
||||
import type { ExtrudedSolid, Project, Vec2 } from "../model/types";
|
||||
import { getFloor } from "../model/types";
|
||||
import { ceilingVerticalExtent, columnVerticalExtent } from "../model/wall";
|
||||
import type { Primitive } from "./generatePlan/shared";
|
||||
import type { SolidSpec } from "../engine/truckSolid";
|
||||
import type { RWall } from "./toWalls3d/shared";
|
||||
|
||||
@@ -31,8 +30,6 @@ export interface VoidPrism {
|
||||
z1: number;
|
||||
}
|
||||
|
||||
const EPS = 1e-7;
|
||||
|
||||
/** Ob ein Körper als Abzugskörper wirkt (Prisma mit gültigem Profil). */
|
||||
export function isVoidSolid(s: ExtrudedSolid): boolean {
|
||||
return s.operation === "subtract" && !s.brep && (s.taper ?? 0) < 1e-6 && s.points.length >= 3 && s.height > 0;
|
||||
@@ -62,8 +59,6 @@ export function voidPrisms(project: Project): VoidPrism[] {
|
||||
|
||||
// ── Polygon-Booleans (Rust-Kern, `voids.rs`) ─────────────────────────────────
|
||||
|
||||
const ring = (pts: Vec2[]): Pair[] => pts.map((p) => [p.x, p.y] as Pair);
|
||||
|
||||
/** Ringliste flach für den Kern (`[n, (k, x, y …) × n]`). */
|
||||
function encodeRings(rings: Pair[][]): Float64Array {
|
||||
const b: number[] = [rings.length];
|
||||
@@ -121,87 +116,6 @@ export function subtractRings(
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Grundriss ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Teile der Strecke a→b ausserhalb aller Ringe, als Parameter-Intervalle [t0, t1]. */
|
||||
export function segmentOutside(a: Vec2, b: Vec2, cutters: Pair[][]): Array<[number, number]> {
|
||||
const f = core().voids_segment_outside_flat(Float64Array.from([a.x, a.y, b.x, b.y]), encodeRings(cutters));
|
||||
const out: Array<[number, number]> = [];
|
||||
for (let k = 0; k < (f[0] ?? 0); k++) out.push([f[1 + 2 * k], f[2 + 2 * k]]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Linien-Klassen der Wand-Poché, die ein Abzugskörper auf Schnitthöhe unterbricht. */
|
||||
const WALL_LINE_CLS = new Set(["wall-outline", "layer-joint", "layer-joint-l"]);
|
||||
|
||||
/**
|
||||
* Zieht die Abzugskörper von den Bauteil-Polygonen eines Grundrisses ab (in place).
|
||||
* Wände: wenn der Körper die Schnitthöhe `cutZ` durchdringt. Stützen: ebenso, über ihren
|
||||
* Höhenbereich. Decken: wenn der Körper die Platte durchdringt (Deckendurchbruch). Liefert, ob
|
||||
* Abzugskörper da waren (dann kann sich die Liste verändert haben).
|
||||
*/
|
||||
export function subtractVoidsInPlan(prims: Primitive[], project: Project, cutZ: number): boolean {
|
||||
const voids = voidPrisms(project);
|
||||
if (voids.length === 0) return false;
|
||||
const ceilings = new Map((project.ceilings ?? []).map((c) => [c.id, c]));
|
||||
const columns = new Map((project.columns ?? []).map((c) => [c.id, c]));
|
||||
const cuttersFor = (z0: number, z1: number): Pair[][] =>
|
||||
voids.filter((v) => v.z0 < z1 - EPS && v.z1 > z0 + EPS).map((v) => ring(v.pts));
|
||||
const wallCutters = cuttersFor(cutZ - 1e-4, cutZ + 1e-4);
|
||||
const out: Primitive[] = [];
|
||||
for (const pr of prims) {
|
||||
if (pr.kind === "line" && WALL_LINE_CLS.has(pr.cls) && wallCutters.length) {
|
||||
const parts = segmentOutside(pr.a, pr.b, wallCutters);
|
||||
const whole = parts.length === 1 && parts[0][0] === 0 && parts[0][1] === 1;
|
||||
if (whole) out.push(pr);
|
||||
else
|
||||
for (const [t0, t1] of parts) {
|
||||
const at = (t: number) => ({ x: pr.a.x + (pr.b.x - pr.a.x) * t, y: pr.a.y + (pr.b.y - pr.a.y) * t });
|
||||
out.push({ ...pr, a: at(t0), b: at(t1) });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (pr.kind !== "polygon" || pr.extrudedSolidId) {
|
||||
out.push(pr);
|
||||
continue;
|
||||
}
|
||||
let cutters: Pair[][] | null = null;
|
||||
if (pr.wallId) cutters = wallCutters;
|
||||
else if (pr.ceilingId) {
|
||||
const c = ceilings.get(pr.ceilingId);
|
||||
if (c) {
|
||||
const { zBottom, zTop } = ceilingVerticalExtent(project, c);
|
||||
cutters = cuttersFor(zBottom, zTop);
|
||||
}
|
||||
} else if (pr.columnId) {
|
||||
const c = columns.get(pr.columnId);
|
||||
if (c) {
|
||||
const { zBottom, zTop } = columnVerticalExtent(project, c);
|
||||
cutters = zBottom <= cutZ && zTop >= cutZ ? wallCutters : cuttersFor(zBottom, zTop);
|
||||
}
|
||||
}
|
||||
if (!cutters || cutters.length === 0) {
|
||||
out.push(pr);
|
||||
continue;
|
||||
}
|
||||
const rest = subtractRings(ring(pr.pts), cutters, pr.noStrokeEdges ?? []);
|
||||
if (rest === null) {
|
||||
out.push(pr);
|
||||
continue;
|
||||
}
|
||||
for (const r of rest) {
|
||||
out.push({
|
||||
...pr,
|
||||
pts: r.pts.map(([x, y]) => ({ x, y })),
|
||||
noStrokeEdges: r.noStrokeEdges.length ? r.noStrokeEdges : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
prims.length = 0;
|
||||
for (const p of out) prims.push(p);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Schnitt ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user