Merge [K3b] Plan-Puffer v1 und GPU-Kompilierung in Rust (plan_buf.rs, gpu_compile.rs, hatch.rs); K3b abgeschlossen

Laut Agent bitgleich (Vertex-/Index-Puffer, Batches; Beispielprojekt, 30 Zufallsprojekte, 460 Zufallslisten,
Landeskoordinaten). Trigonometrie im Web-Build ueber Math der JS-Engine (musl-libm wich ab). Schraffur ~2x,
100k Linien + 3000 Schraffurflaechen 3.9 -> 1.8 s, Beispiel-EG 1.5 -> 0.8 ms. Browser-Build startet geprueft.

Claude-Session: https://claude.ai/code/session_01NTYBZBvLYCtugMJoKXaB67
This commit is contained in:
Claude committed 2026-10-27 23:27:31 +00:00
commit 7a8af4f3bd
17 files changed
+3426 -1445

No files matched your search

+946
View File
@@ -0,0 +1,946 @@
//! GPU-Kompilierung des Grundrisses ([K3b], früher `glPlanCompile.ts`): Plan-Puffer
//! (`plan_buf`) → Vertex-/Index-Puffer und Zeichen-Batches für den nativen Metal-Renderer
//! (`native_embed.rs`/`render2d/chunks.rs`) und den WebGL-Pfad.
//!
//! - Polygone → Ear-Clipping (konkav-fähig) in Bildschirm-Raum (`sx = mx·90`, `sy = −my·90`),
//! relativ zum ersten abgelegten Punkt (lokaler Ursprung gegen f32-Auflösungsverlust).
//! - Striche → butt-endige Segment-Quads mit Normale + Seiten-Flag (bildschirmkonstante Breite
//! im Shader), runde Joins/Kappen als Fächer; Schraffur, Zickzack, Motive, Bögen und Kreise
//! werden vorher zu Linienzügen tesselliert (`hatch`).
//! - Batches: aufeinanderfolgende Indizes gleicher Farbe (+ Breite) werden zusammengefasst.
//!
//! Ausgabe (`compile_flat`) als EIN `u32`-Puffer (eine Kopie über die WASM-Grenze):
//! ```text
//! [M, 0, meta (M × f64 als je zwei u32, little-endian), fillPos (f32-Bits), fillIdx,
//! lineVerts (f32-Bits bzw. gepackt), lineIdx]
//! meta = [originX, originY, minX, minY, maxX, maxY, nFillPos, nFillIdx, nLineVerts, nLineIdx,
//! nFillBatches, nLineBatches,
//! nFillBatches × (start, count, r, g, b, a),
//! nLineBatches × (start, count, r, g, b, a, strokeMm, screenPx)]
//! ```
//! Linien-Vertices: 6 × f32 (x, y, nx, ny, side, miter=1) oder gepackt 3 Wörter (x, y als
//! f32-Bits, dann snorm8 nx | ny | side | miter=127).
//! Die Rechenreihenfolge folgt der TS-Fassung Operation für Operation: Vertex-Puffer bitgleich.
use crate::hatch::{self, v2, Hatch, HatchKind, Pattern, Run, V2, DASH_MM_TO_M};
use crate::jsmath::hypot2;
use crate::jsnum;
use crate::plan_buf::{self, PlanBuf, Prim, Style};
use std::f64::consts::PI;
const PX_PER_M: f64 = 90.0;
/// Grauton gedimmter Linien (wie `GREY_RGB` in `toRenderScene.ts`).
pub const GREY_RGB: f64 = 0.549;
const DEFAULT_INK: [f64; 4] = [0.1, 0.1, 0.1, 1.0];
type Rgba = [f64; 4];
pub struct FillBatch {
pub start: u32,
pub count: u32,
pub color: Rgba,
}
pub struct LineBatch {
pub start: u32,
pub count: u32,
pub color: Rgba,
pub stroke_mm: f64,
pub screen_px: bool,
}
/// Ergebnis der Kompilierung (Bildschirm-Raum relativ zu `origin`).
pub struct GpuOut {
pub fill_pos: Vec<f32>,
pub fill_idx: Vec<u32>,
pub fill_batches: Vec<FillBatch>,
/// f32-Bits (ungepackt, 6 je Vertex) bzw. gepackte Wörter (3 je Vertex).
pub line_verts: Vec<u32>,
pub line_idx: Vec<u32>,
pub line_batches: Vec<LineBatch>,
pub origin: (f64, f64),
/// Modell-Bounds (Meter): (minX, minY, maxX, maxY), ±∞ wenn leer.
pub bounds: (f64, f64, f64, f64),
}
// ── Triangulierung ─────────────────────────────────────────────────────────
fn signed_area(pts: &[V2]) -> f64 {
let n = pts.len();
let mut a = 0.0;
let mut j = n - 1;
for i in 0..n {
a += pts[j].x * pts[i].y - pts[i].x * pts[j].y;
j = i;
}
a / 2.0
}
#[inline]
fn cross(a: V2, b: V2, c: V2) -> f64 {
(b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}
#[inline]
fn point_in_tri(a: V2, b: V2, c: V2, p: V2) -> bool {
let d1 = cross(a, b, p);
let d2 = cross(b, c, p);
let d3 = cross(c, a, p);
let has_neg = d1 < 0.0 || d2 < 0.0 || d3 < 0.0;
let has_pos = d1 > 0.0 || d2 > 0.0 || d3 > 0.0;
!(has_neg && has_pos)
}
/// Ear-Clipping eines einfachen (lochfreien) Polygons, konvex oder konkav. Indizes auf `pts`;
/// leer bei < 3 Ecken. Enthalten-Test nur gegen reflexe Ecken, Ohren per verketteter Liste.
pub fn triangulate(pts: &[V2]) -> Vec<u32> {
let n = pts.len();
if n < 3 {
return Vec::new();
}
let mut order: Vec<usize> = (0..n).collect();
if signed_area(pts) < 0.0 {
order.reverse();
}
let mut next = vec![0usize; n];
let mut prev = vec![0usize; n];
for i in 0..n {
next[order[i]] = order[(i + 1) % n];
prev[order[i]] = order[(i + n - 1) % n];
}
// Reflex-Menge: Liste + Position (Reihenfolge ist für das Ergebnis belanglos — nur „liegt
// irgendeine reflexe Ecke im Ohr?“ zählt).
let mut reflex: Vec<usize> = Vec::new();
let mut pos = vec![usize::MAX; n];
let is_reflex = |i: usize, prev: &[usize], next: &[usize]| cross(pts[prev[i]], pts[i], pts[next[i]]) <= 0.0;
fn add(i: usize, reflex: &mut Vec<usize>, pos: &mut [usize]) {
if pos[i] == usize::MAX {
pos[i] = reflex.len();
reflex.push(i);
}
}
fn del(i: usize, reflex: &mut Vec<usize>, pos: &mut [usize]) {
let p = pos[i];
if p != usize::MAX {
let last = *reflex.last().unwrap();
reflex.swap_remove(p);
if last != i {
pos[last] = p;
}
pos[i] = usize::MAX;
}
}
for &i in &order {
if is_reflex(i, &prev, &next) {
add(i, &mut reflex, &mut pos);
}
}
let mut tris: Vec<u32> = Vec::new();
let mut remaining = n;
let mut i = order[0];
let mut no_ear_streak = 0usize;
let mut guard: u64 = 0;
let max_guard = (n as u64) * (n as u64) + 16;
while remaining > 3 && {
let g = guard;
guard += 1;
g < max_guard
} {
let a = prev[i];
let b = i;
let c = next[i];
let mut is_ear = pos[b] == usize::MAX;
if is_ear {
for &vi in &reflex {
if vi == a || vi == b || vi == c {
continue;
}
if point_in_tri(pts[a], pts[b], pts[c], pts[vi]) {
is_ear = false;
break;
}
}
}
if is_ear {
tris.extend_from_slice(&[a as u32, b as u32, c as u32]);
next[a] = c;
prev[c] = a;
del(b, &mut reflex, &mut pos);
remaining -= 1;
if is_reflex(a, &prev, &next) {
add(a, &mut reflex, &mut pos);
} else {
del(a, &mut reflex, &mut pos);
}
if is_reflex(c, &prev, &next) {
add(c, &mut reflex, &mut pos);
} else {
del(c, &mut reflex, &mut pos);
}
i = a;
no_ear_streak = 0;
} else {
i = c;
no_ear_streak += 1;
if no_ear_streak > remaining {
break;
}
}
}
if remaining == 3 {
tris.extend_from_slice(&[prev[i] as u32, i as u32, next[i] as u32]);
}
tris
}
// ── Farben ─────────────────────────────────────────────────────────────────
/// Gedimmt → fester Grauton; Objekt-Deckkraft in den Alphakanal (wie `dim` in TS).
fn dim(color: Rgba, s: &Style) -> Rgba {
let c = if s.greyed { [GREY_RGB, GREY_RGB, GREY_RGB, color[3]] } else { color };
match s.opacity {
Some(o) if !(o >= 1.0) => [c[0], c[1], c[2], c[3] * jsnum::max(0.0, o)],
_ => c,
}
}
/// Wie `dim`, aber gedimmte Flächen bleiben weiss.
fn dim_fill(color: Rgba, s: &Style) -> Rgba {
let c = if s.greyed { [1.0, 1.0, 1.0, color[3]] } else { color };
match s.opacity {
Some(o) if !(o >= 1.0) => [c[0], c[1], c[2], c[3] * jsnum::max(0.0, o)],
_ => c,
}
}
#[inline]
fn same_rgba(a: &Rgba, b: &Rgba) -> bool {
a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3]
}
/// `weightMm || 0.18`.
#[inline]
fn weight_or_default(w: f64) -> f64 {
if w == 0.0 || w.is_nan() {
0.18
} else {
w
}
}
/// `Math.round(Math.max(-1, Math.min(1, v)) * 127) & 0xff`. Der Wert liegt in [−127, 127], NaN
/// ergibt 0; das Vorzeichen einer Null spielt nach `& 0xff` keine Rolle.
#[inline]
fn snorm8(v: f64) -> u32 {
if v.is_nan() {
return 0;
}
let x = (if v > 1.0 {
1.0
} else if v < -1.0 {
-1.0
} else {
v
}) * 127.0;
let c = x.ceil();
let r = if c - 0.5 > x { c - 1.0 } else { c };
((r as i32) & 0xff) as u32
}
/// Gepacktes Normalen-Wort: snorm8 nx | ny | side | miter (=127).
#[inline]
fn normal_word(nx: f64, ny: f64, side: f64) -> u32 {
snorm8(nx) | (snorm8(ny) << 8) | (snorm8(side) << 16) | (127 << 24)
}
/// Fächer-Zentrum (1, 0, 0) gepackt.
const CENTER_WORD: u32 = 127 | (127 << 24);
#[inline]
fn left_normal(d: V2) -> V2 {
v2(-d.y, d.x)
}
// ── Kompilierer ────────────────────────────────────────────────────────────
struct Compiler {
packed: bool,
fill_pos: Vec<f32>,
fill_idx: Vec<u32>,
fill_batches: Vec<FillBatch>,
line_verts: Vec<u32>,
line_idx: Vec<u32>,
line_batches: Vec<LineBatch>,
origin_x: f64,
origin_y: f64,
origin_set: bool,
min_x: f64,
min_y: f64,
max_x: f64,
max_y: f64,
/// Wiederverwendeter Punktpuffer für `stroke_polyline`.
scratch: Vec<V2>,
seg_dir: Vec<Option<V2>>,
seg_ang: Vec<[Option<f64>; 2]>,
}
impl Compiler {
#[inline]
fn scr(&mut self, p: V2) -> V2 {
let sx = p.x * PX_PER_M;
let sy = -p.y * PX_PER_M;
if !self.origin_set {
self.origin_x = sx;
self.origin_y = sy;
self.origin_set = true;
}
v2(sx - self.origin_x, sy - self.origin_y)
}
#[inline]
fn track(&mut self, mx: f64, my: f64) {
if mx < self.min_x {
self.min_x = mx;
}
if my < self.min_y {
self.min_y = my;
}
if mx > self.max_x {
self.max_x = mx;
}
if my > self.max_y {
self.max_y = my;
}
}
fn add_fill_batch(&mut self, count: usize, color: Rgba) {
if let Some(last) = self.fill_batches.last_mut() {
if same_rgba(&last.color, &color) {
last.count += count as u32;
return;
}
}
self.fill_batches.push(FillBatch { start: (self.fill_idx.len() - count) as u32, count: count as u32, color });
}
fn add_line_batch(&mut self, count: usize, color: Rgba, stroke_mm: f64, screen_px: bool) {
if let Some(last) = self.line_batches.last_mut() {
if last.stroke_mm == stroke_mm && last.screen_px == screen_px && same_rgba(&last.color, &color) {
last.count += count as u32;
return;
}
}
self.line_batches.push(LineBatch { start: (self.line_idx.len() - count) as u32, count: count as u32, color, stroke_mm, screen_px });
}
#[inline]
fn push_vert(&mut self, p: V2, nx: f64, ny: f64, side: f64) -> u32 {
let w = if self.packed { normal_word(nx, ny, side) } else { 0 };
self.push_vert_w(p, w, nx, ny, side)
}
/// Wie `push_vert`, mit bereits gepacktem Normalen-Wort `w` (nur im gepackten Layout benutzt).
#[inline]
fn push_vert_w(&mut self, p: V2, w: u32, nx: f64, ny: f64, side: f64) -> u32 {
if self.packed {
self.line_verts.extend_from_slice(&[(p.x as f32).to_bits(), (p.y as f32).to_bits(), w]);
(self.line_verts.len() / 3 - 1) as u32
} else {
self.line_verts.extend_from_slice(&[
(p.x as f32).to_bits(),
(p.y as f32).to_bits(),
(nx as f32).to_bits(),
(ny as f32).to_bits(),
(side as f32).to_bits(),
1.0f32.to_bits(),
]);
(self.line_verts.len() / 6 - 1) as u32
}
}
/// Kreisbogen-Fächer um `p` (Radius = halbe Strichbreite im Shader).
fn add_fan_arc(&mut self, p: V2, a_from: f64, a_to: f64, stroke_mm: f64) {
let delta = a_to - a_from;
let step_angle = if stroke_mm <= 0.35 { PI / 3.0 } else { PI / 10.0 };
let steps = jsnum::max(1.0, (delta.abs() / step_angle).ceil());
let i_center = self.push_vert_w(p, CENTER_WORD, 1.0, 0.0, 0.0);
let mut prev = self.push_vert(p, jsnum::cos(a_from), jsnum::sin(a_from), 1.0);
let mut s = 1.0;
while s <= steps {
let t = a_from + (delta * s) / steps;
let cur = self.push_vert(p, jsnum::cos(t), jsnum::sin(t), 1.0);
self.line_idx.extend_from_slice(&[i_center, prev, cur]);
prev = cur;
s += 1.0;
}
}
/// Zusammenhängender Linienzug (Modell-Meter) mit runden Kappen/Ecken.
fn stroke_polyline(&mut self, pts_m: &[V2], closed: bool, color: Rgba, stroke_mm: f64, screen_px: bool) {
let mut s_pts = std::mem::take(&mut self.scratch);
s_pts.clear();
for &p in pts_m {
let s = self.scr(p);
if let Some(l) = s_pts.last() {
if (l.x - s.x).abs() < 1e-6 && (l.y - s.y).abs() < 1e-6 {
continue;
}
}
s_pts.push(s);
self.track(p.x, p.y);
}
if closed && s_pts.len() > 1 {
let f = s_pts[0];
let l = s_pts[s_pts.len() - 1];
if (f.x - l.x).abs() < 1e-6 && (f.y - l.y).abs() < 1e-6 {
s_pts.pop();
}
}
let k = s_pts.len();
if k < 2 {
self.scratch = s_pts;
return;
}
let start_idx_len = self.line_idx.len();
let segs = if closed { k } else { k - 1 };
let mut seg_dir = std::mem::take(&mut self.seg_dir);
seg_dir.clear();
for i in 0..segs {
let from = s_pts[i];
let to = s_pts[(i + 1) % k];
let dx = to.x - from.x;
let dy = to.y - from.y;
let len = hypot2(dx, dy);
seg_dir.push(if len < 1e-9 { None } else { Some(v2(dx / len, dy / len)) });
}
for i in 0..segs {
let Some(d) = seg_dir[i] else { continue };
let n = left_normal(d);
let a = s_pts[i];
let b = s_pts[(i + 1) % k];
let (wp, wm) = if self.packed { (normal_word(n.x, n.y, 1.0), normal_word(n.x, n.y, -1.0)) } else { (0, 0) };
let i0 = self.push_vert_w(a, wp, n.x, n.y, 1.0);
let i1 = self.push_vert_w(a, wm, n.x, n.y, -1.0);
let i2 = self.push_vert_w(b, wp, n.x, n.y, 1.0);
let i3 = self.push_vert_w(b, wm, n.x, n.y, -1.0);
self.line_idx.extend_from_slice(&[i0, i1, i2, i1, i3, i2]);
}
// Winkel der (ggf. gespiegelten) Segment-Normalen: jede Normale dient zwei Ecken bzw.
// einer Ecke und einer Kappe — `atan2` nur einmal je Segment und Richtung (gleiche
// Eingabe, also derselbe Wert).
let mut seg_ang = std::mem::take(&mut self.seg_ang);
seg_ang.clear();
seg_ang.resize(segs, [None, None]);
let mut ang = |seg: usize, sign: f64| -> f64 {
let slot = if sign > 0.0 { 0 } else { 1 };
if let Some(a) = seg_ang[seg][slot] {
return a;
}
let n = left_normal(seg_dir[seg].unwrap_or(v2(0.0, 0.0)));
let a = jsnum::atan2(sign * n.y, sign * n.x);
seg_ang[seg][slot] = Some(a);
a
};
for v in 0..k {
let has_in = closed || v > 0;
let has_out = closed || v < k - 1;
let i_in = (v + segs - 1) % segs;
let i_out = v % segs;
let d_in = if has_in { seg_dir[i_in] } else { None };
let d_out = if has_out { seg_dir[i_out] } else { None };
let p = s_pts[v];
match (d_in, d_out) {
(Some(d1), Some(d2)) => {
// Runder Übergang nur auf der äusseren Seite der Ecke.
let turn = d1.x * d2.y - d1.y * d2.x;
let dot = d1.x * d2.x + d1.y * d2.y;
if turn.abs() < 1e-6 && dot > 0.0 {
continue;
}
if dot < -0.9999 {
// ~180°-Umkehr: voller Kreis.
let a0 = ang(i_in, 1.0);
self.add_fan_arc(p, a0, a0 + 2.0 * PI, stroke_mm);
continue;
}
let outer = if turn > 0.0 { -1.0 } else { 1.0 };
let a1 = ang(i_in, outer);
let a2 = ang(i_out, outer);
let mut delta = a2 - a1;
while delta <= -PI {
delta += 2.0 * PI;
}
while delta > PI {
delta -= 2.0 * PI;
}
if delta.abs() < 1e-4 {
continue;
}
self.add_fan_arc(p, a1, a1 + delta, stroke_mm);
}
// Runde Kappen an offenen Enden (Start bulgt rückwärts, Ende vorwärts).
(None, Some(_)) => {
let a0 = ang(i_out, 1.0);
self.add_fan_arc(p, a0, a0 + PI, stroke_mm);
}
(Some(_), None) => {
let a0 = ang(i_in, 1.0);
self.add_fan_arc(p, a0, a0 + -PI, stroke_mm);
}
(None, None) => {}
}
}
let count = self.line_idx.len() - start_idx_len;
self.add_line_batch(count, color, stroke_mm, screen_px);
self.scratch = s_pts;
self.seg_dir = seg_dir;
self.seg_ang = seg_ang;
}
/// Polygon-Umriss ohne die Kanten in `no_stroke` (offene Züge, gerade Enden an Lücken).
fn stroke_polygon_outline(&mut self, pts: &[V2], color: Rgba, stroke_mm: f64, no_stroke: &[f64]) {
let n = pts.len();
if no_stroke.is_empty() || n < 2 {
self.stroke_polyline(pts, true, color, stroke_mm, false);
return;
}
let nf = n as f64;
// Menge wie `new Set(noStroke.map(i => ((i % n) + n) % n))` (SameValueZero).
let mut keys: Vec<f64> = no_stroke
.iter()
.map(|&i| {
let k = ((i % nf) + nf) % nf;
// −0/+0 und alle NaN sind je derselbe Schlüssel.
if k.is_nan() {
f64::NAN
} else if k == 0.0 {
0.0
} else {
k
}
})
.collect();
let mut skip = vec![false; n];
for &kk in &keys {
if kk >= 0.0 && kk < nf && kk.fract() == 0.0 {
skip[kk as usize] = true;
}
}
keys.sort_by(|a, b| a.total_cmp(b));
keys.dedup_by(|a, b| a.to_bits() == b.to_bits());
if keys.len() >= n {
return;
}
let visible = |i: usize| !skip[i % n];
let mut run: Vec<V2> = Vec::new();
for s in 0..n {
if !visible(s) || visible(s + n - 1) {
continue;
}
run.clear();
run.push(pts[s]);
let mut j = s;
while visible(j) {
run.push(pts[(j + 1) % n]);
j += 1;
if j - s >= n {
break;
}
}
self.stroke_polyline(&run, false, color, stroke_mm, false);
}
}
fn push_fill(&mut self, pts: &[V2], tris: &[u32], color: Rgba) {
let base = (self.fill_pos.len() / 2) as u32;
for &pt in pts {
let s = self.scr(pt);
self.fill_pos.push(s.x as f32);
self.fill_pos.push(s.y as f32);
self.track(pt.x, pt.y);
}
for &t in tris {
self.fill_idx.push(base + t);
}
self.add_fill_batch(tris.len(), color);
}
}
/// Segmentzahl eines Bogens: Sagitta < ~0.5 px über `px_per_meter`, sonst fester Rückfall.
fn arc_segments(r: f64, sweep_abs: f64, px_per_meter: f64, min_fallback: f64) -> f64 {
if px_per_meter > 0.0 {
let r_px = r * px_per_meter;
let theta = if r_px > 0.5 { 2.0 * jsnum::acos(1.0 - 0.5 / r_px) } else { PI };
jsnum::min(2048.0, jsnum::max(8.0, (sweep_abs / theta).ceil()))
} else {
jsnum::max(min_fallback, ((sweep_abs / (PI / 2.0)) * 16.0).ceil())
}
}
fn color_or_ink(plan: &PlanBuf, idx: i32) -> Rgba {
plan.color(idx).unwrap_or(DEFAULT_INK)
}
/// Hatch zeichnet Musterlinien (nicht Bild/Verlauf, nicht none/solid)?
fn hatch_draws_lines(h: &Hatch) -> bool {
h.kind != HatchKind::Image && h.kind != HatchKind::Gradient && h.pattern != Pattern::None && h.pattern != Pattern::Solid
}
/// Kompiliert die Primitive eines Plan-Puffers. `px_per_meter` steuert nur die Bogen-
/// Tessellierung (0 = zoomunabhängig). `packed` = kompakte Linien-Vertices (nativer Renderer).
pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut {
let mut c = Compiler {
packed,
fill_pos: Vec::new(),
fill_idx: Vec::new(),
fill_batches: Vec::new(),
line_verts: Vec::new(),
line_idx: Vec::new(),
line_batches: Vec::new(),
origin_x: 0.0,
origin_y: 0.0,
origin_set: false,
min_x: f64::INFINITY,
min_y: f64::INFINITY,
max_x: f64::NEG_INFINITY,
max_y: f64::NEG_INFINITY,
scratch: Vec::new(),
seg_dir: Vec::new(),
seg_ang: Vec::new(),
};
let prims = &plan.prims;
let plain_line = |p: &Prim| matches!(p, Prim::Line { zigzag: None, motif: None, .. });
// Zusammenhängende, gleich gestylte Einzel-Linien eines Elements als EIN Zug (zwei echte
// Kappen statt 2N). Läuft VOR allen anderen Primitiven, wie in der TS-Fassung.
let mut merged = vec![false; prims.len()];
let mut pts: Vec<V2> = Vec::new();
let mut i = 0;
while i < prims.len() {
let Prim::Line { style, color, weight_mm, a, b, zigzag: None, motif: None, .. } = &prims[i] else {
i += 1;
continue;
};
pts.clear();
pts.push(*a);
pts.push(*b);
let mut j = i + 1;
while j < prims.len() {
match &prims[j] {
Prim::Line { chain: true, a: aj, b: bj, .. } if plain_line(&prims[j]) => {
let last = pts[pts.len() - 1];
if aj.x != last.x || aj.y != last.y {
break;
}
pts.push(*bj);
j += 1;
}
_ => break,
}
}
if j - i > 1 {
let col = dim(color_or_ink(plan, *color), style);
c.stroke_polyline(&pts, false, col, weight_or_default(*weight_mm), false);
for m in merged.iter_mut().take(j).skip(i) {
*m = true;
}
}
i = j;
}
for (idx, prim) in prims.iter().enumerate() {
if merged[idx] {
continue;
}
match prim {
Prim::Placeholder => {}
Prim::Polygon { style, fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges } => {
if let Some(fc) = plan.color(*fill) {
let tris = triangulate(pts);
if !tris.is_empty() {
c.push_fill(pts, &tris, dim_fill(fc, style));
}
}
if let Some(h) = (*hatch >= 0).then(|| plan.hatches.get(*hatch as usize)).flatten() {
if hatch_draws_lines(&h.hatch) {
let hatch_color = dim(color_or_ink(plan, h.color), style);
let hatch_mm = if h.hatch.line_weight > 0.0 { h.hatch.line_weight } else { 0.13 };
let runs: Vec<Run> = hatch::apply_dash_runs(hatch::build_hatch_runs(pts, &h.hatch), &h.hatch.dash);
for run in &runs {
c.stroke_polyline(run, false, hatch_color, hatch_mm, false);
}
}
}
if let Some(sc) = plan.color(*stroke) {
if *stroke_width_mm > 0.0 && pts.len() >= 2 {
c.stroke_polygon_outline(pts, dim(sc, style), *stroke_width_mm, no_stroke_edges);
}
}
}
Prim::Line { style, color, weight_mm, a, b, zigzag, motif, .. } => {
let col = dim(color_or_ink(plan, *color), style);
let w = weight_or_default(*weight_mm);
if let Some((amp, wav)) = zigzag {
let zpts = hatch::zigzag_points(*a, *b, amp * DASH_MM_TO_M, wav * DASH_MM_TO_M).unwrap_or_else(|| vec![*a, *b]);
c.stroke_polyline(&zpts, false, col, w, false);
} else if let Some(m) = motif {
let mpts = hatch::motif_points(*a, *b, m, DASH_MM_TO_M);
c.stroke_polyline(&mpts, false, col, w, false);
} else {
c.stroke_polyline(&[*a, *b], false, col, w, false);
}
}
Prim::Arc { style, color, weight_mm, center, from, to, r, .. } => {
let col = dim(color_or_ink(plan, *color), style);
let stroke_mm = weight_or_default(*weight_mm);
let a0 = jsnum::atan2(from.y - center.y, from.x - center.x);
let a1 = jsnum::atan2(to.y - center.y, to.x - center.x);
let mut d = a1 - a0;
while d <= -PI {
d += 2.0 * PI;
}
while d > PI {
d -= 2.0 * PI;
}
let segs = arc_segments(*r, d.abs(), px_per_meter, 4.0);
let mut arc_pts = vec![*from];
let mut k = 1.0;
while k <= segs {
let t = a0 + (d * k) / segs;
arc_pts.push(v2(center.x + r * jsnum::cos(t), center.y + r * jsnum::sin(t)));
k += 1.0;
}
c.stroke_polyline(&arc_pts, false, col, stroke_mm, false);
}
Prim::Circle { style, fill, stroke, weight_mm, center, r, .. } => {
draw_circle_like(&mut c, plan, style, Some(*fill), *stroke, *weight_mm, *center, *r, None, px_per_meter);
}
Prim::DrawingArc { style, stroke, weight_mm, center, r, a0, a1, .. } => {
draw_circle_like(&mut c, plan, style, None, *stroke, *weight_mm, *center, *r, Some((*a0, *a1)), px_per_meter);
}
}
}
GpuOut {
fill_pos: c.fill_pos,
fill_idx: c.fill_idx,
fill_batches: c.fill_batches,
line_verts: c.line_verts,
line_idx: c.line_idx,
line_batches: c.line_batches,
origin: (c.origin_x, c.origin_y),
bounds: (c.min_x, c.min_y, c.max_x, c.max_y),
}
}
/// 2D-Kreis (`fill` gesetzt, geschlossen) bzw. 2D-Bogen (`arc` = (a0, a1), CCW, offen).
#[allow(clippy::too_many_arguments)]
fn draw_circle_like(
c: &mut Compiler,
plan: &PlanBuf,
style: &Style,
fill: Option<i32>,
stroke: i32,
weight_mm: f64,
center: V2,
r: f64,
arc: Option<(f64, f64)>,
px_per_meter: f64,
) {
let stroke_col = dim(color_or_ink(plan, stroke), style);
let stroke_mm = weight_or_default(weight_mm);
const TAU: f64 = PI * 2.0;
let (a0, sweep) = match arc {
Some((a0, a1)) => {
let s = ((a1 - a0) % TAU + TAU) % TAU;
(a0, if s == 0.0 || s.is_nan() { TAU } else { s })
}
None => (0.0, TAU),
};
let segs = arc_segments(r, sweep, px_per_meter, 8.0);
let mut pts = Vec::new();
let mut i = 0.0;
while i <= segs {
let t = a0 + (sweep * i) / segs;
pts.push(v2(center.x + r * jsnum::cos(t), center.y + r * jsnum::sin(t)));
i += 1.0;
}
if let Some(fi) = fill {
if let Some(fc) = plan.color(fi) {
// Ring ohne den doppelten Schlusspunkt (`pts.slice(0, segs)`).
let n = if segs >= 0.0 { (segs as usize).min(pts.len()) } else { 0 };
let ring = &pts[..n];
let tris = triangulate(ring);
if !tris.is_empty() {
c.push_fill(ring, &tris, dim_fill(fc, style));
}
}
}
c.stroke_polyline(&pts, fill.is_some(), stroke_col, stroke_mm, false);
}
/// Flache Ausgabe (s. Modulkopf); leer bei unlesbarem Plan-Puffer.
pub fn compile_flat(buf: &[f64], px_per_meter: f64, packed: bool) -> Vec<u32> {
let Some(plan) = plan_buf::decode(buf) else { return Vec::new() };
let o = compile(&plan, px_per_meter, packed);
let mut meta: Vec<f64> = vec![
o.origin.0,
o.origin.1,
o.bounds.0,
o.bounds.1,
o.bounds.2,
o.bounds.3,
o.fill_pos.len() as f64,
o.fill_idx.len() as f64,
o.line_verts.len() as f64,
o.line_idx.len() as f64,
o.fill_batches.len() as f64,
o.line_batches.len() as f64,
];
for b in &o.fill_batches {
meta.extend_from_slice(&[b.start as f64, b.count as f64, b.color[0], b.color[1], b.color[2], b.color[3]]);
}
for b in &o.line_batches {
meta.extend_from_slice(&[
b.start as f64,
b.count as f64,
b.color[0],
b.color[1],
b.color[2],
b.color[3],
b.stroke_mm,
if b.screen_px { 1.0 } else { 0.0 },
]);
}
let mut out = Vec::with_capacity(2 + meta.len() * 2 + o.fill_pos.len() + o.fill_idx.len() + o.line_verts.len() + o.line_idx.len());
out.push(meta.len() as u32);
out.push(0);
for m in &meta {
let bits = m.to_bits();
out.push(bits as u32);
out.push((bits >> 32) as u32);
}
out.extend(o.fill_pos.iter().map(|v| v.to_bits()));
out.extend_from_slice(&o.fill_idx);
out.extend_from_slice(&o.line_verts);
out.extend_from_slice(&o.line_idx);
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plan_buf::HatchEntry;
fn st() -> Style {
Style { greyed: false, opacity: None }
}
fn line(ax: f64, bx: f64, chain: bool) -> Prim {
Prim::Line {
style: st(),
color: 0,
weight_mm: 0.18,
a: v2(ax, 0.0),
b: v2(bx, 0.0),
dash: vec![],
chain,
zigzag: None,
motif: None,
}
}
fn plan(prims: Vec<Prim>) -> PlanBuf {
PlanBuf { colors: vec![[0.0, 0.0, 0.0, 1.0], [0.5, 0.5, 0.5, 1.0]], hatches: vec![], prims }
}
fn line_idx_count(p: &PlanBuf) -> u32 {
compile(p, 90.0, false).line_batches.iter().map(|b| b.count).sum()
}
#[test]
fn triangulierung_konvex_konkav() {
let sq = [v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)];
assert_eq!(triangulate(&sq).len(), 6);
let l = [v2(0.0, 0.0), v2(2.0, 0.0), v2(2.0, 1.0), v2(1.0, 1.0), v2(1.0, 2.0), v2(0.0, 2.0)];
let t = triangulate(&l);
assert_eq!(t.len(), 12);
let area: f64 = t.chunks(3).map(|c| cross(l[c[0] as usize], l[c[1] as usize], l[c[2] as usize]).abs() / 2.0).sum();
assert!((area - 3.0).abs() < 1e-12);
let mut cw = l;
cw.reverse();
assert_eq!(triangulate(&cw).len(), 12);
assert!(triangulate(&sq[..2]).is_empty());
}
#[test]
fn linienzug_wird_zusammengefasst() {
let single = line_idx_count(&plan(vec![line(0.0, 1.0, false)]));
let merged = line_idx_count(&plan(vec![line(0.0, 1.0, false), line(1.0, 2.0, true), line(2.0, 3.0, true)]));
assert_eq!(merged, single + 2 * 6);
let apart = line_idx_count(&plan(vec![line(0.0, 1.0, false), line(1.0, 2.0, false)]));
assert_eq!(apart, 2 * single);
}
#[test]
fn polygon_mit_fuellung_schraffur_umriss() {
let mut p = plan(vec![Prim::Polygon {
style: Style { greyed: true, opacity: Some(0.5) },
fill: 1,
stroke: 0,
stroke_width_mm: 0.5,
hatch: 0,
pts: vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)],
no_stroke_edges: vec![0.0],
}]);
p.hatches.push(HatchEntry {
hatch: Hatch {
pattern: Pattern::Diagonal,
kind: HatchKind::Vector,
random: false,
scale: 1.0,
angle: 45.0,
line_weight: 0.0,
origin: None,
seed: None,
density: None,
length_min: None,
length_max: None,
dash: vec![],
motif: None,
},
color: -1,
});
let o = compile(&p, 90.0, true);
assert_eq!(o.fill_idx.len(), 6);
assert_eq!(o.fill_batches[0].color, [1.0, 1.0, 1.0, 0.5]);
// Schraffur (0.13 mm, grau) und Umriss (0.5 mm) als eigene Batches.
assert_eq!(o.line_batches.len(), 2);
assert_eq!(o.line_batches[0].color, [GREY_RGB, GREY_RGB, GREY_RGB, 0.5]);
assert_eq!(o.line_batches[0].stroke_mm, 0.13);
assert_eq!(o.line_batches[1].stroke_mm, 0.5);
assert_eq!(o.line_verts.len() % 3, 0);
assert_eq!(o.origin, (0.0, 0.0));
}
#[test]
fn kreis_und_bogen() {
let p = plan(vec![
Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0, dash: vec![] },
Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.5, center: v2(0.0, 0.0), r: 1.0, a0: 0.0, a1: 0.0, dash: vec![] },
Prim::Placeholder,
]);
let o = compile(&p, 0.0, false);
assert!(!o.fill_idx.is_empty());
assert_eq!(o.line_batches.len(), 2);
assert_eq!(o.bounds, (-1.0, -1.0, 2.0, 2.0));
}
#[test]
fn kaputter_puffer_leer() {
assert!(compile_flat(&[1.0, 2.0, 3.0], 90.0, true).is_empty());
let enc = plan_buf::encode(&plan(vec![line(0.0, f64::NAN, false)]));
let out = compile_flat(&enc, 90.0, true);
assert!(!out.is_empty());
}
}
+786
View File
@@ -0,0 +1,786 @@
//! Schraffur- und Linienmuster-Geometrie des Grundrisses ([K3b], früher `glPlanHatch.ts`):
//! Linie/Segment/Polylinie gegen ein (konkaves) Polygon clippen (even-odd, halb-offene Kanten),
//! Geradenscharen (diagonal/kreuz/eigenes Motiv), Dämmungswelle, deterministische Random-
//! Schraffur (mulberry32, modellraum-stabil), Strichmuster (`apply_dash_runs`), Zickzack und
//! Motiv-Kachelung entlang einer Strecke.
//!
//! Alles in Modell-Metern; die Muster bilden die SVG-`<pattern>`-Kacheln 1:1 nach (Bildschirm-
//! Raum `sx = mx·90`, Kachel 8·scale px bzw. 14×10·scale px). Die Rechenreihenfolge folgt der
//! TS-Fassung Operation für Operation (Bitgleichheit, s. `jsnum`).
use crate::jsmath::hypot2;
use crate::jsnum;
use std::f64::consts::PI;
/// Punkt in Modell-Metern.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct V2 {
pub x: f64,
pub y: f64,
}
#[inline]
pub const fn v2(x: f64, y: f64) -> V2 {
V2 { x, y }
}
/// Zusammenhängender Linienzug (≥ 2 Punkte).
pub type Run = Vec<V2>;
/// Bildschirm-Einheiten je Meter (wie `PlanView.toScreen`).
pub const PX_PER_M: f64 = 90.0;
/// px (Bildschirm-Raum) → Meter.
pub const PX_TO_M: f64 = 1.0 / PX_PER_M;
/// mm-Papier → Modell-Meter des Musterraums (wie SVG-`dashArray`: `dash·(1/0.13)` px).
pub const DASH_MM_TO_M: f64 = (1.0 / 0.13) * PX_TO_M;
/// Muster einer Schraffur (`HatchPattern`). Unbekannte Muster zeichnen wie `Diagonal`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Pattern {
None = 0,
Solid = 1,
Diagonal = 2,
Crosshatch = 3,
Insulation = 4,
Custom = 5,
}
impl Pattern {
pub fn from_code(c: f64) -> Pattern {
match c as i64 {
0 => Pattern::None,
1 => Pattern::Solid,
3 => Pattern::Crosshatch,
4 => Pattern::Insulation,
5 => Pattern::Custom,
_ => Pattern::Diagonal,
}
}
}
/// Schraffur-Typ (`HatchRender.kind`): Vektor, Bild, Verlauf. Bild/Verlauf zeichnet die GPU
/// nicht als Linien (Rückfall auf die Füllung).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HatchKind {
Vector = 0,
Image = 1,
Gradient = 2,
}
impl HatchKind {
pub fn from_code(c: f64) -> HatchKind {
match c as i64 {
1 => HatchKind::Image,
2 => HatchKind::Gradient,
_ => HatchKind::Vector,
}
}
}
/// Wiederhol-Motiv: offene Polylinie einer Einheitszelle, `x` entlang, `y` quer.
#[derive(Clone, Debug, PartialEq)]
pub struct Motif {
pub points: Vec<V2>,
pub length: f64,
}
/// Aufgelöste Schraffur (`HatchRender`) ohne Farbe/Bild/Verlauf-Details.
#[derive(Clone, Debug, PartialEq)]
pub struct Hatch {
pub pattern: Pattern,
pub kind: HatchKind,
/// `lines === "random"`.
pub random: bool,
pub scale: f64,
pub angle: f64,
pub line_weight: f64,
pub origin: Option<V2>,
pub seed: Option<f64>,
pub density: Option<f64>,
pub length_min: Option<f64>,
pub length_max: Option<f64>,
/// Strichmuster der Musterlinien (mm); leer = durchgezogen.
pub dash: Vec<f64>,
pub motif: Option<Motif>,
}
// ── Clipping ────────────────────────────────────────────────────────────────
fn bbox(poly: &[V2]) -> (f64, f64, f64, f64) {
let (mut min_x, mut min_y, mut max_x, mut max_y) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for p in poly {
if p.x < min_x {
min_x = p.x;
}
if p.y < min_y {
min_y = p.y;
}
if p.x > max_x {
max_x = p.x;
}
if p.y > max_y {
max_y = p.y;
}
}
(min_x, min_y, max_x, max_y)
}
/// Unendliche Linie (Aufpunkt `p0`, Einheitsrichtung `dir`) gegen ein einfaches Polygon:
/// innenliegende Segmente (even-odd, halb-offene Kantenkonvention an Ecken).
pub fn clip_line_to_polygon(p0: V2, dir: V2, poly: &[V2]) -> Vec<(V2, V2)> {
let n = poly.len();
if n < 3 {
return Vec::new();
}
let nx = -dir.y;
let ny = dir.x;
let side = |p: V2| (p.x - p0.x) * nx + (p.y - p0.y) * ny;
let mut ts: Vec<f64> = Vec::new();
for i in 0..n {
let a = poly[i];
let b = poly[(i + 1) % n];
let sa = side(a);
let sb = side(b);
if sa > 0.0 && sb > 0.0 {
continue;
}
if sa < 0.0 && sb < 0.0 {
continue;
}
if sa == 0.0 && sb == 0.0 {
continue;
}
if sa == 0.0 && sb < 0.0 {
continue;
}
if sb == 0.0 && sa < 0.0 {
continue;
}
let denom = sa - sb;
let u = if denom != 0.0 { sa / denom } else { 0.0 };
let ix = a.x + (b.x - a.x) * u;
let iy = a.y + (b.y - a.y) * u;
ts.push((ix - p0.x) * dir.x + (iy - p0.y) * dir.y);
}
if ts.len() < 2 {
return Vec::new();
}
// Wie `Array.sort((x, y) => x - y)`: stabil, NaN-Vergleiche zählen als gleich.
ts.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal));
let mut segs = Vec::new();
let mut i = 0;
while i + 1 < ts.len() {
let t0 = ts[i];
let t1 = ts[i + 1];
i += 2;
if t1 - t0 < 1e-9 {
continue;
}
segs.push((v2(p0.x + dir.x * t0, p0.y + dir.y * t0), v2(p0.x + dir.x * t1, p0.y + dir.y * t1)));
}
segs
}
/// Endliches Segment [a,b] gegen ein (konkaves) Polygon: innenliegende Teilstücke.
pub fn clip_segment_to_polygon(a: V2, b: V2, poly: &[V2]) -> Vec<(V2, V2)> {
let dx = b.x - a.x;
let dy = b.y - a.y;
let len = hypot2(dx, dy);
if len < 1e-12 {
return Vec::new();
}
let dir = v2(dx / len, dy / len);
let mut out = Vec::new();
for (sa, sb) in clip_line_to_polygon(a, dir, poly) {
let t0 = (sa.x - a.x) * dir.x + (sa.y - a.y) * dir.y;
let t1 = (sb.x - a.x) * dir.x + (sb.y - a.y) * dir.y;
let lo = jsnum::max(0.0, jsnum::min(t0, t1));
let hi = jsnum::min(len, jsnum::max(t0, t1));
if hi - lo < 1e-9 {
continue;
}
out.push((v2(a.x + dir.x * lo, a.y + dir.y * lo), v2(a.x + dir.x * hi, a.y + dir.y * hi)));
}
out
}
/// Polylinie gegen ein (konkaves) Polygon als zusammenhängende Innen-Läufe.
pub fn clip_polyline_to_polygon(pts: &[V2], poly: &[V2]) -> Vec<Run> {
if pts.len() < 2 || poly.len() < 3 {
return Vec::new();
}
const EPS: f64 = 1e-9;
let near = |p: V2, q: V2| (p.x - q.x).abs() < EPS && (p.y - q.y).abs() < EPS;
let mut runs: Vec<Run> = Vec::new();
let mut cur: Option<Run> = None;
fn close_run(cur: &mut Option<Run>, runs: &mut Vec<Run>) {
if let Some(c) = cur.take() {
if c.len() >= 2 {
runs.push(c);
}
}
}
for i in 0..pts.len() - 1 {
let a = pts[i];
let b = pts[i + 1];
for (sa, sb) in clip_segment_to_polygon(a, b, poly) {
let dx = b.x - a.x;
let dy = b.y - a.y;
let ta = (sa.x - a.x) * dx + (sa.y - a.y) * dy;
let tb = (sb.x - a.x) * dx + (sb.y - a.y) * dy;
let s = if ta <= tb { sa } else { sb };
let e = if ta <= tb { sb } else { sa };
match cur.as_mut() {
Some(c) if near(*c.last().unwrap(), s) => c.push(e),
_ => {
close_run(&mut cur, &mut runs);
cur = Some(vec![s, e]);
}
}
}
if let Some(c) = cur.as_ref() {
if !near(*c.last().unwrap(), b) {
close_run(&mut cur, &mut runs);
}
}
}
close_run(&mut cur, &mut runs);
runs
}
/// Schar paralleler, aufs Polygon geclippter Linien (Richtung `angle_rad`, Abstand `spacing_m`,
/// Phase `offset_m`, Raster-Anker `anchor` = Modellursprung bzw. `hatchOrigin`).
pub fn hatch_line_family(poly: &[V2], angle_rad: f64, spacing_m: f64, offset_m: f64, anchor: V2) -> Vec<(V2, V2)> {
if poly.len() < 3 || spacing_m <= 1e-9 {
return Vec::new();
}
let (min_x, min_y, max_x, max_y) = bbox(poly);
if !(max_x > min_x) && !(max_y > min_y) {
return Vec::new();
}
let dir = v2(jsnum::cos(angle_rad), jsnum::sin(angle_rad));
let nrm = v2(-dir.y, dir.x);
let center = anchor;
let (mut d_min, mut d_max) = (f64::INFINITY, f64::NEG_INFINITY);
for p in poly {
let d = (p.x - center.x) * nrm.x + (p.y - center.y) * nrm.y;
if d < d_min {
d_min = d;
}
if d > d_max {
d_max = d;
}
}
let mut segs = Vec::new();
let first = ((d_min - offset_m) / spacing_m).floor() - 1.0;
let last = ((d_max - offset_m) / spacing_m).ceil() + 1.0;
// Unendliche Ausdehnung (TS lief hier endlos): nichts zeichnen.
if !(last - first).is_finite() {
return segs;
}
let mut k = first;
while k <= last {
let d = offset_m + k * spacing_m;
let p0 = v2(center.x + nrm.x * d, center.y + nrm.y * d);
segs.extend(clip_line_to_polygon(p0, dir, poly));
k += 1.0;
}
segs
}
fn rotate(v: V2, rad: f64) -> V2 {
let c = jsnum::cos(rad);
let s = jsnum::sin(rad);
v2(v.x * c - v.y * s, v.x * s + v.y * c)
}
/// SVG-Drehung (im Uhrzeigersinn, Grad) → Modellwinkel (Bogenmass, CCW).
fn to_model_angle_rad(screen_deg: f64) -> f64 {
(-screen_deg * PI) / 180.0
}
// ── Strichmuster ────────────────────────────────────────────────────────────
/// Zerlegt Läufe entlang eines Strichmusters (`dash` in mm-Papier, [an, aus, …]; ungerade
/// Länge wird verdoppelt). Die Phase läuft über Stützpunkte hinweg durch.
pub fn apply_dash_runs(runs: Vec<Run>, dash: &[f64]) -> Vec<Run> {
if dash.is_empty() {
return runs;
}
let pat: Vec<f64> = dash.iter().map(|&d| jsnum::max(0.0, d) * DASH_MM_TO_M).filter(|&d| d > 0.0).collect();
if pat.is_empty() {
return runs;
}
let cycle: Vec<f64> = if pat.len() % 2 == 0 { pat } else { pat.iter().chain(pat.iter()).copied().collect() };
let mut total = 0.0;
for &d in &cycle {
total += d;
}
if total <= 1e-9 {
return runs;
}
let mut out: Vec<Run> = Vec::new();
for run in &runs {
if run.len() < 2 {
continue;
}
let mut idx = 0usize;
let mut dash_left = cycle[0];
let mut on = true;
let mut piece: Option<Run> = Some(vec![run[0]]);
for i in 0..run.len() - 1 {
let mut a = run[i];
let b = run[i + 1];
let mut seg_len = hypot2(b.x - a.x, b.y - a.y);
if seg_len < 1e-12 {
continue;
}
let ux = (b.x - a.x) / seg_len;
let uy = (b.y - a.y) / seg_len;
while seg_len > 1e-9 {
let step = jsnum::min(seg_len, dash_left);
let mid = v2(a.x + ux * step, a.y + uy * step);
if on {
piece.get_or_insert_with(|| vec![a]).push(mid);
}
a = mid;
seg_len -= step;
dash_left -= step;
if dash_left <= 1e-9 {
if on {
if let Some(p) = piece.take() {
if p.len() >= 2 {
out.push(p);
}
}
}
on = !on;
idx += 1;
dash_left = cycle[idx % cycle.len()];
if on {
piece = Some(vec![a]);
}
}
}
}
if let Some(p) = piece.take() {
if p.len() >= 2 {
out.push(p);
}
}
}
out
}
// ── Muster ──────────────────────────────────────────────────────────────────
/// Schraffur eines Polygons als zusammenhängende Läufe (Modell-Meter); Bild/Verlauf liefern
/// hier keine Linien (die Aufrufer filtern sie vorher).
pub fn build_hatch_runs(poly: &[V2], hatch: &Hatch) -> Vec<Run> {
if poly.len() < 3 {
return Vec::new();
}
let pattern = hatch.pattern;
if pattern == Pattern::None || pattern == Pattern::Solid {
return Vec::new();
}
let scale = if hatch.scale > 1e-6 { hatch.scale } else { 1.0 };
if hatch.kind == HatchKind::Vector && hatch.random {
return build_random_hatch_runs(poly, hatch, Some(scale));
}
if pattern == Pattern::Insulation {
return insulation_runs(poly, hatch, scale);
}
let spacing_m = 8.0 * scale * PX_TO_M;
let rot = to_model_angle_rad(hatch.angle);
let dir1 = rotate(v2(0.0, -1.0), rot);
let a1 = jsnum::atan2(dir1.y, dir1.x);
let anchor = hatch.origin.unwrap_or(v2(0.0, 0.0));
let mut runs: Vec<Run> = hatch_line_family(poly, a1, spacing_m, 0.0, anchor)
.into_iter()
.map(|(a, b)| match (&hatch.motif, pattern) {
(Some(m), Pattern::Custom) => motif_points(a, b, m, scale * DASH_MM_TO_M),
_ => vec![a, b],
})
.collect();
if pattern == Pattern::Crosshatch {
for (a, b) in hatch_line_family(poly, a1 + PI / 2.0, spacing_m, 0.0, anchor) {
runs.push(vec![a, b]);
}
}
runs
}
/// Dämmungswelle (Kachel 14×10·scale px, zwei quadratische Béziers je Welle).
fn insulation_runs(poly: &[V2], hatch: &Hatch, scale: f64) -> Vec<Run> {
let rot = to_model_angle_rad(hatch.angle);
let wavelength = 14.0 * scale * PX_TO_M;
let row_gap = 10.0 * scale * PX_TO_M;
let u_dir = rotate(v2(1.0, 0.0), rot);
let v_dir = rotate(v2(0.0, 1.0), rot);
let (mut u_min, mut u_max, mut v_min, mut v_max) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
for p in poly {
let u = p.x * u_dir.x + p.y * u_dir.y;
let v = p.x * v_dir.x + p.y * v_dir.y;
if u < u_min {
u_min = u;
}
if u > u_max {
u_max = u;
}
if v < v_min {
v_min = v;
}
if v > v_max {
v_max = v;
}
}
if !(u_max > u_min) || !(v_max > v_min) {
return Vec::new();
}
const STEPS: f64 = 22.0;
let du = wavelength / STEPS;
let to_world = |u: f64, v: f64| v2(u_dir.x * u + v_dir.x * v, u_dir.y * u + v_dir.y * v);
let first_row = (v_min / row_gap - 0.5).floor() - 1.0;
let last_row = (v_max / row_gap - 0.5).ceil() + 1.0;
let u_start = ((u_min - wavelength) / du).floor() * du;
let u_end = u_max + wavelength;
if !(last_row - first_row).is_finite() || !(u_end - u_start).is_finite() {
return Vec::new();
}
let half = wavelength / 2.0;
let wave_at = |u: f64| -> f64 {
let phase = ((u % wavelength) + wavelength) % wavelength;
let t = (phase % half) / half;
let mag = 12.0 * scale * PX_TO_M * t * (1.0 - t);
if phase < half {
mag
} else {
-mag
}
};
let mut runs = Vec::new();
let mut r = first_row;
while r <= last_row {
let v_base = (r + 0.5) * row_gap;
let mut wave_pts = Vec::new();
let mut u = u_start;
while u <= u_end + 1e-9 {
wave_pts.push(to_world(u, v_base + wave_at(u)));
u += du;
}
runs.extend(clip_polyline_to_polygon(&wave_pts, poly));
r += 1.0;
}
runs
}
// ── Random-Schraffur ────────────────────────────────────────────────────────
/// mulberry32 (deterministischer 32-bit-PRNG).
struct Mulberry32 {
a: u32,
}
impl Mulberry32 {
fn next(&mut self) -> f64 {
self.a = self.a.wrapping_add(0x6d2b79f5);
let a = self.a;
let mut t = (a ^ (a >> 15)).wrapping_mul(1 | a);
t = t.wrapping_add((t ^ (t >> 7)).wrapping_mul(61 | t)) ^ t;
((t ^ (t >> 14)) as f64) / 4294967296.0
}
}
/// Faltet Kennwerte (gequantelt ·1000) zu einem 32-bit-Seed (FNV-artig).
fn hash_seed(vals: &[f64]) -> u32 {
let mut h: u32 = 0x811c9dc5;
for &v in vals {
let q = jsnum::to_int32(jsnum::round(v * 1000.0)) as u32;
h ^= q & 0xffff;
h = h.wrapping_mul(0x01000193);
h ^= (q >> 16) & 0xffff;
h = h.wrapping_mul(0x01000193);
}
h
}
/// Hash einer Modellraum-Zelle (absolute Indizes) plus Seed.
fn hash_cell(ix: f64, iy: f64, seed: f64) -> u32 {
let mut h: u32 = 0x811c9dc5 ^ (jsnum::to_int32(seed) as u32);
h = (h ^ jsnum::to_int32(ix) as u32).wrapping_mul(0x01000193);
h = (h ^ jsnum::to_int32(iy) as u32).wrapping_mul(0x01000193);
h ^= h >> 15;
h = h.wrapping_mul(0x2c1b3c6d);
h ^= h >> 12;
h
}
/// Streut kurze Striche modellraum-stabil über ein Polygon (eine Zelle je Strich).
pub fn scatter_strokes(
poly: &[V2],
cell: f64,
base_angle_rad: f64,
seed: f64,
stroke_len: f64,
len_min: Option<f64>,
len_max: Option<f64>,
) -> Vec<Run> {
if poly.len() < 3 || cell <= 1e-9 || stroke_len <= 1e-9 {
return Vec::new();
}
let (min_x, min_y, max_x, max_y) = bbox(poly);
if !(max_x > min_x) || !(max_y > min_y) {
return Vec::new();
}
let mut eff = cell;
let mut ix0 = (min_x / eff).floor();
let mut ix1 = (max_x / eff).floor();
let mut iy0 = (min_y / eff).floor();
let mut iy1 = (max_y / eff).floor();
const MAX_CELLS: f64 = 250000.0;
let cells = (ix1 - ix0 + 1.0) * (iy1 - iy0 + 1.0);
if cells > MAX_CELLS {
eff = cell * (cells / MAX_CELLS).sqrt();
ix0 = (min_x / eff).floor();
ix1 = (max_x / eff).floor();
iy0 = (min_y / eff).floor();
iy1 = (max_y / eff).floor();
}
if !(ix1 - ix0).is_finite() || !(iy1 - iy0).is_finite() {
return Vec::new();
}
let range = match (len_min, len_max) {
(Some(lo), Some(hi)) if lo > 1e-9 && hi >= lo => Some((lo, hi)),
_ => None,
};
let mut runs = Vec::new();
let mut iy = iy0;
while iy <= iy1 {
let mut ix = ix0;
while ix <= ix1 {
let mut rnd = Mulberry32 { a: hash_cell(ix, iy, seed) };
let cx = (ix + rnd.next()) * eff;
let cy = (iy + rnd.next()) * eff;
let ang = base_angle_rad + (rnd.next() * 2.0 - 1.0) * PI;
let len = match range {
Some((lo, hi)) => lo + rnd.next() * (hi - lo),
None => stroke_len * (0.6 + 0.8 * rnd.next()),
};
let half = len * 0.5;
let dx = jsnum::cos(ang) * half;
let dy = jsnum::sin(ang) * half;
let a = v2(cx - dx, cy - dy);
let b = v2(cx + dx, cy + dy);
for (sa, sb) in clip_segment_to_polygon(a, b, poly) {
runs.push(vec![sa, sb]);
}
ix += 1.0;
}
iy += 1.0;
}
runs
}
/// Random-Vektor-Schraffur (Kies/Splitt), Dichte/Strichlänge an die Kachel (8·scale px) gekoppelt.
pub fn build_random_hatch_runs(poly: &[V2], hatch: &Hatch, scale: Option<f64>) -> Vec<Run> {
let s = scale.unwrap_or(if hatch.scale > 1e-6 { hatch.scale } else { 1.0 });
let density = match hatch.density {
Some(d) if d > 1e-6 => d,
_ => 1.0,
};
let cell = (8.0 * s * PX_TO_M) / density;
let stroke_len = cell * 1.1;
let seed = hash_seed(&[hatch.angle, s, density, hatch.seed.unwrap_or(0.0)]);
let base = to_model_angle_rad(hatch.angle);
let len_min = hatch.length_min.map(|v| v * DASH_MM_TO_M);
let len_max = hatch.length_max.map(|v| v * DASH_MM_TO_M);
scatter_strokes(poly, cell, base, seed as f64, stroke_len, len_min, len_max)
}
// ── Zickzack / Motiv ────────────────────────────────────────────────────────
/// Zickzack (Dreieckswelle [0,+A,0,−A] je Viertel-Wellenlänge) entlang [a,b]. `None` =
/// entartet (Aufrufer nimmt `[a, b]`).
pub fn zigzag_points(a: V2, b: V2, amplitude: f64, wavelength: f64) -> Option<Vec<V2>> {
let dx = b.x - a.x;
let dy = b.y - a.y;
let l = hypot2(dx, dy);
if l < 1e-12 || wavelength <= 1e-9 || amplitude <= 0.0 {
return None;
}
let ux = dx / l;
let uy = dy / l;
let nx = -uy;
let ny = ux;
let quarter = wavelength / 4.0;
let steps = jsnum::max(1.0, jsnum::round(l / quarter));
const TRI: [f64; 4] = [0.0, 1.0, 0.0, -1.0];
let mut pts = Vec::new();
let mut i = 0.0f64;
while i <= steps {
let t = jsnum::min(l, i * quarter);
let off = amplitude * TRI[(i as u64 % 4) as usize];
pts.push(v2(a.x + ux * t + nx * off, a.y + uy * t + ny * off));
i += 1.0;
}
// (TS warf hier bei NaN-Länge; ohne Punkte gilt die Strecke.)
let last = *pts.last()?;
if (last.x - b.x).abs() > 1e-9 || (last.y - b.y).abs() > 1e-9 {
pts.push(v2(b.x, b.y));
}
Some(pts)
}
/// Kachelt ein Motiv entlang [a,b] (Punkte und Länge ·`scale`), am Ende exakt bei `L`
/// geclippt. `None` = entartet (Aufrufer nimmt `[a, b]`).
pub fn motif_points(a: V2, b: V2, motif: &Motif, scale: f64) -> Vec<V2> {
motif_points_opt(a, b, motif, scale).unwrap_or_else(|| vec![a, b])
}
pub fn motif_points_opt(a: V2, b: V2, motif: &Motif, scale: f64) -> Option<Vec<V2>> {
let dx = b.x - a.x;
let dy = b.y - a.y;
let l = hypot2(dx, dy);
let cell = motif.length * scale;
if l < 1e-12 || cell <= 1e-9 || motif.points.len() < 2 {
return None;
}
let ux = dx / l;
let uy = dy / l;
let nx = -uy;
let ny = ux;
let to_world = |ax: f64, off: f64| v2(a.x + ux * ax + nx * off, a.y + uy * ax + ny * off);
let mut out = Vec::new();
let reps = (l / cell).ceil() + 1.0;
let mut last: Option<(f64, f64)> = None;
let mut r = 0.0f64;
while r < reps {
let base = r * cell;
for p in &motif.points {
let ax = base + p.x * scale;
let off = p.y * scale;
if let Some((lax, loff)) = last {
if (ax - lax).abs() < 1e-9 && (off - loff).abs() < 1e-9 {
continue;
}
}
if ax > l + 1e-9 {
if let Some((lax, loff)) = last {
if ax > lax + 1e-12 && l - lax > 1e-9 {
let tt = (l - lax) / (ax - lax);
out.push(to_world(l, loff + (off - loff) * tt));
}
}
return if out.len() >= 2 { Some(out) } else { None };
}
out.push(to_world(ax, off));
last = Some((ax, off));
}
r += 1.0;
}
if out.len() >= 2 {
Some(out)
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
fn square() -> Vec<V2> {
vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(1.0, 1.0), v2(0.0, 1.0)]
}
fn hatch(pattern: Pattern) -> Hatch {
Hatch {
pattern,
kind: HatchKind::Vector,
random: false,
scale: 1.0,
angle: 45.0,
line_weight: 0.13,
origin: None,
seed: None,
density: None,
length_min: None,
length_max: None,
dash: Vec::new(),
motif: None,
}
}
#[test]
fn linie_durch_quadrat() {
let s = clip_line_to_polygon(v2(-1.0, 0.5), v2(1.0, 0.0), &square());
assert_eq!(s.len(), 1);
assert!((s[0].0.x - 0.0).abs() < 1e-12 && (s[0].1.x - 1.0).abs() < 1e-12);
assert!(clip_line_to_polygon(v2(-1.0, 5.0), v2(1.0, 0.0), &square()).is_empty());
}
#[test]
fn konkav_zwei_stuecke() {
// U-Form: Linie bei y=0.75 trifft beide Schenkel.
let u = vec![v2(0.0, 0.0), v2(3.0, 0.0), v2(3.0, 1.0), v2(2.0, 1.0), v2(2.0, 0.5), v2(1.0, 0.5), v2(1.0, 1.0), v2(0.0, 1.0)];
assert_eq!(clip_line_to_polygon(v2(-1.0, 0.75), v2(1.0, 0.0), &u).len(), 2);
}
#[test]
fn muster_liefern_linien() {
let sq = square();
assert!(!build_hatch_runs(&sq, &hatch(Pattern::Diagonal)).is_empty());
let d = build_hatch_runs(&sq, &hatch(Pattern::Diagonal)).len();
assert!(build_hatch_runs(&sq, &hatch(Pattern::Crosshatch)).len() > d);
assert!(!build_hatch_runs(&sq, &hatch(Pattern::Insulation)).is_empty());
assert!(build_hatch_runs(&sq, &hatch(Pattern::Solid)).is_empty());
assert!(build_hatch_runs(&sq, &hatch(Pattern::None)).is_empty());
let mut r = hatch(Pattern::Diagonal);
r.random = true;
let a = build_hatch_runs(&sq, &r);
assert!(!a.is_empty());
assert_eq!(a, build_hatch_runs(&sq, &r));
r.seed = Some(8.0);
assert_ne!(a, build_hatch_runs(&sq, &r));
}
#[test]
fn unendliches_polygon_haengt_nicht() {
let p = vec![v2(0.0, 0.0), v2(f64::INFINITY, 0.0), v2(1.0, 1.0)];
assert!(build_hatch_runs(&p, &hatch(Pattern::Diagonal)).is_empty());
assert!(build_hatch_runs(&p, &hatch(Pattern::Insulation)).is_empty());
}
#[test]
fn strichmuster_zerlegt() {
let run = vec![v2(0.0, 0.0), v2(1.0, 0.0)];
let on = 0.5 / DASH_MM_TO_M; // 0.5 m an, 0.5 m aus → genau ein Strich
let out = apply_dash_runs(vec![run.clone()], &[on]);
assert_eq!(out.len(), 1);
assert!((out[0][1].x - 0.5).abs() < 1e-9);
assert_eq!(apply_dash_runs(vec![run.clone()], &[]).len(), 1);
assert_eq!(apply_dash_runs(vec![run], &[0.0, -1.0]).len(), 1);
}
#[test]
fn zickzack_und_motiv() {
let z = zigzag_points(v2(0.0, 0.0), v2(8.0, 0.0), 1.0, 4.0).unwrap();
assert_eq!(z.len(), 9);
assert_eq!(z[1], v2(1.0, 1.0));
assert!(zigzag_points(v2(0.0, 0.0), v2(1.0, 0.0), 0.0, 4.0).is_none());
let m = Motif { points: vec![v2(0.0, 0.0), v2(2.0, 1.0), v2(4.0, 0.0)], length: 4.0 };
let p = motif_points(v2(0.0, 0.0), v2(12.0, 0.0), &m, 1.0);
assert_eq!(p.first(), Some(&v2(0.0, 0.0)));
assert_eq!(p.last(), Some(&v2(12.0, 0.0)));
let short = Motif { points: vec![v2(0.0, 0.0)], length: 4.0 };
assert_eq!(motif_points(v2(0.0, 0.0), v2(4.0, 0.0), &short, 1.0), vec![v2(0.0, 0.0), v2(4.0, 0.0)]);
}
#[test]
fn mulberry_wie_js() {
// Referenz aus JS: mulberry32(1)() = 0.6270739405881613
let mut r = Mulberry32 { a: 1 };
assert_eq!(r.next(), 0.6270739405881613);
}
}
+60
View File
@@ -0,0 +1,60 @@
//! Flache Kodierung von Punkten, Segmenten und Läufen für die Schraffur-Bindungen
//! (`[x, y, …]`, `[ax, ay, bx, by, …]`, `[n, x, y, …(n Punkte), n, …]`). Kaputte Eingaben
//! (ungerade Länge, Anzahl über das Pufferende) werden abgeschnitten, nie ein Panic.
use crate::hatch::{v2, Run, V2};
pub fn pts(buf: &[f64]) -> Vec<V2> {
buf.chunks_exact(2).map(|c| v2(c[0], c[1])).collect()
}
pub fn segs_out(segs: &[(V2, V2)]) -> Vec<f64> {
let mut out = Vec::with_capacity(segs.len() * 4);
for (a, b) in segs {
out.extend_from_slice(&[a.x, a.y, b.x, b.y]);
}
out
}
pub fn runs_out(runs: &[Run]) -> Vec<f64> {
let mut out = Vec::new();
for r in runs {
out.push(r.len() as f64);
for p in r {
out.push(p.x);
out.push(p.y);
}
}
out
}
pub fn runs_in(buf: &[f64]) -> Vec<Run> {
let mut out = Vec::new();
let mut i = 0;
while i < buf.len() {
let n = buf[i];
if !(n >= 0.0) || n.fract() != 0.0 {
break;
}
let end = match (n as usize).checked_mul(2).and_then(|k| k.checked_add(i + 1)) {
Some(e) if e <= buf.len() => e,
_ => break,
};
out.push(pts(&buf[i + 1..end]));
i = end;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn laeufe_hin_und_zurueck() {
let r = vec![vec![v2(0.0, 1.0), v2(2.0, 3.0)], vec![v2(4.0, 5.0)]];
assert_eq!(runs_in(&runs_out(&r)), r);
assert_eq!(runs_in(&[5.0, 1.0]), Vec::<Run>::new());
assert_eq!(pts(&[1.0, 2.0, 3.0]), vec![v2(1.0, 2.0)]);
}
}
+158
View File
@@ -0,0 +1,158 @@
//! Zahl-Semantik von JavaScript für bitgleiche Portierungen ([K3b] GPU-Kompilierung, Schraffur).
//!
//! - `Math.min/max` liefern bei NaN NaN (Rust `f64::min/max` ignorieren NaN).
//! - `Math.round` rundet halbe Werte Richtung +∞ (Rust `round` weg von 0).
//! - `x | 0` ist ToInt32 (Rest modulo 2³², Rust `as i32` sättigt).
//! - Trigonometrie: im Web-Build (wasm32 + Feature "web") ruft der Kern `Math.cos/sin/atan2/acos`
//! der laufenden JS-Engine. Nur so sind die Werte bitgleich zur bisherigen TS-Fassung — V8
//! (glibc-abgeleitete sin/cos), JavaScriptCore (System-libm von macOS) und Rusts libm (musl)
//! unterscheiden sich in einzelnen Fällen in der letzten Stelle. Nativ (`cargo test`, Tauri)
//! gilt die Rust-Standardbibliothek.
#[cfg(all(feature = "web", target_arch = "wasm32"))]
mod trig {
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = Math, js_name = cos)]
fn js_cos(x: f64) -> f64;
#[wasm_bindgen(js_namespace = Math, js_name = sin)]
fn js_sin(x: f64) -> f64;
#[wasm_bindgen(js_namespace = Math, js_name = atan2)]
fn js_atan2(y: f64, x: f64) -> f64;
#[wasm_bindgen(js_namespace = Math, js_name = acos)]
fn js_acos(x: f64) -> f64;
}
#[inline]
pub fn cos(x: f64) -> f64 {
js_cos(x)
}
#[inline]
pub fn sin(x: f64) -> f64 {
js_sin(x)
}
#[inline]
pub fn atan2(y: f64, x: f64) -> f64 {
js_atan2(y, x)
}
#[inline]
pub fn acos(x: f64) -> f64 {
js_acos(x)
}
}
#[cfg(not(all(feature = "web", target_arch = "wasm32")))]
mod trig {
#[inline]
pub fn cos(x: f64) -> f64 {
x.cos()
}
#[inline]
pub fn sin(x: f64) -> f64 {
x.sin()
}
#[inline]
pub fn atan2(y: f64, x: f64) -> f64 {
y.atan2(x)
}
#[inline]
pub fn acos(x: f64) -> f64 {
x.acos()
}
}
pub use trig::{acos, atan2, cos, sin};
/// `Math.min(a, b)` (NaN gewinnt; −0 < +0).
#[inline]
pub fn min(a: f64, b: f64) -> f64 {
if a.is_nan() || b.is_nan() {
f64::NAN
} else if a < b || (a == b && a.is_sign_negative()) {
a
} else {
b
}
}
/// `Math.max(a, b)` (NaN gewinnt; +0 > −0).
#[inline]
pub fn max(a: f64, b: f64) -> f64 {
if a.is_nan() || b.is_nan() {
f64::NAN
} else if a > b || (a == b && a.is_sign_positive()) {
a
} else {
b
}
}
/// `Math.round(x)`: halbe Werte Richtung +∞, −0 bleibt −0, Werte in (−0.5, 0) → −0.
#[inline]
pub fn round(x: f64) -> f64 {
if !x.is_finite() || x == 0.0 {
return x;
}
if x > 0.0 && x < 0.5 {
return 0.0;
}
if x < 0.0 && x >= -0.5 {
return -0.0;
}
let r = x.ceil();
if r - 0.5 > x {
r - 1.0
} else {
r
}
}
/// ToInt32 (`x | 0`).
#[inline]
pub fn to_int32(x: f64) -> i32 {
// Schneller Weg im i32-Bereich (`as` schneidet wie ToInt32 Richtung 0 ab; NaN → 0).
if (-2147483648.0..=2147483647.0).contains(&x) {
return x as i32;
}
if !x.is_finite() {
return 0;
}
let t = x.trunc();
let m = t.rem_euclid(4294967296.0);
(m as u64 as u32) as i32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rundung_wie_js() {
assert_eq!(round(2.5), 3.0);
assert_eq!(round(-2.5), -2.0);
assert_eq!(round(-0.5).to_bits(), (-0.0f64).to_bits());
assert_eq!(round(0.49999999999999994), 0.0);
assert_eq!(round(-126.5), -126.0);
assert!(round(f64::NAN).is_nan());
}
#[test]
fn min_max_wie_js() {
assert!(min(1.0, f64::NAN).is_nan());
assert!(max(f64::NAN, 1.0).is_nan());
assert_eq!(max(0.0, -0.0).to_bits(), 0.0f64.to_bits());
assert_eq!(min(0.0, -0.0).to_bits(), (-0.0f64).to_bits());
assert_eq!(max(-1.0, min(1.0, 3.0)), 1.0);
}
#[test]
fn int32_wie_js() {
assert_eq!(to_int32(4294967296.0 + 5.0), 5);
assert_eq!(to_int32(2147483648.0), -2147483648);
assert_eq!(to_int32(-1.7), -1);
assert_eq!(to_int32(f64::NAN), 0);
assert_eq!(to_int32(-4294967297.0), -1);
}
}
+5
View File
@@ -28,6 +28,11 @@ pub mod columns3d;
pub mod drawing2d_3d;
pub mod openings3d;
pub mod wall_mesh_cut;
pub mod jsnum;
pub mod hatch;
pub mod hatch_flat;
pub mod plan_buf;
pub mod gpu_compile;
#[cfg(feature = "web")]
mod web;
+666
View File
@@ -0,0 +1,666 @@
//! Plan-Puffer ([K3b]): kompakte Binärkodierung der zeichnungsrelevanten Plan-Primitive als
//! flacher `f64`-Puffer (TS schreibt ihn heute in `src/plan/planBuf.ts`, später erzeugt Rust ihn
//! direkt, [K3a]). Pick-IDs gehören nicht hinein (Picken bleibt vorerst TS); dafür hat jedes
//! Primitiv genau einen Eintrag, damit Indizes und Bereiche (`greyedRanges`, Chunks) gleich bleiben.
//!
//! ```text
//! Kopf [MAGIC, VERSION, nColors, nHatches, nPrims]
//! MAGIC = 0x504C4231 ("PLB1"), VERSION = 1 — fremde Werte → Puffer abgelehnt
//! Farben nColors × [r, g, b, a] (0..1, aus dem Farbtext in TS geparst)
//! Schraffuren nHatches × Hatch
//! Primitive nPrims × Prim
//!
//! Hatch [pattern, kind, flags, scale, angle, colorIdx, lineWeight, originX, originY,
//! seed, density, lengthMin, lengthMax, nDash, dash…, (Motiv: length, nPts, x,y…)]
//! pattern 0 none · 1 solid · 2 diagonal · 3 crosshatch · 4 insulation · 5 custom
//! kind 0 vector · 1 image · 2 gradient (Bild/Verlauf: GPU fällt auf die Füllung zurück)
//! flags 1 random · 2 origin · 4 seed · 8 density · 16 lengthMin · 32 lengthMax · 64 Motiv
//! (Felder ohne Flag stehen auf 0 und gelten als „nicht gesetzt“)
//!
//! Prim [tag, flags, …] flags 1 greyed · 2 opacity gesetzt · 4 setzt den Linienzug der
//! vorigen Linie fort · 8 Zickzack · 16 Motiv
//! 0 Platzhalter [0] (Text, Bild … — zeichnet die GPU nicht)
//! 1 polygon [1, flags, fillIdx, strokeIdx, strokeWidthMm, hatchIdx, opacity,
//! nPts, x,y…, nNoStroke, kante…]
//! 2 line [2, flags, colorIdx, weightMm, opacity, ax, ay, bx, by, nDash, dash…,
//! (Zickzack: amplitude, wavelength), (Motiv: length, nPts, x,y…)]
//! 3 arc [3, flags, colorIdx, weightMm, opacity, cx, cy, fromX, fromY, toX, toY, r,
//! nDash, dash…]
//! 4 drawingCircle [4, flags, fillIdx, strokeIdx, weightMm, opacity, cx, cy, r, nDash, dash…]
//! 5 drawingArc [5, flags, strokeIdx, weightMm, opacity, cx, cy, r, a0, a1, nDash, dash…]
//! ```
//! Farb-/Schraffur-Index −1 = keine (Farbtext ungültig, "none", fehlende Schraffur). Längen in
//! Metern, Strichstärken/Strichmuster/Zickzack/Motiv in Papier-mm, Winkel von drawingArc in
//! Bogenmass, Schraffur-Winkel in Grad (SVG-Drehsinn). Ohne opacity-Flag steht 1 im Feld.
//! Fehlende Strichstärke (`undefined`) wird NaN (der Verbraucher nimmt dann seinen Standard).
//! Flag 4 (Linienzug): TS prüft gleiches Element (`drawingId`), gleiche Farbe/Stärke/greyed/
//! opacity/Strichmuster und Anfang = Ende der vorigen Linie; der Verbraucher prüft die Lage nach.
use crate::hatch::{Hatch, HatchKind, Motif, Pattern, V2};
pub const MAGIC: f64 = 1_347_174_961.0; // 0x504C4231
pub const VERSION: f64 = 1.0;
pub const FLAG_GREYED: u32 = 1;
pub const FLAG_OPACITY: u32 = 2;
pub const FLAG_CHAIN: u32 = 4;
pub const FLAG_ZIGZAG: u32 = 8;
pub const FLAG_MOTIF: u32 = 16;
const HF_RANDOM: u32 = 1;
const HF_ORIGIN: u32 = 2;
const HF_SEED: u32 = 4;
const HF_DENSITY: u32 = 8;
const HF_LEN_MIN: u32 = 16;
const HF_LEN_MAX: u32 = 32;
const HF_MOTIF: u32 = 64;
/// Gemeinsame Darstellungs-Attribute.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Style {
pub greyed: bool,
/// `None` = nicht gesetzt (deckend).
pub opacity: Option<f64>,
}
/// Schraffur samt Farbindex.
#[derive(Clone, Debug, PartialEq)]
pub struct HatchEntry {
pub hatch: Hatch,
pub color: i32,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Prim {
Placeholder,
Polygon {
style: Style,
fill: i32,
stroke: i32,
stroke_width_mm: f64,
hatch: i32,
pts: Vec<V2>,
no_stroke_edges: Vec<f64>,
},
Line {
style: Style,
color: i32,
weight_mm: f64,
a: V2,
b: V2,
dash: Vec<f64>,
/// Setzt den Linienzug der vorigen Linie fort (gleiches Element und gleicher Stil).
chain: bool,
zigzag: Option<(f64, f64)>,
motif: Option<Motif>,
},
Arc {
style: Style,
color: i32,
weight_mm: f64,
center: V2,
from: V2,
to: V2,
r: f64,
dash: Vec<f64>,
},
Circle {
style: Style,
fill: i32,
stroke: i32,
weight_mm: f64,
center: V2,
r: f64,
dash: Vec<f64>,
},
DrawingArc {
style: Style,
stroke: i32,
weight_mm: f64,
center: V2,
r: f64,
a0: f64,
a1: f64,
dash: Vec<f64>,
},
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PlanBuf {
pub colors: Vec<[f64; 4]>,
pub hatches: Vec<HatchEntry>,
pub prims: Vec<Prim>,
}
impl PlanBuf {
pub fn color(&self, idx: i32) -> Option<[f64; 4]> {
if idx < 0 {
None
} else {
self.colors.get(idx as usize).copied()
}
}
}
// ── Lesen ───────────────────────────────────────────────────────────────────
struct Reader<'a> {
buf: &'a [f64],
pos: usize,
}
impl<'a> Reader<'a> {
fn f(&mut self) -> Option<f64> {
let v = *self.buf.get(self.pos)?;
self.pos += 1;
Some(v)
}
/// Nicht-negative ganze Anzahl, höchstens so gross wie der Rest des Puffers × `per`.
fn count(&mut self, per: usize) -> Option<usize> {
let v = self.f()?;
if !(v >= 0.0) || v.fract() != 0.0 {
return None;
}
let n = v as usize;
if n.checked_mul(per)? > self.buf.len() - self.pos {
return None;
}
Some(n)
}
fn idx(&mut self) -> Option<i32> {
let v = self.f()?;
if v.fract() != 0.0 || !(v >= -1.0) || v > i32::MAX as f64 {
return None;
}
Some(v as i32)
}
fn flags(&mut self) -> Option<u32> {
let v = self.f()?;
if !(v >= 0.0) || v.fract() != 0.0 || v > u32::MAX as f64 {
return None;
}
Some(v as u32)
}
fn v2(&mut self) -> Option<V2> {
Some(V2 { x: self.f()?, y: self.f()? })
}
fn list(&mut self) -> Option<Vec<f64>> {
let n = self.count(1)?;
let s = self.buf[self.pos..self.pos + n].to_vec();
self.pos += n;
Some(s)
}
fn pts(&mut self) -> Option<Vec<V2>> {
let n = self.count(2)?;
let mut out = Vec::with_capacity(n);
for _ in 0..n {
out.push(self.v2()?);
}
Some(out)
}
fn motif(&mut self) -> Option<Motif> {
let length = self.f()?;
Some(Motif { length, points: self.pts()? })
}
fn style(flags: u32, opacity: f64) -> Style {
Style { greyed: flags & FLAG_GREYED != 0, opacity: if flags & FLAG_OPACITY != 0 { Some(opacity) } else { None } }
}
}
fn opt(flags: u32, bit: u32, v: f64) -> Option<f64> {
if flags & bit != 0 {
Some(v)
} else {
None
}
}
/// Einen Schraffur-Eintrag lesen (auch für die Einzel-Bindungen der Schraffur-Fassade).
fn read_hatch(r: &mut Reader) -> Option<HatchEntry> {
let pattern = Pattern::from_code(r.f()?);
let kind = HatchKind::from_code(r.f()?);
let flags = r.flags()?;
let scale = r.f()?;
let angle = r.f()?;
let color = r.idx()?;
let line_weight = r.f()?;
let origin = r.v2()?;
let seed = r.f()?;
let density = r.f()?;
let length_min = r.f()?;
let length_max = r.f()?;
let dash = r.list()?;
let motif = if flags & HF_MOTIF != 0 { Some(r.motif()?) } else { None };
Some(HatchEntry {
hatch: Hatch {
pattern,
kind,
random: flags & HF_RANDOM != 0,
scale,
angle,
line_weight,
origin: if flags & HF_ORIGIN != 0 { Some(origin) } else { None },
seed: opt(flags, HF_SEED, seed),
density: opt(flags, HF_DENSITY, density),
length_min: opt(flags, HF_LEN_MIN, length_min),
length_max: opt(flags, HF_LEN_MAX, length_max),
dash,
motif,
},
color,
})
}
/// Einzelne Schraffur (Format wie ein Hatch-Eintrag des Plan-Puffers) ab `buf[0]`.
pub fn decode_hatch(buf: &[f64]) -> Option<(Hatch, usize)> {
let mut r = Reader { buf, pos: 0 };
let h = read_hatch(&mut r)?;
Some((h.hatch, r.pos))
}
fn read_prim(r: &mut Reader) -> Option<Prim> {
let tag = r.f()?;
if tag == 0.0 {
return Some(Prim::Placeholder);
}
let flags = r.flags()?;
Some(match tag as i64 {
1 => {
let fill = r.idx()?;
let stroke = r.idx()?;
let stroke_width_mm = r.f()?;
let hatch = r.idx()?;
let opacity = r.f()?;
let pts = r.pts()?;
let no_stroke_edges = r.list()?;
Prim::Polygon { style: Reader::style(flags, opacity), fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges }
}
2 => {
let color = r.idx()?;
let weight_mm = r.f()?;
let opacity = r.f()?;
let a = r.v2()?;
let b = r.v2()?;
let dash = r.list()?;
let zigzag = if flags & FLAG_ZIGZAG != 0 { Some((r.f()?, r.f()?)) } else { None };
let motif = if flags & FLAG_MOTIF != 0 { Some(r.motif()?) } else { None };
Prim::Line { style: Reader::style(flags, opacity), color, weight_mm, a, b, dash, chain: flags & FLAG_CHAIN != 0, zigzag, motif }
}
3 => {
let color = r.idx()?;
let weight_mm = r.f()?;
let opacity = r.f()?;
let center = r.v2()?;
let from = r.v2()?;
let to = r.v2()?;
let rad = r.f()?;
let dash = r.list()?;
Prim::Arc { style: Reader::style(flags, opacity), color, weight_mm, center, from, to, r: rad, dash }
}
4 => {
let fill = r.idx()?;
let stroke = r.idx()?;
let weight_mm = r.f()?;
let opacity = r.f()?;
let center = r.v2()?;
let rad = r.f()?;
let dash = r.list()?;
Prim::Circle { style: Reader::style(flags, opacity), fill, stroke, weight_mm, center, r: rad, dash }
}
5 => {
let stroke = r.idx()?;
let weight_mm = r.f()?;
let opacity = r.f()?;
let center = r.v2()?;
let rad = r.f()?;
let a0 = r.f()?;
let a1 = r.f()?;
let dash = r.list()?;
Prim::DrawingArc { style: Reader::style(flags, opacity), stroke, weight_mm, center, r: rad, a0, a1, dash }
}
_ => return None,
})
}
/// Puffer lesen; `None` bei fremder Magie/Version oder kaputtem Puffer (nie ein Panic).
pub fn decode(buf: &[f64]) -> Option<PlanBuf> {
let mut r = Reader { buf, pos: 0 };
if r.f()? != MAGIC || r.f()? != VERSION {
return None;
}
let n_colors = r.count(4)?;
let n_hatches = r.count(1)?;
let n_prims = r.count(1)?;
let mut colors = Vec::with_capacity(n_colors);
for _ in 0..n_colors {
colors.push([r.f()?, r.f()?, r.f()?, r.f()?]);
}
let mut hatches = Vec::with_capacity(n_hatches);
for _ in 0..n_hatches {
hatches.push(read_hatch(&mut r)?);
}
let mut prims = Vec::with_capacity(n_prims);
for _ in 0..n_prims {
prims.push(read_prim(&mut r)?);
}
if r.pos != buf.len() {
return None;
}
Some(PlanBuf { colors, hatches, prims })
}
// ── Schreiben (Rust-Erzeuger ab [K3a]; heute für Hin-und-zurück-Tests) ──────
fn put_list(out: &mut Vec<f64>, l: &[f64]) {
out.push(l.len() as f64);
out.extend_from_slice(l);
}
fn put_pts(out: &mut Vec<f64>, pts: &[V2]) {
out.push(pts.len() as f64);
for p in pts {
out.push(p.x);
out.push(p.y);
}
}
fn style_flags(s: &Style) -> u32 {
(if s.greyed { FLAG_GREYED } else { 0 }) | (if s.opacity.is_some() { FLAG_OPACITY } else { 0 })
}
fn write_hatch(out: &mut Vec<f64>, e: &HatchEntry) {
let h = &e.hatch;
let mut flags = 0;
if h.random {
flags |= HF_RANDOM;
}
if h.origin.is_some() {
flags |= HF_ORIGIN;
}
if h.seed.is_some() {
flags |= HF_SEED;
}
if h.density.is_some() {
flags |= HF_DENSITY;
}
if h.length_min.is_some() {
flags |= HF_LEN_MIN;
}
if h.length_max.is_some() {
flags |= HF_LEN_MAX;
}
if h.motif.is_some() {
flags |= HF_MOTIF;
}
let o = h.origin.unwrap_or(V2 { x: 0.0, y: 0.0 });
out.extend_from_slice(&[
h.pattern as u8 as f64,
h.kind as u8 as f64,
flags as f64,
h.scale,
h.angle,
e.color as f64,
h.line_weight,
o.x,
o.y,
h.seed.unwrap_or(0.0),
h.density.unwrap_or(0.0),
h.length_min.unwrap_or(0.0),
h.length_max.unwrap_or(0.0),
]);
put_list(out, &h.dash);
if let Some(m) = &h.motif {
out.push(m.length);
put_pts(out, &m.points);
}
}
pub fn encode(p: &PlanBuf) -> Vec<f64> {
let mut out = vec![MAGIC, VERSION, p.colors.len() as f64, p.hatches.len() as f64, p.prims.len() as f64];
for c in &p.colors {
out.extend_from_slice(c);
}
for h in &p.hatches {
write_hatch(&mut out, h);
}
for prim in &p.prims {
match prim {
Prim::Placeholder => out.push(0.0),
Prim::Polygon { style, fill, stroke, stroke_width_mm, hatch, pts, no_stroke_edges } => {
out.extend_from_slice(&[
1.0,
style_flags(style) as f64,
*fill as f64,
*stroke as f64,
*stroke_width_mm,
*hatch as f64,
style.opacity.unwrap_or(1.0),
]);
put_pts(&mut out, pts);
put_list(&mut out, no_stroke_edges);
}
Prim::Line { style, color, weight_mm, a, b, dash, chain, zigzag, motif } => {
let mut flags = style_flags(style);
if *chain {
flags |= FLAG_CHAIN;
}
if zigzag.is_some() {
flags |= FLAG_ZIGZAG;
}
if motif.is_some() {
flags |= FLAG_MOTIF;
}
out.extend_from_slice(&[2.0, flags as f64, *color as f64, *weight_mm, style.opacity.unwrap_or(1.0), a.x, a.y, b.x, b.y]);
put_list(&mut out, dash);
if let Some((amp, wav)) = zigzag {
out.push(*amp);
out.push(*wav);
}
if let Some(m) = motif {
out.push(m.length);
put_pts(&mut out, &m.points);
}
}
Prim::Arc { style, color, weight_mm, center, from, to, r, dash } => {
out.extend_from_slice(&[
3.0,
style_flags(style) as f64,
*color as f64,
*weight_mm,
style.opacity.unwrap_or(1.0),
center.x,
center.y,
from.x,
from.y,
to.x,
to.y,
*r,
]);
put_list(&mut out, dash);
}
Prim::Circle { style, fill, stroke, weight_mm, center, r, dash } => {
out.extend_from_slice(&[
4.0,
style_flags(style) as f64,
*fill as f64,
*stroke as f64,
*weight_mm,
style.opacity.unwrap_or(1.0),
center.x,
center.y,
*r,
]);
put_list(&mut out, dash);
}
Prim::DrawingArc { style, stroke, weight_mm, center, r, a0, a1, dash } => {
out.extend_from_slice(&[
5.0,
style_flags(style) as f64,
*stroke as f64,
*weight_mm,
style.opacity.unwrap_or(1.0),
center.x,
center.y,
*r,
*a0,
*a1,
]);
put_list(&mut out, dash);
}
}
}
out
}
/// Lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei kaputtem Puffer.
pub fn recode(buf: &[f64]) -> Vec<f64> {
decode(buf).map(|p| encode(&p)).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hatch::v2;
fn style() -> Style {
Style { greyed: true, opacity: Some(0.5) }
}
fn sample() -> PlanBuf {
PlanBuf {
colors: vec![[0.1, 0.2, 0.3, 1.0], [1.0, 1.0, 1.0, 0.25]],
hatches: vec![
HatchEntry {
hatch: Hatch {
pattern: Pattern::Custom,
kind: HatchKind::Vector,
random: true,
scale: 2.0,
angle: 30.0,
line_weight: 0.13,
origin: Some(v2(1.0, 2.0)),
seed: Some(7.0),
density: Some(1.5),
length_min: Some(0.5),
length_max: Some(2.0),
dash: vec![1.0, 0.5],
motif: Some(Motif { points: vec![v2(0.0, 0.0), v2(1.0, 1.0)], length: 2.0 }),
},
color: 0,
},
HatchEntry {
hatch: Hatch {
pattern: Pattern::Insulation,
kind: HatchKind::Gradient,
random: false,
scale: 1.0,
angle: 0.0,
line_weight: 0.0,
origin: None,
seed: None,
density: None,
length_min: None,
length_max: None,
dash: vec![],
motif: None,
},
color: -1,
},
],
prims: vec![
Prim::Placeholder,
Prim::Polygon {
style: style(),
fill: 1,
stroke: 0,
stroke_width_mm: 0.35,
hatch: 0,
pts: vec![v2(0.0, 0.0), v2(1.0, 0.0), v2(0.0, 1.0)],
no_stroke_edges: vec![1.0, 2.0],
},
Prim::Line {
style: Style { greyed: false, opacity: None },
color: -1,
weight_mm: f64::NAN,
a: v2(0.0, 0.0),
b: v2(3.0, 4.0),
dash: vec![2.0],
chain: true,
zigzag: Some((1.0, 4.0)),
motif: Some(Motif { points: vec![v2(0.0, 0.0), v2(2.0, 1.0)], length: 4.0 }),
},
Prim::Arc {
style: style(),
color: 0,
weight_mm: 0.25,
center: v2(0.0, 0.0),
from: v2(1.0, 0.0),
to: v2(0.0, 1.0),
r: 1.0,
dash: vec![],
},
Prim::Circle { style: style(), fill: -1, stroke: 1, weight_mm: 0.18, center: v2(5.0, 5.0), r: 2.0, dash: vec![] },
Prim::DrawingArc {
style: style(),
stroke: 0,
weight_mm: 0.18,
center: v2(5.0, 5.0),
r: 2.0,
a0: 0.0,
a1: 3.0,
dash: vec![0.5, 0.5],
},
],
}
}
/// NaN-feste Gleichheit über die Bits der Kodierung.
fn bits(v: &[f64]) -> Vec<u64> {
v.iter().map(|x| x.to_bits()).collect()
}
#[test]
fn hin_und_zurueck_je_typ() {
let p = sample();
let enc = encode(&p);
let back = decode(&enc).expect("lesbar");
assert_eq!(bits(&encode(&back)), bits(&enc));
assert_eq!(back.prims.len(), 6);
assert_eq!(back.colors, p.colors);
assert_eq!(back.hatches, p.hatches);
// Je Typ einzeln (NaN-Stärke der Linie über die Bits).
for (i, prim) in p.prims.iter().enumerate() {
if i == 2 {
continue;
}
assert_eq!(&back.prims[i], prim);
}
if let Prim::Line { weight_mm, chain, zigzag, .. } = &back.prims[2] {
assert!(weight_mm.is_nan());
assert!(*chain);
assert_eq!(*zigzag, Some((1.0, 4.0)));
} else {
panic!("Linie erwartet");
}
}
#[test]
fn fremde_version_und_kaputte_puffer() {
let mut enc = encode(&sample());
assert!(decode(&enc[..enc.len() - 1]).is_none());
let mut extra = enc.clone();
extra.push(0.0);
assert!(decode(&extra).is_none());
enc[1] = 2.0;
assert!(decode(&enc).is_none());
enc[1] = VERSION;
enc[0] = 0.0;
assert!(decode(&enc).is_none());
assert!(decode(&[]).is_none());
// Riesige Anzahl ohne Daten: kein Speicher-Absturz.
assert!(decode(&[MAGIC, VERSION, 1e15, 0.0, 0.0]).is_none());
assert!(decode(&[MAGIC, VERSION, 0.0, 0.0, 1.0, 9.0, 0.0]).is_none());
assert!(decode(&[MAGIC, VERSION, 0.0, 0.0, f64::NAN]).is_none());
assert_eq!(recode(&[1.0, 2.0]), Vec::<f64>::new());
}
}
+16
View File
@@ -0,0 +1,16 @@
//! Bindungen der GPU-Kompilierung (`crate::gpu_compile`). Ausgabe-Layout s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Plan-Puffer (ein Chunk) → Vertex-/Index-/Batch-Daten als ein `u32`-Puffer; leer bei
/// unlesbarem Puffer.
#[wasm_bindgen]
pub fn gpu_compile_flat(buf: &[f64], px_per_meter: f64, packed_lines: bool) -> Vec<u32> {
crate::gpu_compile::compile_flat(buf, px_per_meter, packed_lines)
}
/// Ear-Clipping eines Rings `[x, y, …]` → Dreiecks-Indizes.
#[wasm_bindgen]
pub fn triangulate_flat(pts: &[f64]) -> Vec<u32> {
crate::gpu_compile::triangulate(&crate::hatch_flat::pts(pts))
}
+90
View File
@@ -0,0 +1,90 @@
//! Bindungen der Schraffur-/Linienmuster-Geometrie (`crate::hatch`) für die TS-Fassade
//! `glPlanHatch.ts`. Punkte als `[x, y, …]`, Läufe als `[n, x, y, …(n Punkte), n, …]`,
//! Segmente als `[ax, ay, bx, by, …]`, Schraffur im Hatch-Format des Plan-Puffers.
use crate::hatch::{self, v2, Motif};
use crate::hatch_flat::{pts, runs_in, runs_out, segs_out};
use wasm_bindgen::prelude::wasm_bindgen;
fn opt(v: f64) -> Option<f64> {
if v.is_nan() {
None
} else {
Some(v)
}
}
#[wasm_bindgen]
pub fn hatch_runs_flat(poly: &[f64], hatch_buf: &[f64]) -> Vec<f64> {
match crate::plan_buf::decode_hatch(hatch_buf) {
Some((h, _)) => runs_out(&hatch::build_hatch_runs(&pts(poly), &h)),
None => Vec::new(),
}
}
/// `scale` NaN = aus der Schraffur.
#[wasm_bindgen]
pub fn random_hatch_runs_flat(poly: &[f64], hatch_buf: &[f64], scale: f64) -> Vec<f64> {
match crate::plan_buf::decode_hatch(hatch_buf) {
Some((h, _)) => runs_out(&hatch::build_random_hatch_runs(&pts(poly), &h, opt(scale))),
None => Vec::new(),
}
}
#[wasm_bindgen]
pub fn dash_runs_flat(runs: &[f64], dash: &[f64]) -> Vec<f64> {
runs_out(&hatch::apply_dash_runs(runs_in(runs), dash))
}
/// Leer = entartet (Aufrufer nimmt `[a, b]`).
#[wasm_bindgen]
pub fn zigzag_points_flat(ax: f64, ay: f64, bx: f64, by: f64, amplitude: f64, wavelength: f64) -> Vec<f64> {
match hatch::zigzag_points(v2(ax, ay), v2(bx, by), amplitude, wavelength) {
Some(p) => p.iter().flat_map(|q| [q.x, q.y]).collect(),
None => Vec::new(),
}
}
/// Leer = entartet (Aufrufer nimmt `[a, b]`).
#[wasm_bindgen]
pub fn motif_points_flat(ax: f64, ay: f64, bx: f64, by: f64, motif_pts: &[f64], length: f64, scale: f64) -> Vec<f64> {
let m = Motif { points: pts(motif_pts), length };
match hatch::motif_points_opt(v2(ax, ay), v2(bx, by), &m, scale) {
Some(p) => p.iter().flat_map(|q| [q.x, q.y]).collect(),
None => Vec::new(),
}
}
#[wasm_bindgen]
pub fn clip_line_to_polygon_flat(px: f64, py: f64, dx: f64, dy: f64, poly: &[f64]) -> Vec<f64> {
segs_out(&hatch::clip_line_to_polygon(v2(px, py), v2(dx, dy), &pts(poly)))
}
#[wasm_bindgen]
pub fn clip_segment_to_polygon_flat(ax: f64, ay: f64, bx: f64, by: f64, poly: &[f64]) -> Vec<f64> {
segs_out(&hatch::clip_segment_to_polygon(v2(ax, ay), v2(bx, by), &pts(poly)))
}
#[wasm_bindgen]
pub fn clip_polyline_to_polygon_flat(line: &[f64], poly: &[f64]) -> Vec<f64> {
runs_out(&hatch::clip_polyline_to_polygon(&pts(line), &pts(poly)))
}
#[wasm_bindgen]
pub fn hatch_line_family_flat(poly: &[f64], angle_rad: f64, spacing_m: f64, offset_m: f64, ax: f64, ay: f64) -> Vec<f64> {
segs_out(&hatch::hatch_line_family(&pts(poly), angle_rad, spacing_m, offset_m, v2(ax, ay)))
}
/// `len_min`/`len_max` NaN = nicht gesetzt.
#[wasm_bindgen]
pub fn scatter_strokes_flat(
poly: &[f64],
cell: f64,
base_angle_rad: f64,
seed: f64,
stroke_len: f64,
len_min: f64,
len_max: f64,
) -> Vec<f64> {
runs_out(&hatch::scatter_strokes(&pts(poly), cell, base_angle_rad, seed, stroke_len, opt(len_min), opt(len_max)))
}
+3
View File
@@ -23,6 +23,9 @@ mod columns3d;
mod drawing2d_3d;
mod openings3d;
mod wall_mesh_cut;
mod plan_buf;
mod gpu_compile;
mod hatch;
use wasm_bindgen::prelude::wasm_bindgen;
+10
View File
@@ -0,0 +1,10 @@
//! Bindungen des Plan-Puffers (`crate::plan_buf`). Format s. dort.
use wasm_bindgen::prelude::wasm_bindgen;
/// Plan-Puffer lesen und neu schreiben (Hin-und-zurück-Prüfung der TS-Kodierung); leer bei
/// fremder Version oder kaputtem Puffer.
#[wasm_bindgen]
pub fn plan_buf_recode(buf: &[f64]) -> Vec<f64> {
crate::plan_buf::recode(buf)
}