diff --git a/crates/io/tests/it/block_expansion.rs b/crates/io/tests/it/block_expansion.rs index 60b064391..7aac5d7db 100644 --- a/crates/io/tests/it/block_expansion.rs +++ b/crates/io/tests/it/block_expansion.rs @@ -41,6 +41,283 @@ fn minsert(cols: u32, rows: u32) -> String { ) } +/// A linear dimension drawn by block `block`, its dimension line at height `y`. +fn dimension(block: &str, y: usize) -> String { + format!("0\nDIMENSION\n2\n{block}\n3\nStandard\n10\n100\n20\n{}\n11\n50\n21\n{}\n70\n0\n13\n0\n23\n{y}\n14\n100\n24\n{y}\n", y + 5, y + 5) +} + +const LINE: &str = "0\nLINE\n10\n0\n20\n0\n11\n1\n21\n1\n"; + +/// What dimension block `*D1` holds on its way back to itself. +#[derive(Clone, Copy, Debug)] +enum Via { + /// Dimensions drawn by `*D1`. + Nothing, + /// References to block `B`, which holds a dimension drawn by `*D1`. + Reference, + /// Dimensions drawn by `*D2`, which holds a dimension drawn by `*D1`. + Dimension, +} + +/// Dimension block `*D1` holds a line and `refs` dimensions or references that lead back to `*D1` +/// (`via`); the block on the way holds a line too. Model space holds one dimension drawn by `*D1`, +/// and a reference to `B` when there is one, so the loop is also entered from `B`. With `closed` +/// false, the first dimension inside a block on the way is drawn by `*D9`, a block the file lacks, +/// so nothing leads back. +fn dimension_loop(refs: usize, via: Via, closed: bool) -> String { + let back = if closed { "*D1" } else { "*D9" }; + let mut s = String::from("0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\n*D1\n70\n1\n10\n0\n20\n0\n"); + for k in 0..refs { + s += &match via { + Via::Nothing => dimension(back, k * 10), + Via::Reference => format!("0\nINSERT\n2\nB\n10\n{k}\n20\n0\n"), + Via::Dimension => dimension(if closed { "*D2" } else { "*D9" }, k * 10), + }; + } + s += LINE; + s += "0\nENDBLK\n"; + match via { + Via::Nothing => {} + Via::Reference => s += &format!("0\nBLOCK\n2\nB\n70\n0\n10\n0\n20\n0\n{}{LINE}0\nENDBLK\n", dimension(back, 0)), + Via::Dimension => s += &format!("0\nBLOCK\n2\n*D2\n70\n1\n10\n0\n20\n0\n{}{LINE}0\nENDBLK\n", dimension("*D1", 0)), + } + s += "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n"; + s += &dimension("*D1", 0); + if matches!(via, Via::Reference) { + s += "0\nINSERT\n2\nB\n10\n200\n20\n0\n"; + } + s + "0\nENDSEC\n0\nEOF\n" +} + +/// Dimension blocks `*D1`..`*Dn` each hold a line and a reference to block `B`, which holds a +/// dimension drawn by each of them; model space holds a dimension drawn by `*D1`. Every ordering +/// of the blocks is a way round the loop. +fn loop_of_blocks(n: usize) -> String { + let mut s = String::from("0\nSECTION\n2\nBLOCKS\n"); + for i in 1..=n { + s += &format!("0\nBLOCK\n2\n*D{i}\n70\n1\n10\n0\n20\n0\n0\nINSERT\n2\nB\n10\n0\n20\n0\n{LINE}0\nENDBLK\n"); + } + s += "0\nBLOCK\n2\nB\n70\n0\n10\n0\n20\n0\n"; + for i in 1..=n { + s += &dimension(&format!("*D{i}"), i * 10); + } + s + "0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n" + &dimension("*D1", 0) + "0\nENDSEC\n0\nEOF\n" +} + +/// Dimension blocks `*D1`..`*Dn` in a ring: each holds a line and three dimensions drawn by the +/// next, the last by `*D1`. Model space holds a dimension drawn by `*D1`. +fn ring_of_blocks(n: usize) -> String { + let mut s = String::from("0\nSECTION\n2\nBLOCKS\n"); + for i in 1..=n { + let next = format!("*D{}", i % n + 1); + s += &format!("0\nBLOCK\n2\n*D{i}\n70\n1\n10\n0\n20\n0\n{LINE}"); + for k in 0..3 { + s += &dimension(&next, k * 10); + } + s += "0\nENDBLK\n"; + } + s + "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n" + &dimension("*D1", 0) + "0\nENDSEC\n0\nEOF\n" +} + +/// Dimension blocks nested without a cycle. `*D3` holds the only line, from (0, 0) to (1, 1); +/// `*D2` holds a dimension drawn by `*D3`; `*D1` holds two dimensions drawn by `*D2` and a +/// reference to block `B`, which holds a dimension drawn by `*D2`. Model space holds a dimension +/// drawn by `*D1` and two references to `B`. +fn nested_dimensions() -> String { + let block = |name: &str, body: &str| format!("0\nBLOCK\n2\n{name}\n70\n{}\n10\n0\n20\n0\n{body}0\nENDBLK\n", u8::from(name.starts_with('*'))); + let mut s = String::from("0\nSECTION\n2\nBLOCKS\n"); + s += &block("*D3", "0\nLINE\n10\n0\n20\n0\n11\n1\n21\n1\n"); + s += &block("*D2", &dimension("*D3", 0)); + s += &block("B", &dimension("*D2", 0)); + s += &block("*D1", &(dimension("*D2", 0) + &dimension("*D2", 10) + "0\nINSERT\n2\nB\n10\n5\n20\n0\n")); + s + "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n" + + &dimension("*D1", 0) + + "0\nINSERT\n2\nB\n10\n20\n20\n0\n0\nINSERT\n2\nB\n10\n40\n20\n0\n0\nENDSEC\n0\nEOF\n" +} + +/// A dimension inside a block whose own block leads back to that block (the same block, or +/// through a reference or another dimension block) is drawn as one whose block is missing: from +/// its definition points. It used to draw the block again at every level down to +/// `MAX_BLOCK_DEPTH` (#1923). +#[test] +fn a_dimension_whose_block_leads_back_draws_as_one_whose_block_is_missing() { + for via in [Via::Nothing, Via::Reference, Via::Dimension] { + let closed = build(&read(&dimension_loop(1, via, true)), &Space::Model, &Options::default()); + let open = build(&read(&dimension_loop(1, via, false)), &Space::Model, &Options::default()); + assert!(!open.prims.is_empty()); + assert_eq!((closed.prims.len(), &closed.verts), (open.prims.len(), &open.verts), "via {via:?}"); + } +} + +/// Many dimensions that lead back to their block (directly, or through as many references or +/// dimensions), dimension blocks that lead to each other, or a long ring of them, drew the blocks +/// again at every level: up to 300^16 times, or once per ordering of the blocks, until the +/// expansion budget ran out and the rest was left out. Now nothing goes round a loop, so the +/// drawing is whole. A block of 300 references and a ring of 20 blocks are more than the search +/// near a dimension's block looks at, so the whole block graph answers for them. Their extents use +/// the shared block cache (#1850) and stay finite. +#[test] +fn dimensions_on_block_loops_draw_whole() { + let files = [Via::Nothing, Via::Reference, Via::Dimension].map(|via| dimension_loop(300, via, true)); + for (i, text) in files.iter().chain([&loop_of_blocks(10), &ring_of_blocks(20)]).enumerate() { + let d = read(text); + let ext = d.extents(&Space::Model); + assert!(!ext.is_empty() && ext.min.is_finite() && ext.max.is_finite(), "{ext:?}"); + let list = build(&d, &Space::Model, &Options::default()); + assert!(!list.prims.is_empty() && !list.truncated, "file {i}: {} expanded", list.expanded); + } +} + +/// A loop can also pass through a multileader's block or a proxy's graphics, which are drawn as +/// block contents: `*D1` holds one of them leading to block `K`, which holds a dimension drawn by +/// `*D1` (or by a block the file lacks, for comparison). The proxy's graphics also hold such a +/// dimension themselves: they are drawn as part of `*D1`. +#[test] +fn a_loop_through_a_multileader_or_proxy_graphics_is_cut_too() { + let line = |h: u64| Entity::new(Handle(h), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) })); + let dim = |h: u64, block: &str| { + Entity::new( + Handle(h), + EntityKind::Dimension(cadcraft_doc::Dimension { + kind: cadcraft_doc::DimKind::Linear { rotation: 0.0 }, + defpt: Vec3::new(100.0, 5.0, 0.0), + text_mid: Vec3::new(50.0, 5.0, 0.0), + p13: Vec3::ZERO, + p14: Vec3::new(100.0, 0.0, 0.0), + p15: Vec3::ZERO, + p16: Vec3::ZERO, + text: String::new(), + style: "Standard".into(), + measurement: 100.0, + text_rotation: 0.0, + user_text_pos: false, + block: Some(block.into()), + overrides: Default::default(), + assoc: Vec::new(), + marks: Default::default(), + insertion_point: Vec3::ZERO, + }), + ) + }; + let to_k = Insert { + block: "K".into(), + insert: Vec3::ZERO, + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }; + for through_proxy in [false, true] { + let drawing = |back: &str| { + let via = if through_proxy { + EntityKind::Unknown(cadcraft_doc::Unknown { + dxf_type: "ACAD_PROXY_ENTITY".into(), + tags: Vec::new(), + graphics: vec![Entity::new(Handle(0x300), EntityKind::Insert(to_k.clone())), dim(0x301, back)], + }) + } else { + EntityKind::MLeader(cadcraft_doc::MLeader { + leaders: vec![vec![Vec3::new(-5.0, 0.0, 0.0)]], + landing: Vec3::ZERO, + dogleg: 1.0, + text: None, + style: "Standard".into(), + arrow_size: 1.0, + spline: false, + block: Some(to_k.clone()), + }) + }; + let mut d = Drawing::new_imperial(); + let mut d1 = Block::new("*D1"); + d1.entities.push(line(0x100)); + d1.entities.push(Entity::new(Handle(0x101), via)); + let mut k = Block::new("K"); + k.entities.push(line(0x200)); + k.entities.push(dim(0x201, back)); + d.blocks.insert("*D1".into(), Arc::new(d1)); + d.blocks.insert("K".into(), Arc::new(k)); + let EntityKind::Dimension(top) = dim(0, "*D1").kind else { unreachable!() }; + d.add(&Space::Model, Common::default(), EntityKind::Dimension(top)).unwrap(); + build(&d, &Space::Model, &Options::default()) + }; + let (closed, open) = (drawing("*D1"), drawing("*D9")); + assert!(!open.prims.is_empty()); + assert_eq!((closed.prims.len(), &closed.verts), (open.prims.len(), &open.verts), "through a proxy: {through_proxy}"); + } +} + +/// Dimension blocks `*E1`..`*En` in a chain: each holds `lines` lines and a dimension drawn by the +/// next; the last holds only lines. Model space holds a dimension drawn by `*E1`. +fn chain_of_blocks(n: usize, lines: usize) -> String { + let mut s = String::from( + "0 +SECTION +2 +BLOCKS +", + ); + for i in 1..=n { + s += &format!( + "0 +BLOCK +2 +*E{i} +70 +1 +10 +0 +20 +0 +{}", + LINE.repeat(lines) + ); + if i < n { + s += &dimension(&format!("*E{}", i + 1), 0); + } + s += "0 +ENDBLK +"; + } + s + "0 +ENDSEC +0 +SECTION +2 +ENTITIES +" + &dimension("*E1", 0) + + "0 +ENDSEC +0 +EOF +" +} + +/// Dimension blocks nested without a cycle are still drawn from their blocks, on every path: two +/// dimensions deep, by sibling dimensions, and through references to a block holding one. A chain +/// of blocks with more objects than the search near a dimension's block looks at is settled by +/// the whole block graph, which finds no loop either. +#[test] +fn nested_dimension_blocks_without_a_cycle_draw_on_every_path() { + let only_lines = |list: &cadcraft_render::DisplayList| { + list.prims.iter().all(|p| { + let v = &list.verts[p.start as usize..(p.start + p.len) as usize]; + matches!(v, [a, b] if *b - *a == Vec2::new(1.0, 1.0)) + }) + }; + let list = build(&read(&nested_dimensions()), &Space::Model, &Options::default()); + // `*D3`'s line, through `*D1` (two dimensions of `*D2`, and `B`) and the two `B` in model + // space; nothing else is drawn, so no dimension fell back to its definition points. + assert_eq!(list.prims.len(), 2 + 1 + 2); + assert!(only_lines(&list)); + let list = build(&read(&chain_of_blocks(5, 100)), &Space::Model, &Options::default()); + assert_eq!(list.prims.len(), 5 * 100); + assert!(only_lines(&list)); +} + #[test] fn block_expansion_bombs_are_bounded() { for text in [self_referencing(4), self_referencing(12), fan_out(), minsert(10_000, 10_000)] { diff --git a/crates/render/src/blocks.rs b/crates/render/src/blocks.rs index 5fb3d6d9b..74a56fde7 100644 --- a/crates/render/src/blocks.rs +++ b/crates/render/src/blocks.rs @@ -41,6 +41,9 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> { block_pstyle: ctx.block_pstyle, // The reference's own, set by the caller (`Builder::transparency` while it draws). block_transparency: ctx.block_transparency, + // Proxy graphics are drawn as part of the block they are in; a block reference or a + // dimension sets its own block instead. + block: ctx.block, } } @@ -82,7 +85,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc: } let off = Vec2::new(ins.col_spacing * f64::from(c), ins.row_spacing * f64::from(r)).rotate(ins.rotation); let m = Mat3::translate(off).then_before(ins.transform(blk.base.xy())); - let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, m) }; + let sub = Ctx { block: Some(blk), block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, m) }; // XCLIP: the copy is drawn on its own, then cut to the boundary. let clip = xclip_region(ins, &sub.xf); let mut part = clip.as_ref().map(|_| b.part()); diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 25c1cae0a..0d0457b13 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -366,13 +366,17 @@ fn draw_dimension( own: u8, ) { let (lt, ltscale) = stroke; + // A dimension inside a block whose own block leads back to that block (it is the block, or + // they lie on a loop of references, dimensions and multileaders) is drawn from its definition + // points, as one whose block is missing is (see `loops`, #1923). if let Some(blk) = dm.block.as_ref().and_then(|n| ctx.d.block(n)) && ctx.depth < cadcraft_doc::MAX_BLOCK_DEPTH + && !ctx.block.is_some_and(|outer| b.leads_back(ctx.d, outer, blk)) { // DXF group 12: a moved dimension keeps its `*D` block where it was and the offset in // the insertion point, so the block draws translated by it (#2634). let off = dm.insertion_point.xy(); - let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::translate(off)) }; + let sub = Ctx { block: Some(blk), block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::translate(off)) }; // DIMTFILL: the block's MTEXT carries no background mask here, so a background // around each of the block's texts is drawn before the block's first text or first // line of the text's marks, except for a text that a SOLID of the block covers. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 81ee3ffe1..7ffa888c9 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,6 +13,7 @@ mod fill; mod hatch; mod linetype; mod linetype_text; +mod loops; mod mline; mod outline; pub mod paper; @@ -100,6 +101,9 @@ struct Ctx<'a> { block_pstyle: Option, /// Transparency (percent) of the block reference being expanded, for `ByBlock`. block_transparency: u8, + /// The block whose contents are being drawn (`None` at the top level): a dimension in it whose + /// own block leads back to it is drawn from its definition points (see [`loops`]). + block: Option<&'a cadcraft_doc::Block>, } impl Ctx<'_> { @@ -130,6 +134,9 @@ struct Builder<'a> { points: &'a std::sync::atomic::AtomicUsize, /// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests). max_points: usize, + /// The loops of the drawing's block graph, worked out once for the whole build when a search + /// near a dimension's block does not settle whether it leads back (see [`loops`]). + loops: &'a std::sync::OnceLock, } /// Upper bound on the block contents drawn per display list (each block reference, MINSERT copy @@ -380,8 +387,14 @@ impl<'a> Builder<'a> { transparency: self.transparency, points: self.points, max_points: self.max_points, + loops: self.loops, } } + /// Whether block `to` leads back to block `from` in `d`, the drawing being built (see + /// [`loops`]). + fn leads_back(&self, d: &Drawing, from: &cadcraft_doc::Block, to: &cadcraft_doc::Block) -> bool { + loops::leads_back(d, self.loops, from, to) + } /// Take one unit of the block-expansion budget; false once it is spent, or once the build /// holds all the points it may ([`MAX_DISPLAY_POINTS`]), so block copies stop being visited. fn expand(&mut self) -> bool { diff --git a/crates/render/src/loops.rs b/crates/render/src/loops.rs new file mode 100644 index 000000000..2c4a008c1 --- /dev/null +++ b/crates/render/src/loops.rs @@ -0,0 +1,219 @@ +//! Loops in the block graph, for dimensions inside blocks (#1923). +//! +//! A block leads to the blocks that drawing its contents draws in turn: those of its block +//! references, dimensions and multileaders, also inside proxy graphics. A dimension inside block +//! `C` whose own block leads back to `C` is part of a loop: drawn from its block, it would draw `C` +//! again, and every such dimension again at each level down to `MAX_BLOCK_DEPTH`. With k of them +//! in the loop that is up to k^16 copies, or one per ordering of the distinct blocks on the loop, +//! which only the expansion budget cuts. Such a dimension is drawn from its definition points +//! instead, as one whose block is missing is. The loops are those of the drawing's data: an +//! object on the way that is hidden or on a layer that is off still closes one. + +use std::collections::HashMap; +use std::sync::OnceLock; + +use cadcraft_doc::{Block, Drawing, Entity, EntityKind}; + +/// The most blocks, and objects in them, that the search from a dimension's block looks at before +/// the whole block graph is searched instead: room for a dimension's block and the blocks of its +/// arrowheads, which is what such a search usually meets. +const NEARBY_BLOCKS: usize = 16; +const NEARBY_OBJECTS: usize = 256; + +/// Whether block `to` leads back to block `from` in `d`: it is `from`, or drawing `to` draws +/// `from` again. A short search from `to` answers for ordinary blocks. Past it, the loops of the +/// whole block graph are found, once per build (`loops`), and answer from then on. +pub(crate) fn leads_back(d: &Drawing, loops: &OnceLock, from: &Block, to: &Block) -> bool { + if std::ptr::eq(from, to) { + return true; + } + if let Some(l) = loops.get() { + return l.on_one_loop(from, to); + } + match reaches_nearby(d, to, from) { + Some(found) => found, + None => loops.get_or_init(|| BlockLoops::new(d)).on_one_loop(from, to), + } +} + +/// Whether `start` leads to `target`, when looking at no more than [`NEARBY_BLOCKS`] blocks and +/// [`NEARBY_OBJECTS`] objects in them settles it. +fn reaches_nearby(d: &Drawing, start: &Block, target: &Block) -> Option { + let mut found: Vec<&Block> = vec![start]; + let mut objects = NEARBY_OBJECTS; + let mut drawn = Vec::new(); + let mut next = 0; + while let Some(b) = found.get(next).copied() { + next += 1; + for e in b.entities.iter() { + if !drawn_blocks(d, e, &mut drawn, &mut objects) { + return None; + } + } + for t in drawn.drain(..) { + if std::ptr::eq(t, target) { + return Some(true); + } + if !found.iter().any(|f| std::ptr::eq(*f, t)) { + if found.len() >= NEARBY_BLOCKS { + return None; + } + found.push(t); + } + } + } + Some(false) +} + +/// The blocks that lie on a loop, numbered by their strongly connected component: two blocks +/// lead to each other exactly when they have the same number. +pub(crate) struct BlockLoops { + /// The component of each block that shares one with another block, by the block's address. + component: HashMap, +} + +impl BlockLoops { + fn new(d: &Drawing) -> Self { + let blocks: Vec<&Block> = d.blocks.values().map(|b| &**b).collect(); + let index: HashMap = blocks.iter().enumerate().map(|(i, b)| (address(b), i)).collect(); + let edges: Vec> = blocks + .iter() + .map(|b| { + let (mut drawn, mut unlimited) = (Vec::new(), usize::MAX); + for e in b.entities.iter() { + drawn_blocks(d, e, &mut drawn, &mut unlimited); + } + drawn.into_iter().filter_map(|t| index.get(&address(t)).copied()).collect() + }) + .collect(); + let mut component = HashMap::new(); + for (n, members) in components(&edges).into_iter().filter(|c| c.len() > 1).enumerate() { + for i in members { + if let Some(b) = blocks.get(i) { + component.insert(address(b), n); + } + } + } + BlockLoops { component } + } + + /// Whether blocks `a` and `b` lie on one loop (so each leads to the other). + fn on_one_loop(&self, a: &Block, b: &Block) -> bool { + self.component.get(&address(a)).is_some_and(|c| self.component.get(&address(b)) == Some(c)) + } +} + +fn address(b: &Block) -> usize { + std::ptr::from_ref(b) as usize +} + +/// Push each block that `e` draws itself, as the renderer finds it by name, counting the objects +/// looked at (`e` and its proxy graphics) against `objects`: false when they run out. +fn drawn_blocks<'d>(d: &'d Drawing, e: &Entity, drawn: &mut Vec<&'d Block>, objects: &mut usize) -> bool { + // Proxy graphics wait here (no allocation for other objects). + let mut pending: Vec<&Entity> = Vec::new(); + let mut next = Some(e); + while let Some(e) = next.take().or_else(|| pending.pop()) { + let Some(left) = objects.checked_sub(1) else { return false }; + *objects = left; + let name = match &e.kind { + EntityKind::Insert(i) => Some(i.block.as_str()), + EntityKind::Dimension(dm) => dm.block.as_deref(), + EntityKind::MLeader(m) => m.block.as_ref().map(|i| i.block.as_str()), + EntityKind::Unknown(u) => { + pending.extend(u.graphics.iter()); + None + } + _ => None, + }; + if let Some(b) = name.and_then(|n| d.block(n)) { + drawn.push(&**b); + } + } + true +} + +/// The strongly connected components of the graph with `edges[i]` leaving node `i` (Tarjan's +/// algorithm, with an explicit stack so a long chain of blocks can't overflow the call stack). +fn components(edges: &[Vec]) -> Vec> { + const UNSEEN: usize = usize::MAX; + let n = edges.len(); + let (mut order, mut low, mut on_stack) = (vec![UNSEEN; n], vec![0; n], vec![false; n]); + let (mut next, mut stack, mut out) = (0, Vec::new(), Vec::new()); + let mut visit = |v: usize, order: &mut [usize], low: &mut [usize], on_stack: &mut [bool], stack: &mut Vec| { + if let (Some(o), Some(l), Some(s)) = (order.get_mut(v), low.get_mut(v), on_stack.get_mut(v)) { + (*o, *l, *s) = (next, next, true); + next += 1; + stack.push(v); + } + }; + for root in 0..n { + if order.get(root) != Some(&UNSEEN) { + continue; + } + visit(root, &mut order, &mut low, &mut on_stack, &mut stack); + // Nodes being visited, each with the position of its next edge. + let mut path: Vec<(usize, usize)> = vec![(root, 0)]; + while let Some((v, at)) = path.last_mut() { + let v = *v; + if let Some(&w) = edges.get(v).and_then(|es| es.get(*at)) { + *at += 1; + match order.get(w).copied() { + Some(UNSEEN) => { + visit(w, &mut order, &mut low, &mut on_stack, &mut stack); + path.push((w, 0)); + } + Some(ow) if on_stack.get(w) == Some(&true) => { + if let Some(l) = low.get_mut(v) { + *l = (*l).min(ow); + } + } + _ => {} + } + continue; + } + path.pop(); + let low_v = low.get(v).copied().unwrap_or(0); + if let Some(l) = path.last().and_then(|(u, _)| low.get_mut(*u)) { + *l = (*l).min(low_v); + } + if order.get(v) == Some(&low_v) { + let mut members = Vec::new(); + while let Some(w) = stack.pop() { + if let Some(s) = on_stack.get_mut(w) { + *s = false; + } + members.push(w); + if w == v { + break; + } + } + out.push(members); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::components; + + fn sorted(mut c: Vec>) -> Vec> { + c.iter_mut().for_each(|m| m.sort_unstable()); + c.sort(); + c + } + + #[test] + fn components_group_exactly_the_nodes_that_reach_each_other() { + // 0 -> 1 -> 2 -> 0 is a loop; 2 -> 3 -> 4 -> 3 is another, reached from the first; 5 + // reaches 0 but nothing reaches 5; 6 holds only a loop to itself. + let edges = vec![vec![1], vec![2], vec![0, 3], vec![4], vec![3], vec![0], vec![6]]; + assert_eq!(sorted(components(&edges)), vec![vec![0, 1, 2], vec![3, 4], vec![5], vec![6]]); + // A long chain closing on its start is one component, without deep recursion. + let n = 200_000; + let chain: Vec> = (0..n).map(|i| vec![(i + 1) % n]).collect(); + assert_eq!(components(&chain).iter().map(Vec::len).collect::>(), vec![n]); + } +} diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 86a45b15c..19ea04287 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -102,6 +102,7 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St lt_factor: 1.0, block_pstyle: None, block_transparency: 0, + block: None, } } @@ -114,6 +115,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t)); let points = std::sync::atomic::AtomicUsize::new(0); + let loops = std::sync::OnceLock::new(); let mut b = Builder { list: DisplayList::default(), opts, @@ -124,6 +126,7 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo transparency: 0, points: &points, max_points, + loops: &loops, }; if let Space::Paper(name) = space { b.list.sheet = paper::sheet(d, name); @@ -171,7 +174,7 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor use rayon::prelude::*; let ents: Vec<&std::sync::Arc> = store.iter().collect(); let budget = std::sync::atomic::AtomicUsize::new(0); - let (opts, plotting, points, max_points) = (b.opts, b.plotting, b.points, b.max_points); + let (opts, plotting, points, max_points, loops) = (b.opts, b.plotting, b.points, b.max_points, b.loops); let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { @@ -185,6 +188,7 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor transparency: 0, points, max_points, + loops, }; for e in chunk { entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); @@ -238,6 +242,7 @@ pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: opts }; let points = std::sync::atomic::AtomicUsize::new(0); + let loops = std::sync::OnceLock::new(); let mut b = Builder { list: DisplayList::default(), opts, @@ -248,6 +253,7 @@ pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: transparency: 0, points: &points, max_points: MAX_DISPLAY_POINTS, + loops: &loops, }; for e in ents { entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 6a1629029..1dc6057b6 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -71,6 +71,7 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t)); let points = std::sync::atomic::AtomicUsize::new(0); + let loops = std::sync::OnceLock::new(); let mut b = Builder { list: DisplayList::default(), opts, @@ -81,6 +82,7 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds transparency: 0, points: &points, max_points: MAX_DISPLAY_POINTS, + loops: &loops, }; contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle)); b.list @@ -135,6 +137,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou transparency: 0, points: b.points, max_points: b.max_points, + loops: b.loops, }; #[cfg(not(target_arch = "wasm32"))] let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK; @@ -146,7 +149,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou // As `build_parallel`: chunks built side by side, joined in drawing order. use rayon::prelude::*; let ents: Vec<&std::sync::Arc> = d.model.iter().collect(); - let (opts, points, max_points) = (b.opts, b.points, b.max_points); + let (opts, points, max_points, loops) = (b.opts, b.points, b.max_points, b.loops); let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { @@ -160,6 +163,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou transparency: 0, points, max_points, + loops, }; let c = ctx(); for me in chunk.iter().filter(|me| seen(me)) {