Skip to main content

brep_render/thumbnail/
line_art.rs

1//! The Line art step picture: a flat technical illustration, as assembly
2//! instructions draw a step (the instructions documents' default style).
3//!
4//! * a light grey ground ([`BACKGROUND`]);
5//! * the parts earlier steps placed: flat white, thin grey visible edges and
6//!   a darker grey outline;
7//! * the parts the step adds: flat blue ([`ADDING_FILL`]) under a heavy black
8//!   outline and thin black visible edges, so the new part pops;
9//! * no lighting at all;
10//! * black insertion arrows over everything.
11//!
12//! The outline is every part's silhouette as it shows: a sample whose
13//! neighbour is another part, the ground, or the same part much further
14//! away (a fold of the part over itself) is on an outline, drawn by the part
15//! in front. It is found in the raster (a part-id buffer beside the depth
16//! buffer), so a cylinder's outline is drawn although no B-rep edge runs
17//! there. Edges are depth-tested against the faces, so hidden lines are
18//! never drawn.
19
20use super::{dot, f64s, normalize, Basis, Body, Projection, SUPERSAMPLE};
21
22/// The ground (sRGB 0..1): `#ececec`, the reference frames' background.
23pub const BACKGROUND: [f32; 3] = [0.925, 0.925, 0.925];
24/// A placed part's fill: white.
25pub const PLACED_FILL: [f32; 3] = [1.0, 1.0, 1.0];
26/// A placed part's visible edges: light grey.
27pub const PLACED_EDGE: [f32; 3] = [0.55, 0.55, 0.55];
28/// A placed part's outline: dark grey.
29pub const PLACED_OUTLINE: [f32; 3] = [0.30, 0.30, 0.30];
30/// An added part's fill: `#9db8f5`, sampled from the reference frames.
31pub const ADDING_FILL: [f32; 3] = [0.616, 0.722, 0.961];
32/// An added part's visible edges and outline, and the arrows: black.
33pub const INK: [f32; 3] = [0.0, 0.0, 0.0];
34
35/// Line widths in output pixels at an 800-pixel picture (the reference
36/// frames' proportions); a picture of another size scales them by the
37/// square root of its size, so a small picture keeps readable lines.
38const REFERENCE_PX: f64 = 800.0;
39const EDGE_PX: f64 = 1.1;
40const PLACED_OUTLINE_PX: f64 = 2.0;
41const ADDING_OUTLINE_PX: f64 = 3.2;
42/// The arrow: a solid shaft and a filled triangular head at the seat
43/// (the reference's insertion frame at 900 px: a ~3 px line, a head ~22 px
44/// long and ~16 px wide).
45pub const ARROW_SHAFT_PX: f64 = 2.6;
46pub const ARROW_HEAD_LENGTH_PX: f64 = 20.0;
47pub const ARROW_HEAD_WIDTH_PX: f64 = 14.0;
48
49/// The fraction of the picture the step (parts and arrows) fills.
50const FILL: f64 = 0.86;
51
52/// What one step picture draws.
53#[derive(Debug, Clone, Default)]
54pub struct LineArt {
55    /// The parts earlier steps placed, each its own outline.
56    pub placed: Vec<Body>,
57    /// The parts the step adds.
58    pub adding: Vec<Body>,
59    /// Insertion arrows in world space: (tail, tip).
60    pub arrows: Vec<([f64; 3], [f64; 3])>,
61}
62
63impl LineArt {
64    fn is_empty(&self) -> bool {
65        self.placed.iter().chain(&self.adding).all(|b| b.indices.is_empty())
66    }
67}
68
69/// The picture as a `size`-pixel square PNG seen along `basis`, fit to the
70/// parts and the arrows. `None` when there is nothing to draw.
71pub fn render_png(art: &LineArt, size: u32, basis: Basis) -> Option<Vec<u8>> {
72    let rgba = render_rgba(art, size, basis)?;
73    super::encode_png(&rgba, size, size).ok()
74}
75
76/// [`render_png`]'s pixels: `size`² RGBA, row-major, opaque.
77pub fn render_rgba(art: &LineArt, size: u32, basis: Basis) -> Option<Vec<u8>> {
78    if art.is_empty() || size == 0 {
79        return None;
80    }
81    let n = (size * SUPERSAMPLE) as usize;
82    let mut extra: Vec<[f64; 3]> = Vec::new();
83    for (tail, tip) in &art.arrows {
84        extra.push(*tail);
85        extra.push(*tip);
86    }
87    let bodies: Vec<(&Body, bool)> = art.placed.iter().map(|b| (b, false)).chain(art.adding.iter().map(|b| (b, true))).collect();
88    let projection = Projection::fit_points(
89        bodies.iter().flat_map(|(b, _)| b.indices.iter().map(|&i| f64s(b.positions[i as usize]))).chain(extra.iter().copied()),
90        n as u32,
91        basis,
92        FILL,
93    );
94    let scale = (size as f64 / REFERENCE_PX).sqrt().clamp(0.5, 2.0);
95    // In samples, never thinner than one output pixel.
96    let px = |output_px: f64| (output_px * scale).max(1.0) * SUPERSAMPLE as f64;
97
98    // Faces: depth and the part's id (0 is the ground).
99    let mut depth = vec![f32::INFINITY; n * n];
100    let mut id = vec![0u32; n * n];
101    for (k, (body, _)) in bodies.iter().enumerate() {
102        let screen: Vec<[f64; 3]> = body.positions.iter().map(|&p| projection.project(f64s(p))).collect();
103        for tri in body.indices.chunks_exact(3) {
104            let p = [screen[tri[0] as usize], screen[tri[1] as usize], screen[tri[2] as usize]];
105            fill_id(&mut depth, &mut id, n, p, k as u32 + 1);
106        }
107    }
108    let adding = |part: u32| part > 0 && bodies[part as usize - 1].1;
109    let mut color: Vec<[f32; 3]> = id
110        .iter()
111        .map(|&part| if part == 0 { BACKGROUND } else if adding(part) { ADDING_FILL } else { PLACED_FILL })
112        .collect();
113
114    // Visible edges, depth-tested with a bias so an edge on its own face wins.
115    let bias = 2.5f32;
116    let edge_radius = px(EDGE_PX) * 0.5;
117    for (body, lit) in &bodies {
118        let ink = if *lit { INK } else { PLACED_EDGE };
119        for line in &body.edges {
120            for seg in line.windows(2) {
121                let (p, q) = (projection.project(f64s(seg[0])), projection.project(f64s(seg[1])));
122                stroke(&mut color, n, p, q, edge_radius, ink, Some((&depth, bias)));
123            }
124        }
125    }
126
127    // Outlines: a sample on a part whose neighbour is the ground, another
128    // part behind it, or the same part far behind it. The nearer side draws
129    // it; the added parts' outlines go last, over the placed parts'.
130    let span = depth.iter().filter(|z| z.is_finite()).fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), &z| (lo.min(z), hi.max(z)));
131    let fold = ((span.1 - span.0).max(1e-6)) * 0.04;
132    let on_outline = |i: usize, j: usize| -> bool {
133        let (a, b) = (id[i], id[j]);
134        a != 0 && (b == 0 || (a != b && depth[i] <= depth[j]) || (a == b && depth[j] - depth[i] > fold))
135    };
136    let mut rims: [Vec<usize>; 2] = [Vec::new(), Vec::new()];
137    for y in 0..n {
138        for x in 0..n {
139            let i = y * n + x;
140            if id[i] == 0 {
141                continue;
142            }
143            let edge = (x + 1 < n && on_outline(i, i + 1))
144                || (x > 0 && on_outline(i, i - 1))
145                || (y + 1 < n && on_outline(i, i + n))
146                || (y > 0 && on_outline(i, i - n))
147                || x == 0
148                || y == 0
149                || x + 1 == n
150                || y + 1 == n;
151            if edge {
152                rims[adding(id[i]) as usize].push(i);
153            }
154        }
155    }
156    for (lit, rim) in rims.iter().enumerate() {
157        let (radius, ink) = if lit == 1 { (px(ADDING_OUTLINE_PX) * 0.5, INK) } else { (px(PLACED_OUTLINE_PX) * 0.5, PLACED_OUTLINE) };
158        let stamp = disc(radius);
159        for &i in rim {
160            let (x, y) = ((i % n) as i64, (i / n) as i64);
161            for &(dx, dy) in &stamp {
162                let (sx, sy) = (x + dx, y + dy);
163                if sx >= 0 && sy >= 0 && (sx as usize) < n && (sy as usize) < n {
164                    color[sy as usize * n + sx as usize] = ink;
165                }
166            }
167        }
168    }
169
170    // Arrows over everything.
171    for (tail, tip) in &art.arrows {
172        let (a, b) = (projection.project(*tail), projection.project(*tip));
173        arrow(&mut color, n, a, b, px(ARROW_SHAFT_PX) * 0.5, px(ARROW_HEAD_LENGTH_PX), px(ARROW_HEAD_WIDTH_PX) * 0.5);
174    }
175
176    // Box-filter down to the output size.
177    let s = SUPERSAMPLE as usize;
178    let out_w = size as usize;
179    let mut out = vec![0u8; out_w * out_w * 4];
180    let inv = 1.0 / (s * s) as f32;
181    for y in 0..out_w {
182        for x in 0..out_w {
183            let mut acc = [0f32; 3];
184            for dy in 0..s {
185                for dx in 0..s {
186                    let c = color[(y * s + dy) * n + x * s + dx];
187                    for k in 0..3 {
188                        acc[k] += c[k];
189                    }
190                }
191            }
192            let o = (y * out_w + x) * 4;
193            for k in 0..3 {
194                out[o + k] = ((acc[k] * inv).clamp(0.0, 1.0) * 255.0).round() as u8;
195            }
196            out[o + 3] = 255;
197        }
198    }
199    Some(out)
200}
201
202/// The offsets of a filled disc of `radius` samples (at least the centre).
203fn disc(radius: f64) -> Vec<(i64, i64)> {
204    let r = radius.max(0.5);
205    let reach = r.ceil() as i64;
206    let mut out = Vec::new();
207    for dy in -reach..=reach {
208        for dx in -reach..=reach {
209            if ((dx * dx + dy * dy) as f64) <= r * r + 0.25 {
210                out.push((dx, dy));
211            }
212        }
213    }
214    out
215}
216
217/// Fill one screen triangle's depth and part id, depth-tested.
218fn fill_id(depth: &mut [f32], id: &mut [u32], w: usize, p: [[f64; 3]; 3], part: u32) {
219    let area = (p[1][0] - p[0][0]) * (p[2][1] - p[0][1]) - (p[2][0] - p[0][0]) * (p[1][1] - p[0][1]);
220    if area.abs() < 1e-12 {
221        return;
222    }
223    let min_x = p.iter().map(|q| q[0]).fold(f64::INFINITY, f64::min).floor().max(0.0) as usize;
224    let max_x = (p.iter().map(|q| q[0]).fold(f64::NEG_INFINITY, f64::max).ceil() as i64).min(w as i64 - 1);
225    let min_y = p.iter().map(|q| q[1]).fold(f64::INFINITY, f64::min).floor().max(0.0) as usize;
226    let max_y = (p.iter().map(|q| q[1]).fold(f64::NEG_INFINITY, f64::max).ceil() as i64).min(w as i64 - 1);
227    if max_x < 0 || max_y < 0 {
228        return;
229    }
230    let inv_area = 1.0 / area;
231    for y in min_y..=max_y as usize {
232        let cy = y as f64 + 0.5;
233        for x in min_x..=max_x as usize {
234            let cx = x as f64 + 0.5;
235            let w0 = ((p[1][0] - cx) * (p[2][1] - cy) - (p[2][0] - cx) * (p[1][1] - cy)) * inv_area;
236            let w1 = ((p[2][0] - cx) * (p[0][1] - cy) - (p[0][0] - cx) * (p[2][1] - cy)) * inv_area;
237            let w2 = 1.0 - w0 - w1;
238            if w0 < 0.0 || w1 < 0.0 || w2 < 0.0 {
239                continue;
240            }
241            let z = (w0 * p[0][2] + w1 * p[1][2] + w2 * p[2][2]) as f32;
242            let i = y * w + x;
243            if z < depth[i] {
244                depth[i] = z;
245                id[i] = part;
246            }
247        }
248    }
249}
250
251/// A round-capped stroke `radius` samples wide from `p` to `q`; with
252/// `depth`, only where the stroke is not behind a face (by more than the
253/// bias).
254fn stroke(color: &mut [[f32; 3]], w: usize, p: [f64; 3], q: [f64; 3], radius: f64, ink: [f32; 3], depth: Option<(&[f32], f32)>) {
255    let steps = ((q[0] - p[0]).abs().max((q[1] - p[1]).abs()).ceil() as usize).max(1);
256    let stamp = disc(radius);
257    for i in 0..=steps {
258        let t = i as f64 / steps as f64;
259        let (x, y, z) = (p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, (p[2] + (q[2] - p[2]) * t) as f32);
260        let (cx, cy) = (x.floor() as i64, y.floor() as i64);
261        if let Some((depth, bias)) = depth {
262            if cx < 0 || cy < 0 || cx >= w as i64 || cy >= w as i64 {
263                continue;
264            }
265            if z - bias > depth[cy as usize * w + cx as usize] {
266                continue;
267            }
268        }
269        for &(dx, dy) in &stamp {
270            let (sx, sy) = (cx + dx, cy + dy);
271            if sx >= 0 && sy >= 0 && sx < w as i64 && sy < w as i64 {
272                color[sy as usize * w + sx as usize] = ink;
273            }
274        }
275    }
276}
277
278/// A black arrow from `tail` to `tip` (screen samples): a shaft and a filled
279/// head whose point is at `tip`.
280fn arrow(color: &mut [[f32; 3]], w: usize, tail: [f64; 3], tip: [f64; 3], shaft: f64, head_length: f64, head_half_width: f64) {
281    let (dx, dy) = (tip[0] - tail[0], tip[1] - tail[1]);
282    let length = (dx * dx + dy * dy).sqrt();
283    if length < 1.0 {
284        return;
285    }
286    let (ux, uy) = (dx / length, dy / length);
287    let head = head_length.min(length * 0.6);
288    let base = [tip[0] - ux * head, tip[1] - uy * head, tip[2]];
289    stroke(color, w, tail, base, shaft, INK, None);
290    let (nx, ny) = (-uy * head_half_width, ux * head_half_width);
291    let corners = [[tip[0], tip[1]], [base[0] + nx, base[1] + ny], [base[0] - nx, base[1] - ny]];
292    let min_x = corners.iter().map(|c| c[0]).fold(f64::INFINITY, f64::min).floor().max(0.0) as i64;
293    let max_x = (corners.iter().map(|c| c[0]).fold(f64::NEG_INFINITY, f64::max).ceil() as i64).min(w as i64 - 1);
294    let min_y = corners.iter().map(|c| c[1]).fold(f64::INFINITY, f64::min).floor().max(0.0) as i64;
295    let max_y = (corners.iter().map(|c| c[1]).fold(f64::NEG_INFINITY, f64::max).ceil() as i64).min(w as i64 - 1);
296    let side = |a: [f64; 2], b: [f64; 2], p: [f64; 2]| (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
297    let orientation = side(corners[0], corners[1], corners[2]).signum();
298    for y in min_y..=max_y {
299        for x in min_x..=max_x {
300            let p = [x as f64 + 0.5, y as f64 + 0.5];
301            let inside = (0..3).all(|k| side(corners[k], corners[(k + 1) % 3], p) * orientation >= 0.0);
302            if inside {
303                color[y as usize * w + x as usize] = INK;
304            }
305        }
306    }
307}
308
309/// A still's insertion arrow, in world space, for a part whose seated bounds
310/// are `lo..hi` and whose motion starts `start_offset` away from home: from
311/// its trailing face where the motion starts to just short of its trailing
312/// face at home, so the arrow points at the seated part from where it came.
313/// `None` for no motion.
314pub fn still_arrow(lo: [f64; 3], hi: [f64; 3], start_offset: [f64; 3]) -> Option<([f64; 3], [f64; 3])> {
315    let length = dot(start_offset, start_offset).sqrt();
316    if !(length > 1e-12) {
317        return None;
318    }
319    // The travel direction, start toward home.
320    let d = normalize([-start_offset[0], -start_offset[1], -start_offset[2]]);
321    let center = [(lo[0] + hi[0]) * 0.5, (lo[1] + hi[1]) * 0.5, (lo[2] + hi[2]) * 0.5];
322    let half = [(hi[0] - lo[0]) * 0.5, (hi[1] - lo[1]) * 0.5, (hi[2] - lo[2]) * 0.5];
323    // The bounds' half extent along d.
324    let h = half[0] * d[0].abs() + half[1] * d[1].abs() + half[2] * d[2].abs();
325    let trailing = [center[0] - d[0] * h, center[1] - d[1] * h, center[2] - d[2] * h];
326    let tail = [trailing[0] + start_offset[0], trailing[1] + start_offset[1], trailing[2] + start_offset[2]];
327    // Stop a little short of the part, so the head reads.
328    let gap = (length * 0.06).min(h * 0.5);
329    let tip = [trailing[0] - d[0] * gap, trailing[1] - d[1] * gap, trailing[2] - d[2] * gap];
330    (dot([tip[0] - tail[0], tip[1] - tail[1], tip[2] - tail[2]], d) > 0.0).then_some((tail, tip))
331}
332