[K3c] Strichmuster im Chunk-Pfad (nativer macOS-Renderer): Instanzen im render2d-Format, gleicher Strich-Shader

Der Chunk-Pfad (gpu_compile → GpuChunkCache → render2d/chunks.rs) hat Linien-Strichmuster nie
gezeichnet (keine Regression von 0516253). Jetzt trägt die GPU-Sicht des Plan-Puffers dash, gpu_compile
gibt gestrichelte Züge als DashSegment-Instanzen aus (Phase über Ketten, Länge wie Szenen-Pfad), der
Chunk-Renderer zeichnet sie mit DASH_LINE_WGSL in Maler-Reihenfolge (lineAt). render_png: --chunks/--bounds.
This commit is contained in:
Claude committed 2026-10-29 12:26:19 +00:00
1 parent 9395ddc5de
commit 7ba007f40c
12 files changed
+827 -53

No files matched your search

+17
View File
@@ -153,6 +153,23 @@ truck (`trucksolid`) bleibt eigenes WASM-Modul (Panic-Isolation), wird vom Kern
SVG/PDF/DXF unberührt. Offen: Kern-Seite bleibt (big16 S2: Schnitt-Primitive 0,37 s, `planSceneBin` 0,45 s); der
Chunk-Pfad (`gpu_compile.rs`, WebGL/nativ-Chunks) zeichnet Striche weiterhin durchgezogen. Nicht in der Tauri-App/Metal und
nicht im Browser-WebGPU angesehen (nur lavapipe/Vulkan headless).
✅ (29.10.) Strichmuster auch im Chunk-Pfad (nativer macOS-Renderer `useNativePlanRenderer` → `GpuChunkCache` →
`render2d/chunks.rs`). Befund: KEINE Regression des Shader-Merges — der Chunk-Pfad hat Linien-Strichmuster nie
gezeichnet (schon die TS-Fassung `glPlanCompile.ts` vor [K3b] ignorierte `dash`, nur Schraffur-Striche wurden zerlegt;
`0516253` hat `core/gpu_compile.rs` nicht berührt) — auf dem Mac waren verdeckte Kanten, Achsen, gestrichelte
Zeichnungen seit jeher durchgezogen. Jetzt: die GPU-Sicht des Plan-Puffers trägt `dash` (Linie/Bogen/Kreis/2D-Bogen),
`gpu_compile` gibt gestrichelte Züge als Instanzen im render2d-Format aus (16 f32: Segment, Lauflänge, Zug, Muster;
Phase über verkettete Linien, Länge Papier-mm × 0,1 wie der Szenen-Pfad, > 8 Einträge zerlegt die CPU), der
Chunk-Renderer zeichnet sie mit DEMSELBEN `DASH_LINE_WGSL`, in Maler-Reihenfolge mit den Linien verzahnt (`lineAt`;
sonst lagen graue verdeckte Kanten über den Schnittkanten). Flaches Format/`NativeChunkLayout` additiv (`dash_inst`,
`dash_batches`, serde-Vorgaben). Tests: Kern (Instanzen, Phase, Muster-Rückfälle, Maler-Reihenfolge, Deckung auf der
Achse = `apply_dash_runs`-Zerlegung, 150 Zufallsfälle), render2d (Reihenfolge; Chunk-Renderer headless zeichnet
Strich/Lücke), TS-Fassade. Bilder (lavapipe, neu `render_png --chunks/--bounds`): Schnitt mit 752 verdeckten Kanten,
Grundriss, gestrichelte Zeichnungen — Chunk-Pfad vs. Szenen-Pfad 0,00 % abweichend in den Schnitt-Ausschnitten,
Rest = Texte (zeichnet der Chunk-Pfad nicht) und vorbestehende Unterschiede; alt (durchgezogen) sichtbar anders.
Nicht kompiliert: `cad-tauri` mit `native2d` für macOS (Linux-Container: cc kann kein `-arch arm64` für
objc2-exception-helper) — `native_embed.rs` ist unverändert, `render2d` (`window`) für `aarch64-apple-darwin`
per `cargo check` geprüft. Nicht auf Metal/in der Tauri-App angesehen.
TS-Fassung gelöscht (29.10.): `toSection.ts`/`toElevation.ts` sind dünne Fassaden (Ebene, Sichtbarkeit, truck-Körper →
Abfrage), `sectionOpenings.ts`, `sectionExtras.ts`, `meshSection.ts`, `generateSectionPlan`/`resolve*SectionStyle` in
`generatePlan.ts`, `windowSymbol` (opening.ts), `keyhole`/`voidSectionRects`/`subtractVoidsInSection` (voids.ts) und ihre
+358 -16
View File
@@ -16,8 +16,18 @@
//! 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)]
//! nLineBatches × (start, count, r, g, b, a, strokeMm, screenPx),
//! nDashInst, nDashBatches, nDashBatches × (start, count, r, g, b, a, strokeMm, lineAt)]
//! danach (hinter lineIdx): dashInst = nDashInst × 16 f32-Bits
//! ```
//! Gestrichelte Striche (Linien, Bögen, Kreise mit Strichmuster) gehen wie im Szenen-Pfad von
//! render2d (`DashSegment`, `DASH_LINE_WGSL`) je Segment als EINE Instanz an die Strich-Pipeline:
//! `[ax, ay, bx, by, s0, runLen, total, count, dash0..dash7]` in Bildschirm-Einheiten (Punkte relativ
//! zu `origin`), der Fragment-Shader setzt Striche/Lücken/runde Enden. Muster mit mehr als
//! [`MAX_LINE_DASH`] Einträgen (nach Verdoppeln) zerlegt weiter die CPU (`apply_dash_runs`).
//! Muster-Längen wie im Szenen-Pfad: Papier-mm × [`LINE_DASH_MM_TO_M`] (Referenz 1:100).
//! `lineAt` = Anzahl Linien-Indizes vor dem Strich-Batch: der Renderer zeichnet ihn vor dem ersten
//! Linien-Batch mit `start >= lineAt` (Maler-Reihenfolge; kein Linien-Batch überspannt ein `lineAt`).
//! 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.
@@ -49,6 +59,31 @@ pub struct LineBatch {
pub screen_px: bool,
}
/// Instanz-Bereich gestrichelter Segmente mit Farbe + Strichbreite (Papier-mm).
pub struct DashBatch {
pub start: u32,
pub count: u32,
pub color: Rgba,
pub stroke_mm: f64,
/// Linien-Indizes vor diesem Batch (Maler-Reihenfolge, s. Modulkopf).
pub line_at: u32,
}
/// Höchstzahl Einträge eines Strichmusters im Shader (wie `render2d::MAX_LINE_DASH`).
pub const MAX_LINE_DASH: usize = 8;
/// f32 je Strich-Instanz (wie `DashInstance` in render2d: ab, run, dash[8]).
pub const DASH_INST_FLOATS: usize = 16;
/// Papier-mm → Modell-Meter für Linien-Strichmuster: `N/1000` bei der Referenz-Skala 1:100, wie der
/// Szenen-Pfad (`render2d::tessellate`, `DASH_MM_TO_M` dort). Schraffur-Striche nehmen die an die
/// Musterkachel gekoppelte `hatch::DASH_MM_TO_M`.
pub const LINE_DASH_MM_TO_M: f64 = 100.0 / 1000.0;
/// Strichmuster einer Linie so umgerechnet, dass `hatch::apply_dash_runs` (rechnet mit
/// `hatch::DASH_MM_TO_M`) in [`LINE_DASH_MM_TO_M`] zerlegt.
fn line_dash_for_runs(dash: &[f64]) -> Vec<f64> {
dash.iter().map(|d| d * (LINE_DASH_MM_TO_M / DASH_MM_TO_M)).collect()
}
/// Ergebnis der Kompilierung (Bildschirm-Raum relativ zu `origin`).
pub struct GpuOut {
pub fill_pos: Vec<f32>,
@@ -58,6 +93,9 @@ pub struct GpuOut {
pub line_verts: Vec<u32>,
pub line_idx: Vec<u32>,
pub line_batches: Vec<LineBatch>,
/// Strich-Instanzen ([`DASH_INST_FLOATS`] je Segment), s. Modulkopf.
pub dash_inst: Vec<f32>,
pub dash_batches: Vec<DashBatch>,
pub origin: (f64, f64),
/// Modell-Bounds (Meter): (minX, minY, maxX, maxY), ±∞ wenn leer.
pub bounds: (f64, f64, f64, f64),
@@ -271,6 +309,8 @@ struct Compiler {
line_verts: Vec<u32>,
line_idx: Vec<u32>,
line_batches: Vec<LineBatch>,
dash_inst: Vec<f32>,
dash_batches: Vec<DashBatch>,
origin_x: f64,
origin_y: f64,
origin_set: bool,
@@ -324,7 +364,9 @@ impl Compiler {
}
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() {
// Nicht über einen dazwischen gezeichneten Strich-Batch hinweg zusammenfassen.
let dash_after = self.dash_batches.last().map_or(0, |d| d.line_at);
if let Some(last) = self.line_batches.last_mut().filter(|l| dash_after <= l.start) {
if last.stroke_mm == stroke_mm && last.screen_px == screen_px && same_rgba(&last.color, &color) {
last.count += count as u32;
return;
@@ -333,6 +375,97 @@ impl Compiler {
self.line_batches.push(LineBatch { start: (self.line_idx.len() - count) as u32, count: count as u32, color, stroke_mm, screen_px });
}
fn add_dash_batch(&mut self, count: usize, color: Rgba, stroke_mm: f64) {
let line_at = self.line_idx.len() as u32;
if let Some(last) = self.dash_batches.last_mut() {
// Nur ohne Linien dazwischen (sonst ginge die Maler-Reihenfolge verloren).
if last.line_at == line_at && last.stroke_mm == stroke_mm && same_rgba(&last.color, &color) {
last.count += count as u32;
return;
}
}
let start = (self.dash_inst.len() / DASH_INST_FLOATS - count) as u32;
self.dash_batches.push(DashBatch { start, count: count as u32, color, stroke_mm, line_at });
}
/// Linienzug mit Strichmuster `dash` (Papier-mm): gültiges Muster bis [`MAX_LINE_DASH`]
/// Einträge → Shader-Instanzen; längeres → CPU-Zerlegung; ungültiges/fehlendes → durchgezogen.
fn stroke_styled(&mut self, pts_m: &[V2], closed: bool, dash: Option<&[f64]>, color: Rgba, stroke_mm: f64) {
let Some(d) = dash.filter(|d| !d.is_empty()) else {
return self.stroke_polyline(pts_m, closed, color, stroke_mm, false);
};
match dash_cycle_m(d) {
Some(cycle) if cycle.len() <= MAX_LINE_DASH => self.stroke_dashed(pts_m, closed, &cycle, color, stroke_mm),
Some(_) => {
let mut run = pts_m.to_vec();
if closed && pts_m.len() > 2 {
run.push(pts_m[0]);
}
for piece in hatch::apply_dash_runs(vec![run], &line_dash_for_runs(d)) {
self.stroke_polyline(&piece, false, color, stroke_mm, false);
}
}
None => self.stroke_polyline(pts_m, closed, color, stroke_mm, false),
}
}
/// Gestrichelter Linienzug (Modell-Meter) mit gültigem Zyklus `cycle_m` (Meter, gerade Länge):
/// je Segment eine Instanz mit Lauflänge, Phase über den ganzen Zug (wie `apply_dash_runs`);
/// Segmente kürzer als 1e-12 m entfallen. Ein geschlossener Zug wird um die Schlusskante ergänzt.
fn stroke_dashed(&mut self, pts_m: &[V2], closed: bool, cycle_m: &[f64], color: Rgba, stroke_mm: f64) {
if pts_m.len() < 2 {
return;
}
let close = closed && pts_m.len() > 2 && (pts_m[0].x != pts_m[pts_m.len() - 1].x || pts_m[0].y != pts_m[pts_m.len() - 1].y);
let n_seg = pts_m.len() - 1 + usize::from(close);
let seg = |i: usize| (pts_m[i], pts_m[(i + 1) % pts_m.len()]);
let mut run = 0.0f64;
for i in 0..n_seg {
let (a, b) = seg(i);
let l = hypot2(b.x - a.x, b.y - a.y);
if l >= 1e-12 {
run += l;
}
}
if !(run > 0.0) || !run.is_finite() {
return;
}
let mut dash = [0.0f32; MAX_LINE_DASH];
for (d, c) in dash.iter_mut().zip(cycle_m) {
*d = (c * PX_PER_M) as f32;
}
let total: f64 = cycle_m.iter().sum::<f64>() * PX_PER_M;
let before = self.dash_inst.len();
let mut s0 = 0.0f64;
for i in 0..n_seg {
let (a, b) = seg(i);
let l = hypot2(b.x - a.x, b.y - a.y);
if !(l >= 1e-12) {
continue;
}
let sa = self.scr(a);
let sb = self.scr(b);
self.track(a.x, a.y);
self.track(b.x, b.y);
self.dash_inst.extend_from_slice(&[
sa.x as f32,
sa.y as f32,
sb.x as f32,
sb.y as f32,
(s0 * PX_PER_M) as f32,
(run * PX_PER_M) as f32,
total as f32,
cycle_m.len() as f32,
]);
self.dash_inst.extend_from_slice(&dash);
s0 += l;
}
let n = (self.dash_inst.len() - before) / DASH_INST_FLOATS;
if n > 0 {
self.add_dash_batch(n, color, stroke_mm);
}
}
#[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 };
@@ -566,6 +699,18 @@ impl Compiler {
}
}
/// Strichmuster (Papier-mm) → Zyklus in Modell-Metern wie `split_dash` in render2d: negative Werte
/// zu 0, Nullen weg, ungerade Länge verdoppelt. `None` = kein gültiges Muster (durchgezogen).
fn dash_cycle_m(dash: &[f64]) -> Option<Vec<f64>> {
let pat: Vec<f64> = dash.iter().map(|&d| jsnum::max(0.0, d) * LINE_DASH_MM_TO_M).filter(|&d| d > 0.0).collect();
if pat.is_empty() {
return None;
}
let cycle: Vec<f64> = if pat.len() % 2 == 0 { pat } else { [pat.as_slice(), pat.as_slice()].concat() };
let total: f64 = cycle.iter().sum();
(total > 1e-9 && total.is_finite()).then_some(cycle)
}
/// 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 {
@@ -597,6 +742,8 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut {
line_verts: Vec::new(),
line_idx: Vec::new(),
line_batches: Vec::new(),
dash_inst: Vec::new(),
dash_batches: Vec::new(),
origin_x: 0.0,
origin_y: 0.0,
origin_set: false,
@@ -617,7 +764,7 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut {
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 {
let Prim::Line { style, color, weight_mm, a, b, zigzag: None, motif: None, dash, .. } = &prims[i] else {
i += 1;
continue;
};
@@ -640,7 +787,7 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut {
}
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);
c.stroke_styled(&pts, false, dash.as_deref(), col, weight_or_default(*weight_mm));
for m in merged.iter_mut().take(j).skip(i) {
*m = true;
}
@@ -677,7 +824,7 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut {
}
}
}
Prim::Line { style, color, weight_mm, a, b, zigzag, motif, .. } => {
Prim::Line { style, color, weight_mm, a, b, zigzag, motif, dash, .. } => {
let col = dim(color_or_ink(plan, *color), style);
let w = weight_or_default(*weight_mm);
if let Some((amp, wav)) = zigzag {
@@ -687,10 +834,10 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut {
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);
c.stroke_styled(&[*a, *b], false, dash.as_deref(), col, w);
}
}
Prim::Arc { style, color, weight_mm, center, from, to, r, .. } => {
Prim::Arc { style, color, weight_mm, center, from, to, r, dash } => {
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);
@@ -710,13 +857,13 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut {
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);
c.stroke_styled(&arc_pts, false, dash.as_deref(), col, stroke_mm);
}
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::Circle { style, fill, stroke, weight_mm, center, r, dash } => {
draw_circle_like(&mut c, plan, style, Some(*fill), *stroke, *weight_mm, *center, *r, None, px_per_meter, dash.as_deref());
}
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);
Prim::DrawingArc { style, stroke, weight_mm, center, r, a0, a1, dash } => {
draw_circle_like(&mut c, plan, style, None, *stroke, *weight_mm, *center, *r, Some((*a0, *a1)), px_per_meter, dash.as_deref());
}
}
}
@@ -728,6 +875,8 @@ pub fn compile(plan: &PlanBuf, px_per_meter: f64, packed: bool) -> GpuOut {
line_verts: c.line_verts,
line_idx: c.line_idx,
line_batches: c.line_batches,
dash_inst: c.dash_inst,
dash_batches: c.dash_batches,
origin: (c.origin_x, c.origin_y),
bounds: (c.min_x, c.min_y, c.max_x, c.max_y),
}
@@ -746,6 +895,7 @@ fn draw_circle_like(
r: f64,
arc: Option<(f64, f64)>,
px_per_meter: f64,
dash: Option<&[f64]>,
) {
let stroke_col = dim(color_or_ink(plan, stroke), style);
let stroke_mm = weight_or_default(weight_mm);
@@ -776,7 +926,7 @@ fn draw_circle_like(
}
}
}
c.stroke_polyline(&pts, fill.is_some(), stroke_col, stroke_mm, false);
c.stroke_styled(&pts, fill.is_some(), dash, stroke_col, stroke_mm);
}
/// Flache Ausgabe (s. Modulkopf) für die Primitive `[from, to)` eines Plan-Puffers (v2); leer bei
@@ -813,7 +963,12 @@ pub fn compile_flat(bytes: &[u8], from: usize, to: usize, px_per_meter: f64, pac
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());
meta.push((o.dash_inst.len() / DASH_INST_FLOATS) as f64);
meta.push(o.dash_batches.len() as f64);
for b in &o.dash_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, b.line_at as f64]);
}
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() + o.dash_inst.len());
out.push(meta.len() as u32);
out.push(0);
for m in &meta {
@@ -825,6 +980,7 @@ pub fn compile_flat(bytes: &[u8], from: usize, to: usize, px_per_meter: f64, pac
out.extend_from_slice(&o.fill_idx);
out.extend_from_slice(&o.line_verts);
out.extend_from_slice(&o.line_idx);
out.extend(o.dash_inst.iter().map(|v| v.to_bits()));
out
}
@@ -847,6 +1003,7 @@ mod tests {
chain,
zigzag: None,
motif: None,
dash: None,
}
}
@@ -926,8 +1083,8 @@ mod tests {
#[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 },
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 },
Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.0, center: v2(1.0, 1.0), r: 1.0, dash: None },
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: None },
Prim::Placeholder,
]);
let o = compile(&p, 0.0, false);
@@ -960,4 +1117,189 @@ mod tests {
assert!(compile_flat(&enc, 0, 2, 90.0, true).is_empty(), "Bereich ausserhalb");
assert!(!compile_flat(&enc, 1, 1, 90.0, true).is_empty(), "leerer Bereich = leere Geometrie");
}
// --- Strichmuster im Shader (Chunk-Pfad, gleiche Instanzen wie render2d `DashSegment`) ---
fn dashed(ax: f64, bx: f64, chain: bool, dash: Vec<f64>) -> Prim {
Prim::Line { style: st(), color: 0, weight_mm: 0.25, a: v2(ax, 0.0), b: v2(bx, 0.0), chain, zigzag: None, motif: None, dash: Some(dash) }
}
/// Instanz `i` als (a, b, s0, run_len, total, count, dash[8]).
fn inst(o: &GpuOut, i: usize) -> &[f32] {
&o.dash_inst[i * DASH_INST_FLOATS..(i + 1) * DASH_INST_FLOATS]
}
#[test]
fn gestrichelte_linie_als_shader_instanz() {
let o = compile(&plan(vec![dashed(1.0, 4.0, false, vec![0.12, 0.08])]), 90.0, true);
assert!(o.line_idx.is_empty() && o.line_verts.is_empty(), "keine durchgezogenen Striche mehr");
assert_eq!(o.dash_inst.len(), DASH_INST_FLOATS);
let d = inst(&o, 0);
// Bildschirm-Raum relativ zum Ursprung (erster Punkt).
assert_eq!(o.origin, (90.0, -0.0));
assert_eq!(&d[..4], &[0.0, 0.0, 270.0, 0.0]);
assert_eq!((d[4], d[5], d[7]), (0.0, 270.0, 2.0));
let (on, off) = ((0.12 * LINE_DASH_MM_TO_M * PX_PER_M) as f32, (0.08 * LINE_DASH_MM_TO_M * PX_PER_M) as f32);
assert_eq!((d[8], d[9]), (on, off));
assert!((d[6] - (on + off)).abs() < 1e-4);
assert!(d[10..].iter().all(|&v| v == 0.0));
assert_eq!(o.dash_batches.len(), 1);
assert_eq!((o.dash_batches[0].start, o.dash_batches[0].count, o.dash_batches[0].stroke_mm), (0, 1, 0.25));
assert_eq!(o.bounds, (1.0, 0.0, 4.0, 0.0));
}
#[test]
fn gestrichelter_zug_phase_laeuft_durch() {
// Verkettete Linien: ein Zug, Phase über die Ecke, ungerades Muster verdoppelt.
let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![1.0]), dashed(1.0, 3.0, true, vec![1.0])]), 90.0, true);
assert_eq!(o.dash_inst.len(), 2 * DASH_INST_FLOATS);
assert_eq!(inst(&o, 1)[4], 90.0);
assert_eq!(inst(&o, 1)[5], 270.0);
assert_eq!(inst(&o, 1)[7], 2.0);
assert_eq!(o.dash_batches.len(), 1);
assert_eq!(o.dash_batches[0].count, 2);
// Einzeln (nicht verkettet): jede Linie beginnt ihr Muster neu.
let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![1.0]), dashed(1.0, 3.0, false, vec![1.0])]), 90.0, true);
assert_eq!(inst(&o, 1)[4], 0.0);
assert_eq!(inst(&o, 1)[5], 180.0);
}
#[test]
fn ungueltiges_muster_durchgezogen_langes_muster_zerlegt() {
let solid = compile(&plan(vec![line(0.0, 1.0, false)]), 90.0, true);
let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![0.0, -1.0])]), 90.0, true);
assert!(o.dash_inst.is_empty());
assert_eq!(o.line_idx.len(), solid.line_idx.len(), "Nullmuster = durchgezogen");
let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![])]), 90.0, true);
assert!(o.dash_inst.is_empty() && o.line_idx.len() == solid.line_idx.len());
// 9 Einträge → verdoppelt 18 > MAX_LINE_DASH: CPU-Zerlegung (mehrere Stücke).
let o = compile(&plan(vec![dashed(0.0, 1.0, false, vec![1.0; 9])]), 90.0, true);
assert!(o.dash_inst.is_empty());
assert!(o.line_idx.len() > 2 * solid.line_idx.len());
}
#[test]
fn gestrichelte_boegen_und_kreise() {
let d = Some(vec![2.0, 1.0]);
let p = plan(vec![
Prim::Arc { style: st(), color: 0, weight_mm: 0.18, center: v2(0.0, 0.0), from: v2(1.0, 0.0), to: v2(0.0, 1.0), r: 1.0, dash: d.clone() },
Prim::Circle { style: st(), fill: 1, stroke: 0, weight_mm: 0.18, center: v2(3.0, 0.0), r: 1.0, dash: d.clone() },
Prim::DrawingArc { style: st(), stroke: 0, weight_mm: 0.18, center: v2(0.0, 0.0), r: 2.0, a0: 0.0, a1: 1.0, dash: d },
]);
let o = compile(&p, 90.0, true);
assert!(o.line_idx.is_empty(), "alle Striche gestrichelt");
assert!(!o.fill_idx.is_empty(), "Kreisfüllung bleibt");
let n = o.dash_inst.len() / DASH_INST_FLOATS;
assert!(n > 20);
// Kreis: geschlossen, die Lauflänge reicht um den ganzen Umfang.
let circle_run = (0..n).map(|i| inst(&o, i)[5]).fold(0.0f32, f32::max);
assert!((circle_run as f64 - 2.0 * PI * PX_PER_M).abs() < 2.0, "Kreisumfang {circle_run}");
// gleiche Farbe/Breite → ein Batch
assert_eq!(o.dash_batches.len(), 1);
assert_eq!(o.dash_batches[0].count as usize, n);
}
/// Auf der Achse deckt eine Instanz genau die Stücke der CPU-Zerlegung (`apply_dash_runs`,
/// gleiche Semantik wie die frühere `split_dash`-Zerlegung in render2d): Spiegel des
/// Fragment-Shaders (`DASH_LINE_WGSL`) für y = 0 und Breite → 0.
#[test]
fn deckung_auf_der_achse_wie_zerlegung() {
let mut seed = 777u32;
let mut rnd = || {
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
(seed >> 8) as f64 / (1u32 << 24) as f64
};
for case in 0..150 {
let n = 1 + (rnd() * 4.0) as usize;
let pat: Vec<f64> = (0..n).map(|_| 0.5 + rnd() * 8.0).collect();
// Zug aus 1–4 kollinearen Stücken entlang x.
let mut xs = vec![0.0];
for _ in 0..1 + case % 4 {
xs.push(xs[xs.len() - 1] + 0.05 + rnd() * 1.5);
}
let prims: Vec<Prim> = xs.windows(2).enumerate().map(|(i, w)| dashed(w[0], w[1], i > 0, pat.clone())).collect();
let o = compile(&plan(prims), 90.0, true);
let runs = hatch::apply_dash_runs(vec![xs.iter().map(|&x| v2(x, 0.0)).collect()], &line_dash_for_runs(&pat));
let total_len = xs[xs.len() - 1];
for _ in 0..300 {
let x = rnd() * total_len;
let old = runs.iter().any(|r| x >= r[0].x - 1e-9 && x <= r[r.len() - 1].x + 1e-9);
let new = (0..o.dash_inst.len() / DASH_INST_FLOATS).any(|i| {
let d = inst(&o, i);
let sx = (x * PX_PER_M) as f32 - (d[0] + o.origin.0 as f32);
let (s0, s1) = (d[4], d[4] + (d[2] - d[0]));
let s = d[4] + sx;
if s < s0 || s > s1 {
return false;
}
let (total, cnt) = (d[6], d[7] as usize);
let k = (s / total).floor();
let m = s - k * total;
let mut acc = 0.0f32;
let mut on = true;
for (j, &len) in d[8..8 + cnt].iter().enumerate() {
if m >= acc && m < acc + len {
on = j % 2 == 0;
}
acc += len;
}
on
});
// An den Strichgrenzen entscheidet die Rundung — dort nicht vergleichen.
let near_edge = runs.iter().any(|r| (x - r[0].x).abs() < 1e-4 || (x - r[r.len() - 1].x).abs() < 1e-4);
assert!(old == new || near_edge, "Fall {case}: x={x} alt {old} neu {new}");
}
}
}
/// Maler-Reihenfolge: Linie, gestrichelte Linie, Linie (gleicher Stil) bleiben drei Batches in
/// dieser Folge — die zweite Linie deckt die gestrichelte (z. B. verdeckte Kante unter einer Wand).
#[test]
fn strich_batches_in_maler_reihenfolge() {
let o = compile(&plan(vec![line(0.0, 1.0, false), dashed(0.0, 1.0, false, vec![2.0, 1.0]), dashed(0.0, 2.0, false, vec![2.0, 1.0]), line(2.0, 3.0, false)]), 90.0, true);
assert_eq!(o.line_batches.len(), 2, "keine Zusammenfassung über den Strich-Batch hinweg");
assert_eq!(o.dash_batches.len(), 1, "zwei gestrichelte ohne Linie dazwischen = ein Batch");
assert_eq!(o.dash_batches[0].count, 2);
assert_eq!(o.dash_batches[0].line_at, o.line_batches[0].count);
assert_eq!(o.line_batches[1].start, o.dash_batches[0].line_at);
// Ohne Strich dazwischen werden gleich gestylte Linien weiter zusammengefasst.
let o = compile(&plan(vec![line(0.0, 1.0, false), line(2.0, 3.0, false)]), 90.0, true);
assert_eq!(o.line_batches.len(), 1);
}
#[test]
fn flache_ausgabe_traegt_strich_instanzen() {
let mut w = plan_buf::Writer::new(false);
w.push(&crate::plan::prim::Primitive::Line {
a: crate::model::Vec2 { x: 0.0, y: 0.0 },
b: crate::model::Vec2 { x: 2.0, y: 0.0 },
cls: "c".into(),
weight_mm: 0.35,
dash: Some(Some(vec![3.0, 1.0])),
zigzag: None,
motif: None,
color: Some("#ff0000".into()),
drawing_id: None,
opening_id: None,
stair_id: None,
greyed: None,
opacity: None,
});
let enc = w.finish();
let out = compile_flat(&enc, 0, 1, 90.0, true);
let m = out[0] as usize;
let meta: Vec<f64> = (0..m).map(|i| f64::from_bits(out[2 + 2 * i] as u64 | ((out[3 + 2 * i] as u64) << 32))).collect();
let (n_fill, n_line) = (meta[10] as usize, meta[11] as usize);
assert_eq!((n_fill, n_line), (0, 0));
let k = 12 + 6 * n_fill + 8 * n_line;
assert_eq!(meta[k], 1.0, "eine Instanz");
assert_eq!(meta[k + 1], 1.0, "ein Strich-Batch");
assert_eq!(&meta[k + 2..k + 10], &[0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.35, 0.0]);
assert_eq!(meta.len(), k + 10);
let data = &out[2 + 2 * m..];
let (nfp, nfi, nlv, nli) = (meta[6] as usize, meta[7] as usize, meta[8] as usize, meta[9] as usize);
let dash = &data[nfp + nfi + nlv + nli..];
assert_eq!(dash.len(), DASH_INST_FLOATS);
assert_eq!(f32::from_bits(dash[2]), 180.0);
assert_eq!(f32::from_bits(dash[7]), 2.0);
}
}
+13 -3
View File
@@ -162,6 +162,8 @@ pub enum Prim {
chain: bool,
zigzag: Option<(f64, f64)>,
motif: Option<Motif>,
/// Strichmuster (Papier-mm, wie im Puffer); `None` = durchgezogen.
dash: Option<Vec<f64>>,
},
Arc {
style: Style,
@@ -171,6 +173,7 @@ pub enum Prim {
from: V2,
to: V2,
r: f64,
dash: Option<Vec<f64>>,
},
Circle {
style: Style,
@@ -179,6 +182,7 @@ pub enum Prim {
weight_mm: f64,
center: V2,
r: f64,
dash: Option<Vec<f64>>,
},
DrawingArc {
style: Style,
@@ -188,6 +192,7 @@ pub enum Prim {
r: f64,
a0: f64,
a1: f64,
dash: Option<Vec<f64>>,
},
}
@@ -747,6 +752,10 @@ impl<'a> View<'a> {
let rec = self.rec(i)?;
let greyed = rec.flags & F_GREYED != 0;
let f = &rec.f;
let dash = match rec.dash {
Some((o, n)) => Some(self.pool(o, n)?),
None => None,
};
let p = match rec.tag {
T_POLYGON => {
let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[4]) };
@@ -793,23 +802,24 @@ impl<'a> View<'a> {
chain: i > from && rec.flags & F_CHAIN != 0,
zigzag: rec.zigzag,
motif,
dash,
}
}
T_ARC => {
let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[3]) };
let c = color(&mut out, f[1])?;
Prim::Arc { style, color: c, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, from: V2 { x: f[6], y: f[7] }, to: V2 { x: f[8], y: f[9] }, r: f[10] }
Prim::Arc { style, color: c, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, from: V2 { x: f[6], y: f[7] }, to: V2 { x: f[8], y: f[9] }, r: f[10], dash }
}
T_CIRCLE => {
let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[3]) };
let fill = color(&mut out, f[0])?;
let stroke = color(&mut out, f[1])?;
Prim::Circle { style, fill, stroke, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, r: f[6] }
Prim::Circle { style, fill, stroke, weight_mm: f[2], center: V2 { x: f[4], y: f[5] }, r: f[6], dash }
}
T_DRAWING_ARC => {
let style = Style { greyed, opacity: opt(rec.flags, F_OPACITY, f[2]) };
let stroke = color(&mut out, f[0])?;
Prim::DrawingArc { style, stroke, weight_mm: f[1], center: V2 { x: f[3], y: f[4] }, r: f[5], a0: f[6], a1: f[7] }
Prim::DrawingArc { style, stroke, weight_mm: f[1], center: V2 { x: f[3], y: f[4] }, r: f[5], a0: f[6], a1: f[7], dash }
}
_ => Prim::Placeholder,
};
+43 -8
View File
@@ -4,9 +4,12 @@
// Session funktioniert.
//
// Start: cargo run --features headless --bin render_png -- [--out PFAD] [--width N] [--height N]
// [--scene szene.bin] [--crop x0,y0,x1,y1] [--scale N]
// [--scene szene.bin | --chunks a.bin,b.bin…] [--bounds minX,minY,maxX,maxY] [--crop x0,y0,x1,y1] [--scale N]
// `--scene`: Szene-Bytes wie für `set_scene_bin` (statt der Demo); Ausschnitt = Ausmass der Szene,
// `--crop` wählt daraus einen Teil (Anteile 0..1, y von oben), `--scale` den Papier-Massstab 1:N.
// `--chunks`: GPU-Chunks (je Datei die u32-Ausgabe von `gpu_compile_flat`, gepackt) über den
// Chunk-Renderer des nativen macOS-Pfads (`chunks.rs`); Ausschnitt = Vereinigung der Chunk-Ausmasse.
// `--bounds` (Modell-Meter) ersetzt das Ausmass — für deckungsgleiche Vergleiche Szene ↔ Chunks.
#![cfg(feature = "headless")]
use render2d::headless::HeadlessRenderer;
@@ -21,6 +24,8 @@ fn main() {
let mut scene_file: Option<String> = None;
let mut crop = [0.0f32, 0.0, 1.0, 1.0];
let mut paper_n = 100.0f32;
let mut chunk_files: Vec<String> = Vec::new();
let mut bounds_arg: Option<[f32; 4]> = None;
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
@@ -39,6 +44,13 @@ fn main() {
}
"--out" => out = args.next().unwrap_or(out),
"--scene" => scene_file = args.next(),
"--chunks" => chunk_files = args.next().unwrap_or_default().split(',').filter(|f| !f.is_empty()).map(String::from).collect(),
"--bounds" => {
let v: Vec<f32> = args.next().unwrap_or_default().split(',').filter_map(|x| x.parse().ok()).collect();
if v.len() == 4 {
bounds_arg = Some([v[0], v[1], v[2], v[3]]);
}
}
"--scale" => paper_n = args.next().and_then(|v| v.parse().ok()).unwrap_or(paper_n),
"--crop" => {
let v: Vec<f32> = args.next().unwrap_or_default().split(',').filter_map(|x| x.parse().ok()).collect();
@@ -51,18 +63,41 @@ fn main() {
}
let mut renderer = HeadlessRenderer::new().expect("Headless-Renderer initialisieren");
// Ausmass (Modell-Meter) → Bildschirm-Raum (x·90, −y·90), dann der Ausschnitt.
let view_of = |b: [f32; 4]| {
let (x0, x1) = (b[0] * 90.0, b[2] * 90.0);
let (y0, y1) = (-b[3] * 90.0, -b[1] * 90.0);
let (w, h) = (x1 - x0, y1 - y0);
ViewBox::new(x0 + crop[0] * w, y0 + crop[1] * h, (crop[2] - crop[0]) * w, (crop[3] - crop[1]) * h)
};
if !chunk_files.is_empty() {
let chunks: Vec<Vec<u32>> = chunk_files
.iter()
.map(|f| std::fs::read(f).expect("Chunk lesen").chunks_exact(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())
.collect();
let b = bounds_arg.unwrap_or_else(|| {
let mut b = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
for c in &chunks {
if let Some(cb) = render2d::headless::chunk_flat_bounds(c) {
b = [b[0].min(cb[0] as f32), b[1].min(cb[1] as f32), b[2].max(cb[2] as f32), b[3].max(cb[3] as f32)];
}
}
b
});
let vb = view_of(b);
let view = render2d::chunks::View { x: vb.x as f64, y: vb.y as f64, w: vb.w as f64, h: vb.h as f64 };
let image = renderer.render_chunks_to_image(&chunks, width, height, view, paper_n as f64).expect("Chunks rendern");
std::fs::write(&out, image.encode_png()).expect("PNG schreiben");
println!("render_png: Chunks geschrieben nach {out} ({width}x{height})");
return;
}
let (scene, view_box) = match &scene_file {
None => (demo_scene(), initial_view_box()),
Some(f) => {
let bytes = std::fs::read(f).expect("Szene lesen");
let scene = render2d::scene_bin::decode_scene(&bytes).expect("Szene dekodieren");
// Ausmass (Modell-Meter) → Bildschirm-Raum (x·90, −y·90), dann der Ausschnitt.
let b = render2d::compile_scene(&scene).bounds;
let (x0, x1) = (b[0] * 90.0, b[2] * 90.0);
let (y0, y1) = (-b[3] * 90.0, -b[1] * 90.0);
let (w, h) = (x1 - x0, y1 - y0);
let vb = ViewBox::new(x0 + crop[0] * w, y0 + crop[1] * h, (crop[2] - crop[0]) * w, (crop[3] - crop[1]) * h);
(scene, vb)
let b = bounds_arg.unwrap_or_else(|| render2d::compile_scene(&scene).bounds);
(scene, view_of(b))
}
};
let image = renderer.render_to_image(&scene, width, height, view_box, paper_n);
+151 -25
View File
@@ -7,6 +7,12 @@
//
// Linien-Vertices kommen KOMPAKT (12 Byte, s. LINE_PACKED_WGSL).
//
// Gestrichelte Striche kommen als Instanzen (je Segment 16 x f32, Format wie
// `DashSegment`/`gpu::DashInstance`) und laufen durch DIESELBE Strich-Pipeline wie
// der Szenen-Pfad (`DASH_LINE_WGSL`: Striche, Luecken, runde Enden im Fragment-
// Shader). Innerhalb eines Chunks in Maler-Reihenfolge mit den Linien verzahnt
// (`DashBatch::line_at`), damit spaetere Striche fruehere gestrichelte decken.
//
// Die Webview kompiliert weiterhin (Cache/Chunk-Logik bleibt in TypeScript) und
// schickt nur noch die Puffer-BYTES je Chunk einmalig; pro Frame geht nur der
// Ausschnitt (viewBox) hierher. Rust haelt die Puffer — kein JSON, kein
@@ -17,7 +23,7 @@ use std::collections::HashMap;
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;
use crate::shaders::FILL_WGSL;
use crate::shaders::{DASH_LINE_WGSL, FILL_WGSL};
/// Graustufe fuer gedimmte Linien (== GREY_RGB in glPlanCompile.ts).
const GREY: f32 = 0.549;
@@ -175,6 +181,40 @@ pub struct LineBatch {
pub device_px: bool,
}
/// Instanz-Bereich gestrichelter Segmente (Strich-Pipeline) mit Farbe + Papier-mm.
#[derive(Clone, Debug, serde::Deserialize)]
pub struct DashBatch {
pub start: u32,
pub count: u32,
pub color: [f32; 4],
pub stroke_mm: f32,
/// Maler-Reihenfolge: gezeichnet vor dem ersten Linien-Batch mit `start >= line_at`
/// (Linien-Index-Position beim Erzeugen; kein Linien-Batch ueberspannt sie).
#[serde(default)]
pub line_at: u32,
}
/// Zeichenfolge der Striche eines Chunks: (gestrichelt?, Batch-Index), Linien und
/// gestrichelte Batches nach `line_at` verzahnt. Fehlen die Puffer einer Art, entfaellt sie.
fn stroke_order(g: &ChunkGeom) -> Vec<(bool, usize)> {
let lines = if g.line_vtx.is_some() && g.line_idx.is_some() { g.line_batches.len() } else { 0 };
let dashes = if g.dash_inst.is_some() { g.dash_batches.len() } else { 0 };
let mut out = Vec::with_capacity(lines + dashes);
let mut j = 0;
for i in 0..lines {
while j < dashes && g.dash_batches[j].line_at <= g.line_batches[i].start {
out.push((true, j));
j += 1;
}
out.push((false, i));
}
out.extend((j..dashes).map(|k| (true, k)));
out
}
/// Bytes je Strich-Instanz (16 x f32: ab, run, dash[8]; wie `gpu::DashInstance`).
pub const DASH_INSTANCE_BYTES: u64 = 16 * 4;
/// Ein Chunk (== `GpuGeometry` der Webview): Puffer-IDs statt GL-Puffer.
#[derive(Clone, Debug, serde::Deserialize)]
pub struct ChunkGeom {
@@ -184,6 +224,11 @@ pub struct ChunkGeom {
pub line_vtx: Option<u32>,
pub line_idx: Option<u32>,
pub line_batches: Vec<LineBatch>,
/// Puffer der Strich-Instanzen (gestrichelte Segmente); fehlt ohne Strichmuster.
#[serde(default)]
pub dash_inst: Option<u32>,
#[serde(default)]
pub dash_batches: Vec<DashBatch>,
pub origin: [f64; 2],
#[serde(default)]
pub greyed: bool,
@@ -201,6 +246,7 @@ pub struct View {
pub struct ChunkRenderer {
fill_pipeline: wgpu::RenderPipeline,
line_pipeline: wgpu::RenderPipeline,
dash_pipeline: wgpu::RenderPipeline,
bind_group_layout: wgpu::BindGroupLayout,
uniform: Option<(wgpu::Buffer, wgpu::BindGroup, u64)>,
buffers: HashMap<u32, wgpu::Buffer>,
@@ -338,6 +384,20 @@ impl ChunkRenderer {
},
"chunks.line.pipeline",
);
// Gestrichelte Segmente: Instanz-Puffer, Quad aus `vertex_index` (wie gpu.rs).
let dash_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("chunks.dash"),
source: wgpu::ShaderSource::Wgsl(DASH_LINE_WGSL.into()),
});
let dash_pipeline = make(
&dash_module,
wgpu::VertexBufferLayout {
array_stride: DASH_INSTANCE_BYTES,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4, 2 => Float32x4, 3 => Float32x4],
},
"chunks.dash.pipeline",
);
let text_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("chunks.text"),
source: wgpu::ShaderSource::Wgsl(TEXT_WGSL.into()),
@@ -387,6 +447,7 @@ impl ChunkRenderer {
inst_buf: None,
fill_pipeline,
line_pipeline,
dash_pipeline,
bind_group_layout,
uniform: None,
buffers: HashMap::new(),
@@ -567,20 +628,20 @@ impl ChunkRenderer {
blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: 0.0, stroke_scale: 1.0 });
}
}
for g in self.layout.iter().chain(self.highlight.iter()) {
if g.line_vtx.is_none() || g.line_idx.is_none() {
continue;
}
// Striche (Linien + gestrichelte) je Chunk in Maler-Reihenfolge (`stroke_order`).
let orders: Vec<Vec<(bool, usize)>> = self.layout.iter().chain(self.highlight.iter()).map(stroke_order).collect();
for (g, order) in self.layout.iter().chain(self.highlight.iter()).zip(&orders) {
let proj = projection(bounds, g.origin);
for b in &g.line_batches {
let c = if g.greyed { [GREY, GREY, GREY, b.color[3]] } else { b.color };
blocks.push(Globals {
view_proj: proj,
color: c,
viewport_px: vp,
stroke_px: b.stroke_mm,
stroke_scale: if b.device_px { 1.0 } else if b.screen_px { meet as f32 } else { mm_px as f32 },
});
for &(dashed, k) in order {
let (color, stroke_mm, scale) = if dashed {
let b = &g.dash_batches[k];
(b.color, b.stroke_mm, mm_px as f32)
} else {
let b = &g.line_batches[k];
(b.color, b.stroke_mm, if b.device_px { 1.0 } else if b.screen_px { meet as f32 } else { mm_px as f32 })
};
let c = if g.greyed { [GREY, GREY, GREY, color[3]] } else { color };
blocks.push(Globals { view_proj: proj, color: c, viewport_px: vp, stroke_px: stroke_mm, stroke_scale: scale });
}
}
@@ -719,19 +780,55 @@ impl ChunkRenderer {
block += 1;
}
}
pass.set_pipeline(&self.line_pipeline);
for g in self.layout.iter().chain(self.highlight.iter()) {
let (Some(p), Some(i)) = (g.line_vtx, g.line_idx) else { continue };
let (Some(pb), Some(ib)) = (self.buffers.get(&p), self.buffers.get(&i)) else {
block += g.line_batches.len() as u32;
continue;
// Striche je Chunk: Linien-Batches (indiziert) und gestrichelte Segmente (je
// Instanz ein Quad aus 6 Vertices) in Maler-Reihenfolge, Pipeline nur bei Wechsel.
let mut current: Option<bool> = None;
for (g, order) in self.layout.iter().chain(self.highlight.iter()).zip(&orders) {
let lines = match (g.line_vtx.and_then(|p| self.buffers.get(&p)), g.line_idx.and_then(|i| self.buffers.get(&i))) {
(Some(pb), Some(ib)) => Some((pb, ib)),
_ => None,
};
pass.set_vertex_buffer(0, pb.slice(..));
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
for b in &g.line_batches {
pass.set_bind_group(0, ubind, &[block * stride as u32]);
pass.draw_indexed(b.start..b.start + b.count, 0, 0..1);
let dash = g.dash_inst.and_then(|d| self.buffers.get(&d));
let mut bound_lines = false;
let mut bound_dash = false;
for &(dashed, k) in order {
let this_block = block;
block += 1;
if dashed {
let Some(db) = dash else { continue };
if current != Some(true) {
pass.set_pipeline(&self.dash_pipeline);
current = Some(true);
bound_lines = false;
}
if !bound_dash {
pass.set_vertex_buffer(0, db.slice(..));
bound_dash = true;
}
let b = &g.dash_batches[k];
// Bereich gegen die Puffergroesse klemmen (fremde Angaben → nie ausserhalb lesen).
let n_inst = (db.size() / DASH_INSTANCE_BYTES) as u32;
let end = b.start.saturating_add(b.count).min(n_inst);
if b.start < end {
pass.set_bind_group(0, ubind, &[this_block * stride as u32]);
pass.draw(0..6, b.start..end);
}
} else {
let Some((pb, ib)) = lines else { continue };
if current != Some(false) {
pass.set_pipeline(&self.line_pipeline);
current = Some(false);
bound_dash = false;
}
if !bound_lines {
pass.set_vertex_buffer(0, pb.slice(..));
pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
bound_lines = true;
}
let b = &g.line_batches[k];
pass.set_bind_group(0, ubind, &[this_block * stride as u32]);
pass.draw_indexed(b.start..b.start + b.count, 0, 0..1);
}
}
}
// Text zuoberst.
@@ -762,6 +859,35 @@ impl ChunkRenderer {
mod tests {
use super::*;
fn lb(start: u32) -> LineBatch {
LineBatch { start, count: 6, color: [0.0; 4], stroke_mm: 0.1, screen_px: false, device_px: false }
}
fn db(line_at: u32) -> DashBatch {
DashBatch { start: 0, count: 1, color: [0.0; 4], stroke_mm: 0.1, line_at }
}
#[test]
fn striche_in_maler_reihenfolge() {
let g = ChunkGeom {
fill_pos: None,
fill_idx: None,
fill_batches: vec![],
line_vtx: Some(1),
line_idx: Some(2),
line_batches: vec![lb(0), lb(6), lb(12)],
dash_inst: Some(3),
dash_batches: vec![db(0), db(6), db(6), db(18)],
origin: [0.0, 0.0],
greyed: false,
};
assert_eq!(stroke_order(&g), vec![(true, 0), (false, 0), (true, 1), (true, 2), (false, 1), (false, 2), (true, 3)]);
// Ohne Strich-Puffer: nur Linien; ohne Linien-Puffer: nur gestrichelte.
let only_lines = ChunkGeom { dash_inst: None, ..g.clone() };
assert_eq!(stroke_order(&only_lines), vec![(false, 0), (false, 1), (false, 2)]);
let only_dash = ChunkGeom { line_idx: None, ..g };
assert_eq!(stroke_order(&only_dash), vec![(true, 0), (true, 1), (true, 2), (true, 3)]);
}
#[test]
fn projection_matches_ts_reference() {
// viewBox 0,0,100,50 auf 200x100 px: keine Aspekt-Korrektur noetig.
+173
View File
@@ -17,6 +17,7 @@
use image::ImageEncoder;
use crate::chunks::{ChunkGeom, ChunkRenderer, DashBatch, FillBatch, LineBatch, View};
use crate::gpu::Renderer;
use crate::types::{Scene, ViewBox};
@@ -156,6 +157,39 @@ impl HeadlessRenderer {
}
}
/// Rendert GPU-Chunks (je Eintrag die flache Ausgabe der Kern-Kompilierung
/// `gpu_compile_flat`, gepackte Linien-Vertices) ueber den Chunk-Renderer, den der
/// native macOS-Pfad benutzt (`chunks.rs`: dieselben Shader und dieselbe
/// Zeichenreihenfolge, nur ohne Metal-Flaeche). `view` in Bildschirm-Einheiten.
/// Fuer Headless-Vergleiche Chunk-Pfad gegen Szenen-Pfad.
pub fn render_chunks_to_image(&self, chunks: &[Vec<u32>], width: u32, height: u32, view: View, paper_scale_n: f64) -> Result<RgbaImage, String> {
let (width, height) = (width.max(1), height.max(1));
let mut cr = ChunkRenderer::new(&self.device, COLOR_FORMAT, 4);
let mut layout = Vec::new();
let mut next_id = 1u32;
for words in chunks {
let (geom, bufs) = chunk_from_flat(words, &mut next_id).ok_or("Chunk-Ausgabe unlesbar")?;
for (id, bytes) in bufs {
cr.upload(&self.device, id, &bytes);
}
layout.push(geom);
}
cr.set_layout(layout);
let texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("headless.chunks.target"),
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: COLOR_FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let tv = texture.create_view(&wgpu::TextureViewDescriptor::default());
cr.render(&self.device, &self.queue, &tv, view, (width, height), paper_scale_n);
Ok(RgbaImage { width, height, pixels: self.read_pixels(&texture, width, height) })
}
/// Texture -> gepolsterter Buffer -> straff gepacktes Pixel-Array (Row-
/// Alignment-Falle, siehe Modul-Kopf).
fn read_pixels(&self, texture: &wgpu::Texture, width: u32, height: u32) -> Vec<u8> {
@@ -235,3 +269,142 @@ fn align_up(value: u32, align: u32) -> u32 {
}
((value + align - 1) / align) * align
}
/// Modell-Ausmass (minX, minY, maxX, maxY, Meter) einer flachen Chunk-Ausgabe (`gpu_compile_flat`).
pub fn chunk_flat_bounds(words: &[u32]) -> Option<[f64; 4]> {
let meta = flat_meta(words)?;
(meta.len() >= 6).then(|| [meta[2], meta[3], meta[4], meta[5]])
}
fn flat_meta(words: &[u32]) -> Option<Vec<f64>> {
let m = *words.first()? as usize;
if words.len() < 2 + 2 * m {
return None;
}
Some((0..m).map(|i| f64::from_bits(words[2 + 2 * i] as u64 | ((words[3 + 2 * i] as u64) << 32))).collect())
}
/// Flache Kern-Ausgabe (Layout s. `core/src/gpu_compile.rs`, gepackt) → Layout-Eintrag + Puffer
/// (ID, Bytes) wie sie die Webview an den nativen Renderer schickt (`nativeGl.ts`).
pub fn chunk_from_flat(words: &[u32], next_id: &mut u32) -> Option<(ChunkGeom, Vec<(u32, Vec<u8>)>)> {
let meta = flat_meta(words)?;
if meta.len() < 12 {
return None;
}
let n = |v: f64| -> Option<usize> { (v >= 0.0 && v.fract() == 0.0).then_some(v as usize) };
let (nfp, nfi, nlv, nli, nf, nl) = (n(meta[6])?, n(meta[7])?, n(meta[8])?, n(meta[9])?, n(meta[10])?, n(meta[11])?);
let mut k = 12;
let rgba = |m: &[f64]| [m[0] as f32, m[1] as f32, m[2] as f32, m[3] as f32];
let mut fill_batches = Vec::new();
for _ in 0..nf {
let b = meta.get(k..k + 6)?;
fill_batches.push(FillBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]) });
k += 6;
}
let mut line_batches = Vec::new();
for _ in 0..nl {
let b = meta.get(k..k + 8)?;
line_batches.push(LineBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]), stroke_mm: b[6] as f32, screen_px: b[7] == 1.0, device_px: false });
k += 8;
}
let (nd, ndb) = (meta.get(k).copied().map(n).unwrap_or(Some(0))?, meta.get(k + 1).copied().map(n).unwrap_or(Some(0))?);
k += 2;
let mut dash_batches = Vec::new();
for _ in 0..ndb {
let b = meta.get(k..k + 8)?;
dash_batches.push(DashBatch { start: b[0] as u32, count: b[1] as u32, color: rgba(&b[2..6]), stroke_mm: b[6] as f32, line_at: b[7] as u32 });
k += 8;
}
let mut off = 2 + 2 * meta.len();
let mut bufs = Vec::new();
let mut take = |len: usize, off: &mut usize| -> Option<Option<u32>> {
let w = words.get(*off..*off + len)?;
*off += len;
if len == 0 {
return Some(None);
}
let id = *next_id;
*next_id += 1;
bufs.push((id, w.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()));
Some(Some(id))
};
let fill_pos = take(nfp, &mut off)?;
let fill_idx = take(nfi, &mut off)?;
let line_vtx = take(nlv, &mut off)?;
let line_idx = take(nli, &mut off)?;
let dash_inst = take(nd * 16, &mut off)?;
let geom = ChunkGeom {
fill_pos,
fill_idx,
fill_batches,
line_vtx,
line_idx,
line_batches,
dash_inst,
dash_batches,
origin: [meta[0], meta[1]],
greyed: false,
};
Some((geom, bufs))
}
#[cfg(test)]
mod tests {
use super::*;
/// Flache Ausgabe wie `gpu_compile_flat` mit EINER gestrichelten Linie (Instanz) von
/// (0,0) nach (L,0) Bildschirm-Einheiten, Muster an/aus = `on`/`off`.
fn dashed_chunk(len: f32, on: f32, off: f32, stroke_mm: f64) -> Vec<u32> {
let mut meta: Vec<f64> = vec![0.0, 0.0, 0.0, 0.0, len as f64 / 90.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
meta.extend_from_slice(&[1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, stroke_mm, 0.0]);
let mut out = vec![meta.len() as u32, 0];
for m in &meta {
let b = m.to_bits();
out.push(b as u32);
out.push((b >> 32) as u32);
}
let inst = [0.0, 0.0, len, 0.0, 0.0, len, on + off, 2.0, on, off, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0f32];
out.extend(inst.iter().map(|v| v.to_bits()));
out
}
/// Der Chunk-Renderer (nativer macOS-Pfad, hier ueber Vulkan/lavapipe) zeichnet Striche
/// und Luecken: entlang der Achse wechseln gedeckte und freie Pixel im Muster-Takt.
#[test]
fn chunk_renderer_zeichnet_striche_und_luecken() {
let r = match HeadlessRenderer::new() {
Ok(r) => r,
Err(e) => {
eprintln!("uebersprungen, kein Headless-Adapter: {e}");
return;
}
};
// 200 Einheiten lang, Muster 20 an / 20 aus; Ansicht 1:1 auf 200x40 px.
let chunk = dashed_chunk(200.0, 20.0, 20.0, 0.05);
let img = r
.render_chunks_to_image(&[chunk], 200, 40, View { x: 0.0, y: -20.0, w: 200.0, h: 40.0 }, 1000.0)
.expect("rendern");
let px = |x: u32| {
let i = ((20 * img.width + x) * 4) as usize;
img.pixels[i] // Rot-Kanal: Linie schwarz -> 0, Hintergrund weiss -> 255
};
// Strich-Mitten (10, 50, 90 …) dunkel, Luecken-Mitten (30, 70, 110 …) hell.
for c in [10u32, 50, 90, 130, 170] {
assert!(px(c) < 80, "Strich bei x={c}: {}", px(c));
}
for c in [30u32, 70, 110, 150] {
assert!(px(c) > 200, "Luecke bei x={c}: {}", px(c));
}
}
#[test]
fn flache_ausgabe_wird_gelesen() {
let mut id = 1;
let (g, bufs) = chunk_from_flat(&dashed_chunk(100.0, 5.0, 5.0, 0.35), &mut id).unwrap();
assert_eq!(g.dash_inst, Some(1));
assert_eq!(g.dash_batches.len(), 1);
assert_eq!(bufs[0].1.len(), 64);
assert!(g.line_vtx.is_none() && g.fill_pos.is_none());
assert!(chunk_from_flat(&[5, 0, 1], &mut id).is_none());
}
}
+1
View File
@@ -165,6 +165,7 @@ function disposeGeometry(gl: BufferGl, g: GpuGeometry): void {
gl.deleteBuffer(g.fill.indexBuffer);
gl.deleteBuffer(g.line.vertexBuffer);
gl.deleteBuffer(g.line.indexBuffer);
if (g.dash) gl.deleteBuffer(g.dash.instanceBuffer);
}
export interface ChunkStats {
+19
View File
@@ -57,6 +57,25 @@ describe('compilePrimitivesToGpu: zusammenhängende Linien-Segmente', () => {
});
});
describe('compilePrimitivesToGpu: Strichmuster (Shader-Instanzen wie der Szenen-Pfad)', () => {
it('gestrichelte Linie wird EINE Strich-Instanz statt durchgezogener Striche', () => {
const uploads: ArrayBufferView[] = [];
const gl = { ...glStub, bufferData: (_t: number, d: ArrayBufferView) => uploads.push(d) } as unknown as WebGL2RenderingContext;
const dashed = { ...seg(0, 0, 2, 0, 'a'), dash: [3, 1] } as Primitive;
const g = compilePrimitivesToGpu(gl, [seg(0, 1, 1, 1, 'b'), dashed], 90);
expect(g.dash?.batches).toEqual([{ startInstance: 0, instanceCount: 1, color: [0, 0, 0, 1], strokeMm: 0.18, lineAt: g.line.batches[0].indexCount }]);
const inst = uploads[uploads.length - 1] as Float32Array;
expect(inst.length).toBe(16);
// Lauflänge des Zugs (Bildschirm-Einheiten) und Muster 3/1 mm × 0.1 m/mm × 90.
expect(inst[5]).toBeCloseTo(180, 4);
expect(Array.from(inst.slice(7, 10)).map((v) => +v.toFixed(4))).toEqual([2, 27, 9]);
});
it('ohne Strichmuster keine Strich-Geometrie', () => {
expect(compilePrimitivesToGpu(glStub, [seg(0, 0, 1, 0, 'a')], 90).dash).toBeUndefined();
});
});
/** Summierte Dreiecksfläche (Betrag) aus Indizes über pts. */
function triArea(pts: Vec2[], idx: number[]): number {
let area = 0;
+18 -1
View File
@@ -12,7 +12,7 @@
import type { Primitive } from '../generatePlan';
import type { Vec2 } from '../../model/types';
import type { BufferGl, GpuGeometry, Rgba } from './glPlanTypes';
import type { BufferGl, DashBatch, GpuGeometry, Rgba } from './glPlanTypes';
import { encodePlanBuf, type DecodedPlanBuf } from '../planBuf';
import { core } from '../../engine/coreWasm';
@@ -94,6 +94,20 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry {
screenPx: meta[k + 7] === 1,
});
}
// Strich-Instanzen (hinter den Linien-Batches; ältere Ausgaben ohne diesen Teil → keine).
const nDash = k < m ? meta[k] : 0;
const nDashBatches = k + 1 < m ? meta[k + 1] : 0;
k += 2;
const dashBatches: DashBatch[] = [];
for (let i = 0; i < nDashBatches; i++, k += 8) {
dashBatches.push({
startInstance: meta[k],
instanceCount: meta[k + 1],
color: [meta[k + 2], meta[k + 3], meta[k + 4], meta[k + 5]] as Rgba,
strokeMm: meta[k + 6],
lineAt: meta[k + 7],
});
}
let off = out.byteOffset + 8 + m * 8;
const fillPos = new Float32Array(out.buffer, off, nFillPos);
off += nFillPos * 4;
@@ -103,6 +117,8 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry {
const lineVerts = new Uint32Array(out.buffer, off, nLineVerts);
off += nLineVerts * 4;
const lineIdx = new Uint32Array(out.buffer, off, nLineIdx);
off += nLineIdx * 4;
const dashInst = new Float32Array(out.buffer, off, nDash * 16);
const upload = (target: number, data: ArrayBufferView & { length: number }): WebGLBuffer | null => {
if (!data.length) return null;
@@ -123,6 +139,7 @@ function uploadCompiled(gl: BufferGl, out: Uint32Array): GpuGeometry {
indexBuffer: upload(gl.ELEMENT_ARRAY_BUFFER, lineIdx),
batches: lineBatches,
},
...(nDash > 0 ? { dash: { instanceBuffer: upload(gl.ARRAY_BUFFER, dashInst), batches: dashBatches } } : {}),
origin: { x: originX, y: originY },
bounds: {
minX: isFinite(minX) ? minX : 0,
+22
View File
@@ -99,10 +99,32 @@ export interface GpuGeometry {
indexBuffer: WebGLBuffer | null;
batches: LineBatch[];
};
/**
* Gestrichelte Striche: je Segment EINE Instanz (16 × f32: ax, ay, bx, by, s0, runLen, total,
* count, dash0..7 in Bildschirm-Einheiten relativ zu `origin`); Striche/Lücken setzt der
* Fragment-Shader (`DASH_LINE_WGSL` in render2d). Fehlt bei Geometrie ohne Strichmuster.
*/
dash?: {
instanceBuffer: WebGLBuffer | null;
batches: DashBatch[];
};
/** Modell-Bounds (Meter) für Debug/Einpassen; nicht render-kritisch. */
bounds: { minX: number; minY: number; maxX: number; maxY: number };
}
/** Ein Strich-Batch: Instanz-Bereich mit Farbe + Papier-Strichbreite (mm). */
export interface DashBatch {
startInstance: number;
instanceCount: number;
color: Rgba;
strokeMm: number;
/**
* Maler-Reihenfolge: Anzahl Linien-Indizes vor diesem Batch — gezeichnet vor dem ersten
* Linien-Batch mit `startIndex >= lineAt` (kein Linien-Batch überspannt diese Stelle).
*/
lineAt: number;
}
/** Rechteckiger Ausschnitt in Bildschirm-Einheiten (viewBox). */
export interface ViewBox {
x: number;
+11
View File
@@ -24,6 +24,9 @@ export interface NativeChunkLayout {
line_vtx: number | null;
line_idx: number | null;
line_batches: { start: number; count: number; color: number[]; stroke_mm: number; screen_px: boolean; device_px?: boolean }[];
/** Strich-Instanzen (gestrichelte Segmente, `DASH_LINE_WGSL`), s. `GpuGeometry.dash`. */
dash_inst?: number | null;
dash_batches?: { start: number; count: number; color: number[]; stroke_mm: number; line_at: number }[];
origin: [number, number];
greyed: boolean;
}
@@ -193,6 +196,14 @@ export class NativeGl implements BufferGl {
stroke_mm: b.strokeMm,
screen_px: !!b.screenPx,
})),
dash_inst: id(g.dash?.instanceBuffer ?? null),
dash_batches: (g.dash?.batches ?? []).map((b) => ({
start: b.startInstance,
count: b.instanceCount,
color: b.color,
stroke_mm: b.strokeMm,
line_at: b.lineAt,
})),
origin: [g.origin?.x ?? 0, g.origin?.y ?? 0] as [number, number],
greyed: !!g.greyed,
};
+1
View File
@@ -237,6 +237,7 @@ export function useNativePlanRenderer(
gl.deleteBuffer(old.fill.indexBuffer);
gl.deleteBuffer(old.line.vertexBuffer);
gl.deleteBuffer(old.line.indexBuffer);
if (old.dash) gl.deleteBuffer(old.dash.instanceBuffer);
highlightGeom.current = null;
}
if (prims.length) {