Selection through a viewport leaves out block parts on its frozen layers (#3126)

Through an MSPACE viewport a block reference on a layer the viewport draws
was hit on a part whose layer is frozen in that viewport, and that part
took room in the box a window tests. The viewport does not draw the part.

- doc: ViewportBounds measures an entity as one layout viewport draws it,
  without the block contents on the viewport's frozen layers.
- render: build_entities_in_viewport builds loose entities as a viewport
  that freezes the given layers draws them.
- engine: a pick, selection cycling's list, a window, a crossing window, a
  fence and the polygons test a reference against that box and that
  geometry. The spatial index is unchanged: the viewport's box is never
  larger than the indexed one.
- ui: the highlight of a reference inside the active viewport is built
  the same way.

A clipped reference (XCLIP) stays selected by its boundary whatever the
viewport draws inside it, as AutoCAD 2022 selects it: it keeps the box
the drawing gives it.

Nothing changes where no layer is frozen in the active viewport.
This commit is contained in:
V1dalTheAbidal
2026-11-16 11:14:42 +02:00
parent ed0fbce27c
commit f3a9ecdce9
10 changed files with 1233 additions and 60 deletions
+267 -37
View File
@@ -270,15 +270,56 @@ fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
/// entities a visibility state hides are invisible this way, and they sit far from the block's
/// geometry in real drawings. Layer "0" takes the insert's layer, which the caller has checked.
/// `off_counts`: a layer turned off counts too, as in the drawing's extents ([`extent_bounds`]).
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool) -> bool {
/// `frozen`: the layers frozen in the layout viewport measured through ([`ViewportBounds`]).
fn in_block_visible(d: &Drawing, e: &Entity, off_counts: bool, frozen: &[String]) -> bool {
// Attribute definitions are not drawn in an insert (its attribs are, see below).
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts)
!matches!(e.kind, EntityKind::AttDef(_)) && e.common.visible && layer_counts(d, &e.common.layer, off_counts, frozen)
}
/// Whether what lies on `layer` inside an insert counts: layer "0" takes the insert's layer, which
/// the caller has checked; a frozen layer never counts, one turned off only with `off_counts`.
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool) -> bool {
layer == "0" || d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts))
/// Nor does one of the layers in `frozen`, those frozen in the layout viewport measured through,
/// which does not draw them (the names compared as the renderer compares them).
fn layer_counts(d: &Drawing, layer: &str, off_counts: bool, frozen: &[String]) -> bool {
layer == "0" || (d.layer(layer).is_none_or(|l| !l.frozen && (l.on || off_counts)) && !frozen.iter().any(|f| f.eq_ignore_ascii_case(layer)))
}
/// The box of the contents of the block `blk`, referenced at `depth`, in the block's coordinates:
/// the parts that count there ([`in_block_visible`]). It is read from `blocks`, or measured and
/// kept there, so a block is measured once per depth and not again for every reference to it
/// ([`bounds_in`] says what the maps hold and why the depth is part of the key).
fn block_contents_box<'a>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
in_drawing: &mut HashMap<(&'a str, usize), Bounds2>,
off_counts: bool,
frozen: &[String],
) -> Bounds2 {
if let Some(known) = blocks.get(&(blk.name.as_str(), depth)) {
return *known;
}
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts, frozen)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks, in_drawing, off_counts, frozen));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
/// The box of the contents of the block `blk`, referenced at `depth`, as the drawing shows them:
/// no viewport's frozen layers are left out. For a clipped reference measured through a viewport
/// ([`bounds_in`]). `in_drawing` keeps these boxes, apart from that viewport's own block bounds.
fn drawing_block_box<'a>(
d: &'a Drawing,
blk: &'a crate::Block,
depth: usize,
off_counts: bool,
in_drawing: &mut HashMap<(&'a str, usize), Bounds2>,
) -> Bounds2 {
// With no layer left out, the measure never asks for the drawing's boxes itself.
block_contents_box(d, blk, depth, in_drawing, &mut HashMap::new(), off_counts, &[])
}
/// The layer an insert's attribute draws on, as the renderer takes it: its own, else its
@@ -327,13 +368,13 @@ fn mtext_box(t: &crate::MText) -> Bounds2 {
/// The box of what `e` draws (block contents on layers turned off left out).
pub fn entity_bounds(d: &Drawing, e: &Entity, depth: usize) -> Bounds2 {
bounds_of(d, e, depth, false, &mut HashMap::new())
bounds_of(d, e, depth, false, &[], &mut HashMap::new(), &mut HashMap::new())
}
/// The box `e` takes in the drawing's extents: as [`entity_bounds`], but block contents on a layer
/// turned off count, as AutoCAD 2024's ZOOM Extents counts them (a frozen layer's do not).
pub fn extent_bounds(d: &Drawing, e: &Entity) -> Bounds2 {
bounds_of(d, e, 0, true, &mut HashMap::new())
bounds_of(d, e, 0, true, &[], &mut HashMap::new(), &mut HashMap::new())
}
/// The bounds of block contents measured so far, kept across the entities of one unchanged
@@ -351,24 +392,69 @@ pub struct BlockBoundsCache<'a> {
/// [`entity_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
pub fn entity_bounds_cached<'a>(d: &'a Drawing, e: &Entity, depth: usize, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
bounds_of(d, e, depth, false, &mut cache.drawn)
bounds_of(d, e, depth, false, &[], &mut cache.drawn, &mut HashMap::new())
}
/// [`extent_bounds`] reusing the block bounds `cache` holds from earlier calls on drawing `d`.
pub fn extent_bounds_cached<'a>(d: &'a Drawing, e: &Entity, cache: &mut BlockBoundsCache<'a>) -> Bounds2 {
bounds_of(d, e, 0, true, &mut cache.extents)
bounds_of(d, e, 0, true, &[], &mut cache.extents, &mut HashMap::new())
}
fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blocks: &mut HashMap<(&'a str, usize), Bounds2>) -> Bounds2 {
/// The boxes of what one layout viewport draws: [`entity_bounds`] with the block contents on the
/// layers frozen in that viewport left out, as the viewport leaves them out when it draws. It
/// keeps the block bounds it has measured, as a [`BlockBoundsCache`] does, so use one only while
/// the drawing it measured is unchanged. The layers belong to it, so the bounds measured through
/// one viewport never answer for another. One thing a selection counts whatever the viewport
/// draws stays in: a clipped reference (XCLIP) is selected by its boundary, so it keeps the box
/// the drawing gives it.
pub struct ViewportBounds<'a> {
/// The layers frozen in the viewport.
frozen: &'a [String],
/// By block name and depth, the box of the block contents the viewport draws.
blocks: HashMap<(&'a str, usize), Bounds2>,
/// The same with no layer of the viewport left out: the box the drawing gives the contents,
/// which a clipped reference keeps.
in_drawing: HashMap<(&'a str, usize), Bounds2>,
}
impl<'a> ViewportBounds<'a> {
/// For a viewport that freezes the layers in `frozen` (none: the drawing as it shows anywhere).
pub fn new(frozen: &'a [String]) -> Self {
ViewportBounds { frozen, blocks: HashMap::new(), in_drawing: HashMap::new() }
}
/// The layers frozen in the viewport.
pub fn frozen(&self) -> &'a [String] {
self.frozen
}
/// The box of what the viewport draws of `e`. Like [`entity_bounds`] it does not look at the
/// layer `e` itself is on: whether the viewport draws `e` at all is the caller's to check.
pub fn entity_bounds(&mut self, d: &'a Drawing, e: &Entity) -> Bounds2 {
bounds_of(d, e, 0, false, self.frozen, &mut self.blocks, &mut self.in_drawing)
}
}
/// The box of `e` at `depth` with the block bounds in `blocks` and `in_drawing`: [`bounds_in`], a
/// top-level annotative object measured as it draws.
fn bounds_of<'a>(
d: &'a Drawing,
e: &Entity,
depth: usize,
off_counts: bool,
frozen: &[String],
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
in_drawing: &mut HashMap<(&'a str, usize), Bounds2>,
) -> Bounds2 {
// A top-level annotative object measures as it draws at the current annotation scale.
if depth == 0 {
match d.anno_draw(e) {
crate::AnnoDraw::Plain => {}
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, off_counts),
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
}
}
bounds_in(d, e, depth, blocks, off_counts)
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
}
/// [`entity_bounds`] with the bounds of block contents (in block coordinates) already computed,
@@ -376,8 +462,20 @@ fn bounds_of<'a>(d: &'a Drawing, e: &Entity, depth: usize, off_counts: bool, blo
/// expanding the block again, so nested or self-referencing blocks cost at most one pass over each
/// definition per depth instead of one per reference (which grows exponentially with the nesting
/// depth). The depth is part of the key because [`MAX_BLOCK_DEPTH`] cuts a deep visit short: its
/// bounds must not stand in for a shallower reference to the same block (#706).
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<(&'a str, usize), Bounds2>, off_counts: bool) -> Bounds2 {
/// bounds must not stand in for a shallower reference to the same block (#706). The bounds in
/// `blocks` depend on `off_counts` and on `frozen` (see [`layer_counts`]), so one map goes with
/// one value of each. `in_drawing` is the map that goes with the same `off_counts` and no frozen
/// layer: a measure through a viewport takes from it the box the drawing gives the block of a
/// clipped reference ([`drawing_block_box`]). A measure with no frozen layer does not use it.
fn bounds_in<'a>(
d: &'a Drawing,
e: &Entity,
depth: usize,
blocks: &mut HashMap<(&'a str, usize), Bounds2>,
in_drawing: &mut HashMap<(&'a str, usize), Bounds2>,
off_counts: bool,
frozen: &[String],
) -> Bounds2 {
match &e.kind {
EntityKind::Table(t) if t.is_broken() => t.bounds(),
EntityKind::Text(t) if blank(&t.value) => Bounds2::EMPTY,
@@ -400,17 +498,16 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
let mut b = Bounds2::EMPTY;
if let Some(blk) = d.block(&ins.block) {
let m = ins.transform(blk.base.xy());
let inner = match blocks.get(&(blk.name.as_str(), depth)) {
Some(b) => *b,
None => {
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
};
let mut inner = block_contents_box(d, blk, depth, blocks, in_drawing, off_counts, frozen);
// XCLIP: the reference app selects a clipped reference by its boundary whatever a
// viewport draws inside it, so a clipped reference keeps the box the drawing gives it.
// One that is not inverted and has a part drawn gets the boundary's box below as it is.
if !frozen.is_empty()
&& let Some(c) = ins.clip.as_ref().filter(|c| c.active())
&& (c.inverted || inner.is_empty())
{
inner = drawing_block_box(d, blk, depth, off_counts, in_drawing);
}
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
@@ -432,7 +529,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
}
for a in &ins.attribs {
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts) {
if !a.invisible && layer_counts(d, attrib_layer(d, ins, a), off_counts, frozen) {
b = b.union(&match a.multiline_text() {
Some(m) => mtext_box(&m),
None => text_box(&a.text, a.text.value.chars().count()),
@@ -469,17 +566,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
// Reuse the shared block-bounds cache (as the Insert branch does) so a dimension
// block with branching or self-referencing children costs one pass per definition
// per depth, not one per reference (which grows exponentially) (CWE-400).
let inner = match blocks.get(&(blk.name.as_str(), depth)) {
Some(cached) => *cached,
None => {
let mut inner = Bounds2::EMPTY;
for be in blk.entities.iter().filter(|be| in_block_visible(d, be, off_counts)) {
inner = inner.union(&bounds_in(d, be, depth + 1, blocks, off_counts));
}
blocks.insert((blk.name.as_str(), depth), inner);
inner
}
};
let inner = block_contents_box(d, blk, depth, blocks, in_drawing, off_counts, frozen);
// The block draws translated by the insertion point (group 12), so its bounds
// move with it (#2634); the cache above keeps the block's own bounds.
let off = dm.insertion_point.xy();
@@ -498,7 +585,7 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
if let Some(ins) = &m.block {
let be = Entity { handle: e.handle, common: e.common.clone(), kind: EntityKind::Insert(ins.clone()) };
b = b.union(&bounds_in(d, &be, depth, blocks, off_counts));
b = b.union(&bounds_in(d, &be, depth, blocks, in_drawing, off_counts, frozen));
}
b
}
@@ -798,6 +885,149 @@ mod tests {
}
}
/// Through a layout viewport the block contents on a layer frozen in it take no room: a part
/// of a reference, a part two blocks deep, a nested reference that is itself on that layer
/// (with everything in it), an attribute, the parts of the block a dimension or a multileader
/// draws (a reference nested in a dimension's block too), and the parts of an annotative
/// reference. A clipped reference (XCLIP) keeps the box the drawing gives it, whatever is drawn
/// of it. The layer's name is matched whatever its case. With no layer frozen
/// the box is the one [`entity_bounds`] gives, and one [`ViewportBounds`] gives every entity
/// the box a fresh one gives it.
#[test]
fn a_viewport_leaves_out_block_contents_on_the_layers_frozen_in_it() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(crate::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = Entity::new(crate::Handle(handle), kind);
e.common.layer = layer.into();
e
};
let reference = |block: &str| crate::Insert { block: block.into(), ..crate::Insert::default() };
let ins = |block: &str, layer: &str| {
let mut e = Entity::new(crate::Handle(2), EntityKind::Insert(reference(block)));
e.common.layer = layer.into();
e
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let mut add = |name: &str, parts: Vec<Entity>| {
let mut b = crate::Block::new(name);
for part in parts {
b.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(b));
};
// B: a line on layer 0 along y = 0 and one on "Hidden" along y = 50. N nests B. Z holds a
// reference to B that is itself on "Hidden", and a line along y = 90. H is all on "Hidden".
add("B", vec![line(1, 0.0, "0"), line(3, 50.0, "Hidden")]);
add("N", vec![ins("B", "0")]);
add("Z", vec![ins("B", "Hidden"), line(1, 90.0, "0")]);
add("H", vec![line(1, 50.0, "Hidden")]);
// A reference to B with an attribute on "Hidden" at y = 70.
let mut tagged = ins("B", "0");
if let EntityKind::Insert(i) = &mut tagged.kind {
i.attribs.push(crate::Attrib {
tag: "T".into(),
text: Text { insert: Vec3::new(0.0, 70.0, 0.0), align_pt: None, ..text(HAlign::Left, VAlign::Baseline) },
invisible: false,
constant: false,
prompt: String::new(),
props: crate::AttribProps { layer: Some("Hidden".into()), ..Default::default() },
multiline: None,
modes: Default::default(),
});
}
// References to H clipped to a boundary around its line, and with that clip inverted: no
// part of either is drawn where "Hidden" is frozen in the viewport. And a reference to B
// with the inverted clip: its line along y = 0 is drawn there.
let clip = |block: &str, inverted: bool| {
let mut e = ins(block, "0");
if let EntityKind::Insert(i) = &mut e.kind {
let boundary = crate::ClipBoundary::new(vec![Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0)]);
i.clip = Some(crate::ClipBoundary { inverted, ..boundary });
}
e
};
let (clipped, clipped_inverted, clipped_partly) = (clip("H", false), clip("H", true), clip("B", true));
// An annotative reference to B: measured as it draws at the annotation scale, here 1:1.
let mut scaled = ins("B", "0");
scaled.common.anno_scales = vec![crate::AnnoScale::unit()];
// Dimensions that draw B and N, and a multileader that draws B.
let dimension = |block: &str| {
let kind = EntityKind::Dimension(crate::Dimension {
kind: crate::DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
});
Entity::new(crate::Handle(3), kind)
};
let (dim, dim_nested) = (dimension("B"), dimension("N"));
let leader = Entity::new(
crate::Handle(4),
EntityKind::MLeader(crate::MLeader {
leaders: vec![vec![Vec3::ZERO]],
landing: Vec3::new(1.0, 0.0, 0.0),
dogleg: 0.45,
text: None,
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: Some(reference("B")),
}),
);
let frozen = ["HIDDEN".to_string()];
let mut view = ViewportBounds::new(&frozen);
let ys = |b: Bounds2| (b.min.y, b.max.y);
assert_eq!(ys(entity_bounds(&d, &ins("B", "0"), 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &ins("B", "0"))), (0.0, 0.0), "a part on the frozen layer");
assert_eq!(ys(view.entity_bounds(&d, &ins("N", "0"))), (0.0, 0.0), "a part two blocks deep");
assert_eq!(ys(entity_bounds(&d, &ins("Z", "0"), 0)), (0.0, 90.0));
assert_eq!(ys(view.entity_bounds(&d, &ins("Z", "0"))), (90.0, 90.0), "a nested reference on the frozen layer");
assert!(!entity_bounds(&d, &ins("H", "0"), 0).is_empty());
assert!(view.entity_bounds(&d, &ins("H", "0")).is_empty(), "nothing of it is drawn");
let boundary = (Vec2::new(-2.0, 40.0), Vec2::new(12.0, 60.0));
let (drawn, seen) = (entity_bounds(&d, &clipped, 0), view.entity_bounds(&d, &clipped));
assert_eq!((drawn.min, drawn.max), boundary);
assert_eq!((seen.min, seen.max), boundary, "a clipped reference no part of which is drawn keeps its boundary");
assert_eq!(ys(entity_bounds(&d, &clipped_inverted, 0)), (50.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &clipped_inverted)), (50.0, 50.0), "and one clipped the other way its block's box");
assert_eq!(ys(entity_bounds(&d, &clipped_partly, 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &clipped_partly)), (0.0, 50.0), "with a part drawn too");
assert!(entity_bounds(&d, &tagged, 0).max.y >= 70.0);
assert_eq!(ys(view.entity_bounds(&d, &tagged)), (0.0, 0.0), "an attribute on the frozen layer");
assert_eq!(ys(entity_bounds(&d, &scaled, 0)), (0.0, 50.0));
assert_eq!(ys(view.entity_bounds(&d, &scaled)), (0.0, 0.0), "an annotative reference");
assert_eq!(entity_bounds(&d, &dim, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &dim).max.y < 50.0, "the block a dimension draws");
assert_eq!(entity_bounds(&d, &dim_nested, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &dim_nested).max.y < 50.0, "a reference nested in the block a dimension draws");
assert_eq!(entity_bounds(&d, &leader, 0).max.y, 50.0);
assert!(view.entity_bounds(&d, &leader).max.y < 50.0, "the block a multileader draws");
let clips = [clipped, clipped_inverted, clipped_partly];
let all = [ins("B", "0"), ins("N", "0"), ins("Z", "0"), ins("H", "0"), tagged, scaled, dim, dim_nested, leader].into_iter().chain(clips);
let all: Vec<Entity> = all.collect();
let mut plain = ViewportBounds::new(&[]);
for e in &all {
let (shared, fresh) = (view.entity_bounds(&d, e), ViewportBounds::new(&frozen).entity_bounds(&d, e));
assert_eq!((shared.min, shared.max), (fresh.min, fresh.max));
let (unfrozen, drawn) = (plain.entity_bounds(&d, e), entity_bounds(&d, e, 0));
assert_eq!((unfrozen.min, unfrozen.max), (drawn.min, drawn.max));
}
}
/// A turned array of references reaches its side copies, not only the first and the last;
/// a hostile count measures only the copies that are drawn.
#[test]
+2 -2
View File
@@ -30,8 +30,8 @@ pub use cadcraft_geom as geom;
pub use constraint::*;
pub use entity::*;
pub use extents::{
BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts,
ole_frame_transform,
BlockBoundsCache, MAX_BLOCK_DEPTH, ViewportBounds, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame,
ole_frame_accepts, ole_frame_transform,
};
pub use format::Format;
pub use gdt::*;
+62 -15
View File
@@ -1,6 +1,6 @@
//! Hit testing and window/crossing selection.
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, entity_bounds};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, Prim, Space, ViewportBounds, entity_bounds};
use cadcraft_geom::{Bounds2, Line, Vec2, point_in_polygon};
use crate::spatial::{self, SpatialIndex};
@@ -8,6 +8,14 @@ use crate::{Accept, Prompt};
/// Polylines approximating an entity for hit testing, tessellated at `tol`.
pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
hit_polylines_in(d, e, &mut ViewportBounds::new(&[]), tol)
}
/// [`hit_polylines`] through the layout viewport `view`: the parts of a block reference on the
/// layers frozen in that viewport are not drawn there, so they are not hit, and the box around
/// the reference is the box around the parts that are drawn ([`bounds_in`]). A clipped
/// reference's box stays, as [`ViewportBounds`] says.
fn hit_polylines_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, tol: f64) -> Vec<Vec<Vec2>> {
match &e.kind {
EntityKind::Text(_)
| EntityKind::MText(_)
@@ -19,17 +27,18 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
| EntityKind::MLeader(_)
| EntityKind::Image(_) => {
// Text-like objects are hit inside their box.
let b = entity_bounds(d, e, 0);
let b = bounds_in(d, e, None, view);
if b.is_empty() {
return Vec::new();
}
let c = b.corners();
let mut v = vec![vec![c[0], c[1], c[2], c[3], c[0]]];
if matches!(e.kind, EntityKind::Dimension(_) | EntityKind::Insert(_) | EntityKind::MLeader(_)) {
let list = cadcraft_render::build_entities(
let list = cadcraft_render::build_entities_in_viewport(
d,
std::iter::once(e),
&cadcraft_render::Options { tolerance: tol, text: false, linetypes: false, ..Default::default() },
view.frozen(),
);
v = list.prims.iter().map(|p| list.points(p).to_vec()).collect();
v.push(vec![c[0], c[1], c[2], c[3], c[0]]);
@@ -93,7 +102,13 @@ fn dist_to_polyline(pts: &[Vec2], p: Vec2) -> f64 {
/// Distance from `p` to the entity (0 inside text boxes and solid fills).
pub fn entity_distance(d: &Drawing, e: &Entity, p: Vec2, tol: f64) -> f64 {
let polys = hit_polylines(d, e, tol);
entity_distance_in(d, e, &mut ViewportBounds::new(&[]), p, tol)
}
/// [`entity_distance`] through the layout viewport `view`: to what that viewport draws of the
/// entity ([`hit_polylines_in`]).
fn entity_distance_in<'a>(d: &'a Drawing, e: &Entity, view: &mut ViewportBounds<'a>, p: Vec2, tol: f64) -> f64 {
let polys = hit_polylines_in(d, e, view, tol);
let mut best = polys.iter().map(|pl| dist_to_polyline(pl, p)).fold(f64::INFINITY, f64::min);
let filled = matches!(e.kind, EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::AttDef(_) | EntityKind::Table(_))
|| matches!(e.kind, EntityKind::Tolerance(_));
@@ -183,6 +198,16 @@ pub(crate) fn bounds_of(d: &Drawing, e: &Entity, known: Option<Bounds2>) -> Boun
known.unwrap_or_else(|| entity_bounds(d, e, 0))
}
/// The box a selection made through the layout viewport `view` tests `e` against: the box of
/// what that viewport draws of it. `known` is the box the spatial index holds, of what the
/// drawing shows; it stands unless the viewport freezes layers and `e` draws a block (a block
/// reference, a dimension, a multileader), whose contents on those layers the viewport leaves
/// out. That box is never larger than `known`, so the index still finds every candidate.
fn bounds_in<'a>(d: &'a Drawing, e: &Entity, known: Option<Bounds2>, view: &mut ViewportBounds<'a>) -> Bounds2 {
let draws_a_block = matches!(e.kind, EntityKind::Insert(_) | EntityKind::Dimension(_) | EntityKind::MLeader(_));
if draws_a_block && !view.frozen().is_empty() { view.entity_bounds(d, e) } else { bounds_of(d, e, known) }
}
pub(crate) fn is_infinite(e: &Entity) -> bool {
matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))
}
@@ -235,16 +260,17 @@ pub(crate) fn pick_with(
aperture: f64,
) -> Option<Handle> {
let probe = Bounds2::new(p, p).expand(aperture);
let mut view = ViewportBounds::new(frozen);
// Candidates come topmost first: the first within the aperture is the one.
for (e, known) in candidates(d, space, ix, &probe.expand(aperture), true, true)? {
if !selectable(d, e, frozen) {
continue;
}
let infinite = is_infinite(e);
if !infinite && !bounds_of(d, e, known).expand(aperture).intersects(&probe) {
if !infinite && !bounds_in(d, e, known, &mut view).expand(aperture).intersects(&probe) {
continue;
}
if entity_distance(d, e, p, aperture / 4.0) <= aperture {
if entity_distance_in(d, e, &mut view, p, aperture / 4.0) <= aperture {
return Some(e.handle);
}
}
@@ -262,9 +288,13 @@ pub fn pick_all_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, apert
let ix = spatial::index(d, space);
let probe = Bounds2::new(p, p).expand(aperture);
let Some(cands) = candidates(d, space, &ix, &probe.expand(aperture), true, true) else { return Vec::new() };
let mut view = ViewportBounds::new(frozen);
cands
.filter(|(e, known)| selectable(d, e, frozen) && (is_infinite(e) || bounds_of(d, e, *known).expand(aperture).intersects(&probe)))
.filter(|(e, _)| entity_distance(d, e, p, aperture / 4.0) <= aperture)
.filter(|(e, known)| {
selectable(d, e, frozen)
&& (is_infinite(e) || bounds_in(d, e, *known, &mut view).expand(aperture).intersects(&probe))
&& entity_distance_in(d, e, &mut view, p, aperture / 4.0) <= aperture
})
.map(|(e, _)| e.handle)
.collect()
}
@@ -311,7 +341,8 @@ pub(crate) fn select_window_with(
) -> Vec<Handle> {
let Some(cands) = candidates(d, space, ix, &bx, crossing, false) else { return Vec::new() };
let tol = window_tol(&bx);
cands.filter(|(e, known)| selectable(d, e, frozen) && in_window(d, e, *known, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
let mut view = ViewportBounds::new(frozen);
cands.filter(|(e, known)| selectable(d, e, frozen) && in_window_in(d, e, *known, &mut view, &bx, crossing, tol)).map(|(e, _)| e.handle).collect()
}
/// The tessellation tolerance window and crossing tests use for a box.
@@ -322,15 +353,29 @@ pub(crate) fn window_tol(bx: &Bounds2) -> f64 {
/// Whether a window box (`crossing` false: entirely inside) or a crossing box (inside or
/// touching its geometry, not just its bounding box) selects `e`.
pub(crate) fn in_window(d: &Drawing, e: &Entity, known: Option<Bounds2>, bx: &Bounds2, crossing: bool, tol: f64) -> bool {
in_window_in(d, e, known, &mut ViewportBounds::new(&[]), bx, crossing, tol)
}
/// [`in_window`] through the layout viewport `view`: a block reference is inside the box, or
/// touches it, by the parts that viewport draws ([`bounds_in`], [`hit_polylines_in`]).
fn in_window_in<'a>(
d: &'a Drawing,
e: &Entity,
known: Option<Bounds2>,
view: &mut ViewportBounds<'a>,
bx: &Bounds2,
crossing: bool,
tol: f64,
) -> bool {
let infinite = is_infinite(e);
let eb = bounds_of(d, e, known);
let eb = bounds_in(d, e, known, view);
if !infinite && bx.contains_box(&eb) {
return true;
}
if !crossing || (!infinite && !eb.intersects(bx)) {
return false;
}
let polys = hit_polylines(d, e, tol);
let polys = hit_polylines_in(d, e, view, tol);
let hit = polys.iter().any(|pl| {
if pl.len() == 1 {
pl.first().is_some_and(|p| bx.contains(*p))
@@ -378,13 +423,14 @@ pub(crate) fn select_fence_with(
let tol = (fb.width() + fb.height()).max(1e-9) / 2000.0;
let probe = fb.expand(tol);
let Some(cands) = candidates(d, space, ix, &probe, true, false) else { return Vec::new() };
let mut view = ViewportBounds::new(frozen);
let mut out = Vec::new();
for (e, known) in cands {
// Infinite objects have no useful bounds; like window selection, test their geometry directly.
if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_of(d, e, known).intersects(&probe)) {
if !selectable(d, e, frozen) || (!is_infinite(e) && !bounds_in(d, e, known, &mut view).intersects(&probe)) {
continue;
}
let polys = hit_polylines(d, e, tol);
let polys = hit_polylines_in(d, e, &mut view, tol);
let hit = fence.windows(2).any(|f| {
let (Some(a), Some(b)) = (f.first(), f.get(1)) else { return false };
let fl = Line::new(*a, *b);
@@ -415,17 +461,18 @@ pub fn select_polygon_in(d: &Drawing, space: &Space, frozen: &[String], poly: &[
let Some(cands) = candidates(d, space, &ix, &pb, crossing, false) else { return Vec::new() };
let edges: Vec<Line> =
poly.windows(2).filter_map(|w| Some(Line::new(*w.first()?, *w.get(1)?))).chain(poly.last().map(|l| Line::new(*l, *first))).collect();
let mut view = ViewportBounds::new(frozen);
let mut out = Vec::new();
for (e, known) in cands {
let infinite = is_infinite(e);
if !selectable(d, e, frozen) || (infinite && !crossing) {
continue;
}
let eb = bounds_of(d, e, known);
let eb = bounds_in(d, e, known, &mut view);
if !infinite && if crossing { !eb.intersects(&pb) } else { !pb.contains_box(&eb) } {
continue;
}
let polys = hit_polylines(d, e, tol);
let polys = hit_polylines_in(d, e, &mut view, tol);
let crosses = polys.iter().any(|pl| {
pl.windows(2).any(|w| {
w.first().zip(w.get(1)).is_some_and(|(p, q)| edges.iter().any(|f| cadcraft_geom::line_line(f, &Line::new(*p, *q)).is_some()))
+1
View File
@@ -167,6 +167,7 @@ mod trim_extend_options;
mod undo_count;
mod undo_layout_tab;
mod viewport_clip;
mod viewport_frozen_block_parts;
mod viewport_frozen_selection;
mod vplayer_prompts;
mod vports;
@@ -0,0 +1,825 @@
//! A block reference on a layer the active MSPACE viewport draws, with parts on a layer frozen in
//! that viewport ("VP Freeze"): the viewport does not draw those parts, so a selection made
//! through it does not hit the reference on them, and they take no room in the box a window
//! tests. AutoCAD 2022 was given the same objects and answers the cases asserted on them one by
//! one the same way through a viewport. Where it differs is what is taken through the rectangle
//! around a reference (#2991): the grid test only compares that between a layer frozen in the
//! viewport and one frozen for the whole drawing. In a viewport that does not freeze the layer
//! and on the Model tab everything is as before.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Handle;
use cadcraft_engine::geom::{Bounds2, Vec2};
use cadcraft_engine::select;
use serde_json::json;
/// Draws a line from `a` to `b` on layer 0, or on "Hidden" when `hidden`, and returns its handle.
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2], hidden: bool) -> Handle {
let r = s.execute("line", &json!({ "points": [a, b] })).unwrap();
let h = Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap();
if hidden {
to_hidden(s, h);
}
h
}
/// Puts `h` on the layer "Hidden".
fn to_hidden(s: &mut Session, h: Handle) {
s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": "Hidden" })).unwrap();
assert_eq!(s.doc().unwrap().entity(h).unwrap().common.layer, "Hidden");
}
/// Makes the block `name` of the objects `parts`, with its base at `base`, and returns the
/// reference to it that takes their place, on layer 0.
fn block(s: &mut Session, name: &str, base: [f64; 2], parts: &[Handle]) -> Handle {
let hs: Vec<String> = parts.iter().map(|h| h.hex()).collect();
let r = s.execute("block", &json!({ "name": name, "base": base, "handles": hs })).unwrap();
let h = Handle::parse_hex(r["insert"].as_str().unwrap()).unwrap();
assert_eq!(s.doc().unwrap().entity(h).unwrap().common.layer, "0");
h
}
/// Inserts the block `name` at `at` and returns the reference.
fn insert(s: &mut Session, name: &str, at: [f64; 2]) -> Handle {
let r = s.execute("insert", &json!({ "name": name, "at": at })).unwrap();
Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap()
}
/// Makes `viewport` the active MSPACE viewport.
fn enter(s: &mut Session, viewport: &str) {
s.execute("mspace", &json!({ "handle": viewport })).unwrap();
}
/// `hs` in handle order.
fn sorted(mut hs: Vec<Handle>) -> Vec<Handle> {
hs.sort_by_key(|h| h.0);
hs
}
/// Five block references on layer 0 and two viewports, as AutoCAD was given them.
struct Parts {
/// The session, on the layout that holds the two viewports, in paper space.
s: Session,
/// One line on layer 0 from (0, 0) to (10, 0) and one on "Hidden" from (0, 5) to (10, 5).
r: Handle,
/// One line, on "Hidden", from (20, 5) to (30, 5): nothing of it is drawn where the layer is
/// frozen. The last object made.
h: Handle,
/// A reference to the block of `r` nested in another block: its lines run from (40, 0) to
/// (50, 0) on layer 0 and from (40, 5) to (50, 5) on "Hidden".
n: Handle,
/// A block of a reference to the block of `r` that is itself on "Hidden" (lines from (60, 0)
/// to (70, 0) and from (60, 5) to (70, 5), neither drawn where the layer is frozen) and of a
/// line on layer 0 from (60, 10) to (70, 10).
z: Handle,
/// Two lines on layer 0, from (80, 0) to (90, 0) and from (80, 10) to (90, 10), and between
/// them one on "Hidden" from (80, 5) to (90, 5): a part that is not drawn where the layer is
/// frozen, inside the box around the parts that are.
q: Handle,
/// The viewport that freezes "Hidden".
a: String,
/// The viewport that freezes nothing.
b: String,
}
/// The drawing of [`Parts`], in paper space. With `crowded`, model space also holds enough lines,
/// far from the references, for selections to go through the spatial index instead of scanning
/// the space.
fn parts(crowded: bool) -> Parts {
let mut s = Session::new();
s.execute("layer.new", &json!({ "name": "Hidden" })).unwrap();
let on_0 = line(&mut s, [0.0, 0.0], [10.0, 0.0], false);
let on_hidden = line(&mut s, [0.0, 5.0], [10.0, 5.0], true);
let r = block(&mut s, "BP", [0.0, 0.0], &[on_0, on_hidden]);
let nested = insert(&mut s, "BP", [40.0, 0.0]);
let n = block(&mut s, "BN", [40.0, 0.0], &[nested]);
let child = insert(&mut s, "BP", [60.0, 0.0]);
to_hidden(&mut s, child);
let own = line(&mut s, [60.0, 10.0], [70.0, 10.0], false);
let z = block(&mut s, "BZ", [60.0, 0.0], &[child, own]);
let low = line(&mut s, [80.0, 0.0], [90.0, 0.0], false);
let high = line(&mut s, [80.0, 10.0], [90.0, 10.0], false);
let between = line(&mut s, [80.0, 5.0], [90.0, 5.0], true);
let q = block(&mut s, "BQ", [80.0, 0.0], &[low, high, between]);
if crowded {
let far: Vec<[f64; 2]> = (0..=cadcraft_engine::spatial::MIN_INDEXED).map(|i| [1000.0 + i as f64, 1000.0 + (i % 2) as f64]).collect();
s.execute("line", &json!({ "points": far })).unwrap();
}
let only_hidden = line(&mut s, [20.0, 5.0], [30.0, 5.0], true);
let h = block(&mut s, "BH", [20.0, 5.0], &[only_hidden]);
assert_eq!(s.doc().unwrap().model.len() >= cadcraft_engine::spatial::MIN_INDEXED, crowded, "whether model space is indexed");
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let v = s.execute("mview", &json!({ "count": 2, "p1": [20, 20], "p2": [220, 120] })).unwrap();
let (a, b) = (v["viewports"][0].as_str().unwrap().to_string(), v["viewports"][1].as_str().unwrap().to_string());
s.execute("vplayer", &json!({ "handles": [a], "freeze": ["Hidden"] })).unwrap();
Parts { s, r, h, n, z, q, a, b }
}
/// What a pick at `p` finds where the session is: through the active viewport, or on its tab.
fn pick(s: &Session, p: [f64; 2]) -> Option<Handle> {
let st = s.state().unwrap();
select::pick_in(&st.doc, &st.edit_space(), st.viewport_frozen(), Vec2::new(p[0], p[1]), 0.2)
}
/// Every object a pick at `p` finds where the session is, as selection cycling lists them.
fn pick_all(s: &Session, p: [f64; 2]) -> Vec<Handle> {
let st = s.state().unwrap();
sorted(select::pick_all_in(&st.doc, &st.edit_space(), st.viewport_frozen(), Vec2::new(p[0], p[1]), 0.2))
}
/// What a window from `a` to `b` takes where the session is (a crossing window with `crossing`).
fn window(s: &Session, a: [f64; 2], b: [f64; 2], crossing: bool) -> Vec<Handle> {
let st = s.state().unwrap();
let bx = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1]));
sorted(select::select_window_in(&st.doc, &st.edit_space(), st.viewport_frozen(), bx, crossing))
}
/// The objects of the selection set the AutoLISP `code` returns (none for nil), in handle order.
fn lisp_set(s: &mut Session, code: &str) -> Vec<Handle> {
use cadcraft_engine::lisp::value::Value as Lisp;
match s.lisp_eval(code, false, true, Vec::new()).unwrap() {
Some(Ok(Lisp::PickSet(set))) => sorted(set.items.lock().unwrap().clone()),
Some(Ok(Lisp::Nil)) => Vec::new(),
other => panic!("`{code}` returned {other:?}"),
}
}
/// What a fence along `pts` takes where the session is.
fn fence(s: &Session, pts: &[[f64; 2]]) -> Vec<Handle> {
let st = s.state().unwrap();
let pts: Vec<Vec2> = pts.iter().map(|p| Vec2::new(p[0], p[1])).collect();
sorted(select::select_fence_in(&st.doc, &st.edit_space(), st.viewport_frozen(), &pts))
}
/// What a window polygon through `pts` takes where the session is (a crossing polygon with
/// `crossing`).
fn polygon(s: &Session, pts: &[[f64; 2]], crossing: bool) -> Vec<Handle> {
let st = s.state().unwrap();
let pts: Vec<Vec2> = pts.iter().map(|p| Vec2::new(p[0], p[1])).collect();
sorted(select::select_polygon_in(&st.doc, &st.edit_space(), st.viewport_frozen(), &pts, crossing))
}
/// A pick, selection cycling's list, a crossing window, a fence and a crossing polygon on the part
/// the viewport does not draw find nothing; neither does a pick on the side of the box around both parts, nor a
/// crossing window in the empty middle of that box, where the viewport draws nothing of the
/// reference. The part it draws is hit as before, and the other viewport hits both parts. The
/// same with and without the spatial index.
#[test]
fn a_reference_is_not_hit_on_a_part_the_viewport_does_not_draw() {
for crowded in [false, true] {
let Parts { mut s, r, a, b, .. } = parts(crowded);
let around = [[4.0, 4.0], [6.0, 4.0], [6.0, 6.0], [4.0, 6.0]];
enter(&mut s, &a);
assert_eq!(pick(&s, [5.0, 5.0]), None, "a pick on the part that is not drawn (indexed: {crowded})");
assert_eq!(pick_all(&s, [5.0, 5.0]), [], "selection cycling's list there (indexed: {crowded})");
assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), [], "a crossing window over it (indexed: {crowded})");
assert_eq!(fence(&s, &[[5.0, 4.0], [5.0, 6.0]]), [], "a fence across it (indexed: {crowded})");
assert_eq!(polygon(&s, &around, true), [], "a crossing polygon over it (indexed: {crowded})");
assert_eq!(pick(&s, [0.0, 2.5]), None, "a pick on the side of the box around both parts (indexed: {crowded})");
assert_eq!(window(&s, [4.0, 2.0], [6.0, 3.0], true), [], "a crossing window between the parts (indexed: {crowded})");
assert_eq!(pick(&s, [5.0, 0.0]), Some(r), "the part that is drawn (indexed: {crowded})");
enter(&mut s, &b);
assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "this viewport draws the part (indexed: {crowded})");
assert_eq!(pick_all(&s, [5.0, 5.0]), [r]);
assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), [r]);
assert_eq!(fence(&s, &[[5.0, 4.0], [5.0, 6.0]]), [r]);
assert_eq!(polygon(&s, &around, true), [r]);
}
}
/// A window and a window polygon around the drawn part alone take the reference: the part that
/// is not drawn takes no room in its box. A window around that part alone takes nothing. The
/// other viewport needs both parts inside the window, as before.
#[test]
fn a_window_takes_a_reference_by_the_parts_the_viewport_draws() {
for crowded in [false, true] {
let Parts { mut s, r, a, b, .. } = parts(crowded);
let around = [[-1.0, -1.0], [11.0, -1.0], [11.0, 1.0], [-1.0, 1.0]];
enter(&mut s, &a);
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r], "around the drawn part alone (indexed: {crowded})");
assert_eq!(polygon(&s, &around, false), [r], "a window polygon around the drawn part alone (indexed: {crowded})");
assert_eq!(window(&s, [-1.0, 4.0], [11.0, 6.0], false), [], "around the part that is not drawn (indexed: {crowded})");
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 6.0], false), [r], "around both (indexed: {crowded})");
enter(&mut s, &b);
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [], "this viewport draws both parts (indexed: {crowded})");
assert_eq!(polygon(&s, &around, false), []);
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 6.0], false), [r]);
}
}
/// A reference whose every part is on the frozen layer has nothing drawn in the viewport: no
/// pick, window, crossing window or fence finds it there, and a window around it and three others
/// takes those three. It is still on a layer the viewport draws, so Select All takes it, and
/// Last takes such a reference when it is the last object made, as AutoCAD's All and Last do. The
/// other viewport finds it.
#[test]
fn a_reference_with_nothing_drawn_in_the_viewport_is_not_selected_there() {
for crowded in [false, true] {
let Parts { mut s, r, h, n, z, a, b, .. } = parts(crowded);
enter(&mut s, &a);
assert_eq!(pick(&s, [25.0, 5.0]), None, "a pick on its line (indexed: {crowded})");
assert_eq!(window(&s, [24.0, 4.0], [26.0, 6.0], true), [], "a crossing window over its line (indexed: {crowded})");
assert_eq!(fence(&s, &[[25.0, 4.0], [25.0, 6.0]]), [], "a fence across its line (indexed: {crowded})");
assert_eq!(window(&s, [19.0, 4.0], [31.0, 6.0], false), [], "a window around it (indexed: {crowded})");
assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], false), sorted(vec![r, n, z]), "a window around the four (indexed: {crowded})");
assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], true), sorted(vec![r, n, z]), "a crossing window over the four (indexed: {crowded})");
s.execute("selectall", &json!({})).unwrap();
assert!(s.selection().contains(&h), "its own layer is drawn: Select All takes it (indexed: {crowded})");
s.set_selection(Vec::new());
// Another reference to that block, made through this viewport: the last object made.
let last = insert(&mut s, "BH", [20.0, 15.0]);
assert_eq!(pick(&s, [25.0, 15.0]), None, "nothing of it is drawn here either (indexed: {crowded})");
assert_eq!(lisp_set(&mut s, "(ssget \"L\")"), [last], "its own layer is drawn: Last takes it (indexed: {crowded})");
enter(&mut s, &b);
assert_eq!(pick(&s, [25.0, 5.0]), Some(h), "this viewport draws it (indexed: {crowded})");
assert_eq!(window(&s, [19.0, 4.0], [31.0, 6.0], false), [h]);
assert_eq!(window(&s, [-2.0, -2.0], [72.0, 12.0], false), sorted(vec![r, h, n, z]));
}
}
/// The same inside a nested reference: a part on the frozen layer two blocks deep is not hit and
/// takes no room, and a nested reference that is itself on the frozen layer brings none of its
/// lines, whatever their layers, while the rest of the block around it is hit and measured.
#[test]
fn a_nested_reference_follows_the_viewport_too() {
for crowded in [false, true] {
let Parts { mut s, n, z, a, b, .. } = parts(crowded);
enter(&mut s, &a);
assert_eq!(pick(&s, [45.0, 5.0]), None, "the nested part that is not drawn (indexed: {crowded})");
assert_eq!(window(&s, [44.0, 4.0], [46.0, 6.0], true), [], "a crossing window over it (indexed: {crowded})");
assert_eq!(pick(&s, [45.0, 0.0]), Some(n), "the nested part that is drawn (indexed: {crowded})");
assert_eq!(window(&s, [39.0, -1.0], [51.0, 1.0], false), [n], "a window around the drawn nested part (indexed: {crowded})");
assert_eq!(pick(&s, [65.0, 0.0]), None, "the layer 0 line of a nested reference on the frozen layer (indexed: {crowded})");
assert_eq!(pick(&s, [65.0, 5.0]), None, "its other line (indexed: {crowded})");
assert_eq!(window(&s, [64.0, -1.0], [66.0, 6.0], true), [], "a crossing window over that nested reference (indexed: {crowded})");
assert_eq!(pick(&s, [65.0, 10.0]), Some(z), "the line beside it in the block (indexed: {crowded})");
assert_eq!(window(&s, [59.0, 9.0], [71.0, 11.0], false), [z], "a window around that line alone (indexed: {crowded})");
assert_eq!(window(&s, [59.0, -1.0], [71.0, 11.0], false), [z], "a window around the whole block (indexed: {crowded})");
enter(&mut s, &b);
assert_eq!(pick(&s, [45.0, 5.0]), Some(n), "this viewport draws every part (indexed: {crowded})");
assert_eq!(window(&s, [39.0, -1.0], [51.0, 1.0], false), []);
assert_eq!(pick(&s, [65.0, 0.0]), Some(z));
assert_eq!(window(&s, [59.0, 9.0], [71.0, 11.0], false), []);
}
}
/// A part that is not drawn can lie inside the box around the parts that are. A pick, selection
/// cycling's list and a fence on it find nothing there, although they are within that box; the drawn parts are hit, and a
/// window takes the reference when it holds both of them, not one alone. The hit geometry is what
/// decides here, not the box: without the viewport's layers in it the part is hit.
#[test]
fn a_part_that_is_not_drawn_is_not_hit_inside_the_box_of_the_drawn_parts() {
for crowded in [false, true] {
let Parts { mut s, q, a, b, .. } = parts(crowded);
enter(&mut s, &a);
assert_eq!(pick(&s, [85.0, 5.0]), None, "a pick on the part that is not drawn (indexed: {crowded})");
assert_eq!(pick_all(&s, [85.0, 5.0]), [], "selection cycling's list there (indexed: {crowded})");
assert_eq!(fence(&s, &[[85.0, 4.0], [85.0, 6.0]]), [], "a fence across it (indexed: {crowded})");
assert_eq!(pick(&s, [85.0, 10.0]), Some(q), "a drawn part (indexed: {crowded})");
assert_eq!(window(&s, [79.0, -1.0], [91.0, 11.0], false), [q], "a window around both drawn parts (indexed: {crowded})");
assert_eq!(window(&s, [79.0, -1.0], [91.0, 1.0], false), [], "a window around one of them (indexed: {crowded})");
enter(&mut s, &b);
assert_eq!(pick(&s, [85.0, 5.0]), Some(q), "this viewport draws the part (indexed: {crowded})");
assert_eq!(pick_all(&s, [85.0, 5.0]), [q]);
assert_eq!(fence(&s, &[[85.0, 4.0], [85.0, 6.0]]), [q]);
}
}
/// Freezing the layer in the viewport the session is in, and thawing it again, changes what the
/// next pick and the next window find: nothing is kept from before the change. With the spatial
/// index too, which is not rebuilt for a layer frozen in a viewport.
#[test]
fn freezing_and_thawing_the_layer_in_the_viewport_changes_what_is_hit_at_once() {
for crowded in [false, true] {
let Parts { mut s, r, b, .. } = parts(crowded);
enter(&mut s, &b);
assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "drawn here (indexed: {crowded})");
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), []);
s.execute("vplayer", &json!({ "handles": [b], "freeze": ["Hidden"] })).unwrap();
assert_eq!(pick(&s, [5.0, 5.0]), None, "frozen in this viewport now (indexed: {crowded})");
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r], "the part takes no room any more (indexed: {crowded})");
s.execute("vplayer", &json!({ "handles": [b], "thaw": ["Hidden"] })).unwrap();
assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "thawed again (indexed: {crowded})");
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [], "and it takes its room again (indexed: {crowded})");
}
}
/// What a user does goes through the same tests. A click on the part the viewport does not draw
/// is a click on nothing: it starts a selection window. A window dragged around the drawn part
/// alone takes the reference, and so does a click on that part. The `select` command's pick and
/// window answer the same way.
#[test]
fn clicks_and_the_select_command_see_the_parts_the_viewport_draws() {
for crowded in [false, true] {
let Parts { mut s, r, a, .. } = parts(crowded);
enter(&mut s, &a);
s.idle_click(Vec2::new(5.0, 5.0), false).unwrap();
assert!(s.pending_window.is_some(), "a click on the part that is not drawn must be a click on nothing (indexed: {crowded})");
// The other corner of that window, left to right around nothing.
s.idle_click(Vec2::new(6.0, 6.0), false).unwrap();
assert_eq!(s.selection(), [], "a click on the part that is not drawn (indexed: {crowded})");
s.idle_click(Vec2::new(-1.0, -1.0), false).unwrap();
s.idle_click(Vec2::new(11.0, 1.0), false).unwrap();
assert_eq!(s.selection(), [r], "a window dragged around the drawn part alone (indexed: {crowded})");
s.set_selection(Vec::new());
s.idle_click(Vec2::new(5.0, 0.0), false).unwrap();
assert_eq!(s.selection(), [r], "a click on the drawn part (indexed: {crowded})");
s.set_selection(Vec::new());
s.execute("select", &json!({ "at": [5, 5], "aperture": 0.5 })).unwrap();
assert_eq!(s.selection(), [], "select at a point on the part that is not drawn (indexed: {crowded})");
s.execute("select", &json!({ "window": [[-1, -1], [11, 1]] })).unwrap();
assert_eq!(s.selection(), [r], "select by a window around the drawn part (indexed: {crowded})");
}
}
/// A clipped reference (XCLIP) with every part on the frozen layer is still selected by its clip
/// boundary, as AutoCAD 2022 selects it: a pick, a crossing window and a fence on the boundary
/// and a window around it take the reference, a pick on the part that is not drawn does not, and
/// a window must hold the whole boundary. Hiding the frames (XCLIPFRAME 0) changes none of that.
/// The viewport draws the frame and nothing else of the reference. The viewport that draws the
/// layer selects it on its part too.
#[test]
fn a_clipped_reference_with_no_part_drawn_is_selected_by_its_boundary() {
/// [`parts`] with one more reference to the block of `h`, at (20, 20), where its line runs
/// from (20, 20) to (30, 20), clipped to the rectangle from (18, 18) to (32, 22). The session
/// is left in the viewport that freezes nothing.
fn clipped(crowded: bool) -> (Parts, Handle) {
let mut p = parts(crowded);
enter(&mut p.s, &p.b);
let c = insert(&mut p.s, "BH", [20.0, 20.0]);
p.s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[18, 18], [32, 22]] })).unwrap();
(p, c)
}
/// What six selections find: a pick on the reference's line, a pick on its boundary, a
/// crossing window and a fence over the boundary, a window around all of it, and a window
/// around the line alone, inside the boundary.
fn found(s: &Session) -> [Vec<Handle>; 6] {
[
pick(s, [25.0, 20.0]).into_iter().collect(),
pick(s, [18.0, 20.0]).into_iter().collect(),
window(s, [17.0, 19.0], [19.0, 21.0], true),
fence(s, &[[17.0, 20.0], [19.0, 20.0]]),
window(s, [15.0, 15.0], [35.0, 25.0], false),
window(s, [19.0, 19.0], [31.0, 21.0], false),
]
}
/// Whether `v` lies on a side of the clip rectangle.
fn on_the_frame(v: Vec2) -> bool {
[v.x - 18.0, v.x - 32.0, v.y - 18.0, v.y - 22.0].iter().any(|d| d.abs() < 1e-9)
}
for crowded in [false, true] {
let (Parts { mut s, a, .. }, c) = clipped(crowded);
assert_eq!(found(&s), [vec![c], vec![c], vec![c], vec![c], vec![c], vec![]], "where the layer is drawn (indexed: {crowded})");
enter(&mut s, &a);
let by_its_boundary = [vec![], vec![c], vec![c], vec![c], vec![c], vec![]];
assert_eq!(found(&s), by_its_boundary, "through the viewport that freezes the layer (indexed: {crowded})");
// That viewport draws the frame, and only the frame.
{
let st = s.state().unwrap();
let reference = st.doc.entity(c).unwrap();
let drawn = cadcraft_engine::render::build_entities_in_viewport(
&st.doc,
std::iter::once(&**reference),
&Default::default(),
st.viewport_frozen(),
);
assert!(!drawn.verts.is_empty(), "the frame is drawn (indexed: {crowded})");
assert!(drawn.verts.iter().all(|v| on_the_frame(Vec2::new(v.x, v.y))), "nothing but the frame is drawn (indexed: {crowded})");
}
// With the frames hidden the boundary selects all the same.
s.execute("xclipframe", &json!({ "value": 0 })).unwrap();
assert_eq!(found(&s), by_its_boundary, "with the frames hidden (indexed: {crowded})");
}
}
/// A clipped reference with a part on each layer, the clip showing a piece of both, with the
/// coordinates AutoCAD 2022 was given (here 100 to the right) and its answers. Through the
/// viewport the piece on the frozen layer is not hit; the drawn piece and the boundary are, the
/// part of the block the clip cuts away is not, and a window must hold the whole boundary.
#[test]
fn a_clipped_reference_with_a_part_drawn_is_selected_by_its_boundary_and_that_part() {
for crowded in [false, true] {
let Parts { mut s, a, b, .. } = parts(crowded);
enter(&mut s, &b);
// A line on layer 0 from (130, 30) to (160, 30) and one on "Hidden" 4 above it, clipped to
// the rectangle from (138, 27) to (152, 37).
let on_0 = line(&mut s, [130.0, 30.0], [160.0, 30.0], false);
let on_hidden = line(&mut s, [130.0, 34.0], [160.0, 34.0], true);
let c = block(&mut s, "BK", [130.0, 30.0], &[on_0, on_hidden]);
s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[138, 27], [152, 37]] })).unwrap();
assert_eq!(pick(&s, [145.0, 34.0]), Some(c), "where the layer is drawn (indexed: {crowded})");
enter(&mut s, &a);
assert_eq!(pick(&s, [145.0, 34.0]), None, "the piece that is not drawn (indexed: {crowded})");
assert_eq!(pick(&s, [145.0, 30.0]), Some(c), "the drawn piece (indexed: {crowded})");
assert_eq!(pick(&s, [133.0, 30.0]), None, "the layer 0 part where the clip cuts it away (indexed: {crowded})");
assert_eq!(pick(&s, [145.0, 27.0]), Some(c), "the bottom side of the boundary (indexed: {crowded})");
assert_eq!(pick(&s, [145.0, 37.0]), Some(c), "the top side of the boundary (indexed: {crowded})");
assert_eq!(window(&s, [144.0, 26.0], [146.0, 28.0], true), [c], "a crossing window over the bottom side (indexed: {crowded})");
assert_eq!(window(&s, [137.0, 26.0], [153.0, 38.0], false), [c], "a window around the boundary (indexed: {crowded})");
assert_eq!(window(&s, [137.5, 29.0], [152.5, 31.0], false), [], "a window around the drawn piece alone (indexed: {crowded})");
assert_eq!(window(&s, [137.0, 26.0], [153.0, 33.0], false), [], "a window around the lower half of the boundary (indexed: {crowded})");
assert_eq!(window(&s, [128.0, 26.0], [162.0, 38.0], false), [c], "a window around the whole block (indexed: {crowded})");
}
}
/// A reference with an inverted clip keeps the box the drawing gives it as well, so its frame,
/// which the viewport draws, here beside a part it does not draw, is still hit there: by a pick
/// and by a fence, neither of which comes near a side of that box. AutoCAD 2022 selects such a
/// reference by its frame too, and answers the pick on the drawn part and the two windows the
/// same way. The shape is the one AutoCAD was given, 80 to the right. This test passes without
/// the change as well: it holds what the change must leave alone, and fails when a clipped
/// reference is measured through the viewport like any other.
#[test]
fn an_inverted_clip_is_hit_on_its_frame_through_the_viewport() {
for crowded in [false, true] {
let Parts { mut s, a, b, .. } = parts(crowded);
enter(&mut s, &b);
// The block of `r` at (100, 20): a line on layer 0 from (100, 20) to (110, 20) and one on
// "Hidden" 5 above it. The clip hides what is inside the rectangle from (103, 23) to
// (107, 27), so the bottom side of its frame runs between the two lines.
let c = insert(&mut s, "BP", [100.0, 20.0]);
s.execute("xclip", &json!({ "handle": c.hex(), "rectangle": [[103, 23], [107, 27]], "invert": true })).unwrap();
assert_eq!(pick(&s, [105.0, 23.0]), Some(c), "where the layer is drawn (indexed: {crowded})");
enter(&mut s, &a);
assert_eq!(pick(&s, [105.0, 23.0]), Some(c), "the bottom side of the frame (indexed: {crowded})");
assert_eq!(fence(&s, &[[105.0, 22.5], [105.0, 23.5]]), [c], "a fence across it (indexed: {crowded})");
assert_eq!(pick(&s, [101.0, 20.0]), Some(c), "the layer 0 part outside the boundary (indexed: {crowded})");
assert_eq!(window(&s, [99.0, 19.0], [111.0, 21.0], false), [], "a window around the drawn part alone (indexed: {crowded})");
assert_eq!(window(&s, [99.0, 19.0], [111.0, 28.5], false), [c], "a window around both parts and the frame (indexed: {crowded})");
}
}
/// What a pick at `p` finds in the model space of `d` through a viewport that freezes the layers
/// in `frozen`, or on the Model tab with no layer.
fn picked(d: &cadcraft_engine::doc::Drawing, frozen: &[String], p: [f64; 2]) -> Option<Handle> {
select::pick_in(d, &cadcraft_engine::doc::Space::Model, frozen, Vec2::new(p[0], p[1]), 0.2)
}
/// What a window from `a` to `b` takes there ([`picked`]).
fn windowed(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec<Handle> {
let area = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1]));
select::select_window_in(d, &cadcraft_engine::doc::Space::Model, frozen, area, false)
}
/// What a crossing window from `a` to `b` takes there ([`picked`]).
fn crossed(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec<Handle> {
let area = Bounds2::new(Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1]));
select::select_window_in(d, &cadcraft_engine::doc::Space::Model, frozen, area, true)
}
/// What a fence from `a` to `b` takes there ([`picked`]).
fn fenced(d: &cadcraft_engine::doc::Drawing, frozen: &[String], a: [f64; 2], b: [f64; 2]) -> Vec<Handle> {
select::select_fence_in(d, &cadcraft_engine::doc::Space::Model, frozen, &[Vec2::new(a[0], a[1]), Vec2::new(b[0], b[1])])
}
/// Other objects that draw a block, built by hand in model space with the coordinates AutoCAD
/// 2022 was given.
struct BlockDrawers {
/// The drawing that holds them.
d: cadcraft_engine::doc::Drawing,
/// A 2 x 2 array of references (MINSERT) from (0, -30), its rows 12 and its columns 15 apart.
array: Handle,
/// A reference at (70, 30) with an attribute on "Hidden" 4 above its line.
tagged: Handle,
/// An annotative reference at the origin, at the drawing's annotation scale.
scaled: Handle,
/// A multileader from (110, -20) to (130, 0) whose content is a block (here 100 to the
/// right of where AutoCAD had it).
leader: Handle,
/// A dimension along (150, -10) to (160, -10) whose block nests a reference, as the block of
/// a dimension with an arrowhead block does in AutoCAD.
dim: Handle,
}
/// The drawing of [`BlockDrawers`]: every block has a line on layer 0 and, above it, one on
/// "Hidden", but for the one with the attribute, where the attribute is on "Hidden".
fn block_drawers() -> BlockDrawers {
use cadcraft_engine::doc::{
AnnoScale, Attrib, AttribProps, Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, HAlign, Insert, Line, MLeader, Space, Text,
VAlign,
};
use cadcraft_engine::geom::Vec3;
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let line = |handle: u64, a: [f64; 2], b: [f64; 2], layer: &str| {
let mut part = Entity::new(Handle(handle), EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) }));
part.common.layer = layer.into();
part
};
let reference = |block: &str, at: [f64; 2]| Insert { block: block.into(), insert: Vec3::new(at[0], at[1], 0.0), ..Insert::default() };
let mut define = |name: &str, parts: Vec<Entity>| {
let mut block = Block::new(name);
for part in parts {
block.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(block));
};
// BP: a line on layer 0 and, 5 above it, one on "Hidden". BM: the same, 8 apart. BA: one line.
define("BP", vec![line(1, [0.0, 0.0], [10.0, 0.0], "0"), line(2, [0.0, 5.0], [10.0, 5.0], "Hidden")]);
define("BM", vec![line(1, [0.0, 0.0], [6.0, 0.0], "0"), line(2, [0.0, 8.0], [6.0, 8.0], "Hidden")]);
define("BA", vec![line(1, [0.0, 0.0], [10.0, 0.0], "0")]);
// *D9: what a dimension draws, here a reference to BP at (150, 0) and a line of its own.
let mut nested = Entity::new(Handle(1), EntityKind::Insert(reference("BP", [150.0, 0.0])));
nested.common.layer = "0".into();
define("*D9", vec![nested, line(2, [150.0, -10.0], [160.0, -10.0], "0")]);
let model = Space::Model;
// A 2 x 2 array of BP from (0, -30), its rows 12 and its columns 15 apart.
let grid = Insert { cols: 2, rows: 2, col_spacing: 15.0, row_spacing: 12.0, ..reference("BP", [0.0, -30.0]) };
let array = d.add(&model, Common::default(), EntityKind::Insert(grid)).unwrap();
// BA at (70, 30) with an attribute on "Hidden" 4 above its line.
let value = Text {
insert: Vec3::new(70.0, 34.0, 0.0),
align_pt: None,
height: 1.5,
value: "HHHH".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
};
let attribute = Attrib {
tag: "TAG".into(),
text: value,
invisible: false,
constant: false,
prompt: String::new(),
props: AttribProps { layer: Some("Hidden".into()), ..Default::default() },
multiline: None,
modes: Default::default(),
};
let tagged = d.add(&model, Common::default(), EntityKind::Insert(Insert { attribs: vec![attribute], ..reference("BA", [70.0, 30.0]) })).unwrap();
// An annotative reference to BP at the origin, at the drawing's annotation scale.
let annotative = Common { anno_scales: vec![AnnoScale::unit()], ..Common::default() };
let scaled = d.add(&model, annotative, EntityKind::Insert(reference("BP", [0.0, 0.0]))).unwrap();
// A multileader from (110, -20) to (130, 0) with BM at (127.36, -4), where AutoCAD put it.
let leader = MLeader {
leaders: vec![vec![Vec3::new(110.0, -20.0, 0.0)]],
landing: Vec3::new(130.0, 0.0, 0.0),
dogleg: 0.36,
text: None,
style: "Standard".into(),
arrow_size: 0.18,
spline: false,
block: Some(reference("BM", [127.36, -4.0])),
};
let leader = d.add(&model, Common::default(), EntityKind::MLeader(leader)).unwrap();
// A dimension along (150, -10) to (160, -10) that draws *D9.
let dimension = Dimension {
kind: DimKind::Aligned,
defpt: Vec3::new(160.0, -10.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::new(150.0, -10.0, 0.0),
p14: Vec3::new(160.0, -10.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some("*D9".into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
};
let dim = d.add(&model, Common::default(), EntityKind::Dimension(dimension)).unwrap();
BlockDrawers { d, array, tagged, scaled, leader, dim }
}
/// An array of references (MINSERT) and a reference with an attribute on the frozen layer follow
/// the viewport as a plain reference does: the parts and the attribute on the frozen layer are
/// not hit and take no room in a window. They have the coordinates AutoCAD 2022 was given and its
/// answers. The frozen layers are given to the selection as a viewport gives them.
#[test]
fn arrays_and_attributes_follow_the_viewport() {
let BlockDrawers { d, array, tagged, .. } = block_drawers();
let through = ["Hidden".to_string()];
// The array: the "Hidden" part of no copy is hit, and a window needs the layer 0 parts only.
assert_eq!(picked(&d, &through, [5.0, -30.0]), Some(array), "the layer 0 part of the first copy");
assert_eq!(picked(&d, &through, [5.0, -25.0]), None, "the part of the first copy that is not drawn");
assert_eq!(picked(&d, &through, [20.0, -13.0]), None, "the part of the last copy that is not drawn");
assert_eq!(picked(&d, &through, [20.0, -18.0]), Some(array), "the layer 0 part of the last copy");
assert_eq!(crossed(&d, &through, [19.0, -14.0], [21.0, -12.0]), [], "a crossing window over the last copy's part that is not drawn");
assert_eq!(windowed(&d, &through, [-1.0, -31.0], [26.0, -17.0]), [array], "a window around all but the upper row's parts that are not drawn");
assert_eq!(picked(&d, &[], [20.0, -13.0]), Some(array), "where the layer is drawn");
assert_eq!(windowed(&d, &[], [-1.0, -31.0], [26.0, -17.0]), []);
assert_eq!(windowed(&d, &[], [-1.0, -31.0], [26.0, -12.0]), [array]);
// The attribute: not hit, and no room taken.
assert_eq!(picked(&d, &through, [75.0, 30.0]), Some(tagged));
assert_eq!(crossed(&d, &through, [70.0, 33.5], [76.0, 36.0]), [], "a crossing window over the attribute that is not drawn");
assert_eq!(fenced(&d, &through, [71.0, 33.0], [71.0, 37.0]), [], "a fence across it");
assert_eq!(windowed(&d, &through, [69.0, 29.0], [81.0, 31.0]), [tagged], "a window around the line alone");
assert_eq!(crossed(&d, &[], [70.0, 33.5], [76.0, 36.0]), [tagged], "where the layer is drawn");
assert_eq!(windowed(&d, &[], [69.0, 29.0], [81.0, 31.0]), []);
assert_eq!(windowed(&d, &[], [69.0, 29.0], [81.0, 37.0]), [tagged]);
}
/// An annotative reference, a multileader whose content is a block and a dimension whose block
/// nests a reference follow the viewport too: their parts on the frozen layer are not hit and
/// take no room in a window. The first two have the coordinates AutoCAD 2022 was given and its
/// answers. The frozen layers are given to the selection as a viewport gives them.
#[test]
fn annotative_references_multileaders_and_dimensions_follow_the_viewport() {
let BlockDrawers { d, scaled, leader, dim, .. } = block_drawers();
let through = ["Hidden".to_string()];
// The annotative reference.
assert_eq!(picked(&d, &through, [5.0, 5.0]), None, "the part of the annotative reference that is not drawn");
assert_eq!(picked(&d, &through, [5.0, 0.0]), Some(scaled));
assert_eq!(crossed(&d, &through, [4.0, 4.0], [6.0, 6.0]), []);
assert_eq!(fenced(&d, &through, [5.0, 4.0], [5.0, 6.0]), []);
assert_eq!(windowed(&d, &through, [-1.0, -1.0], [11.0, 1.0]), [scaled], "a window around its layer 0 part alone");
assert_eq!(picked(&d, &[], [5.0, 5.0]), Some(scaled), "where the layer is drawn");
assert_eq!(windowed(&d, &[], [-1.0, -1.0], [11.0, 1.0]), []);
// The multileader: its block's part on "Hidden" lies from (127.36, 4) to (133.36, 4).
assert_eq!(picked(&d, &through, [130.36, 4.0]), None, "the part of the multileader's block that is not drawn");
assert_eq!(picked(&d, &through, [130.36, -4.0]), Some(leader), "the layer 0 part of its block");
assert_eq!(picked(&d, &through, [120.0, -10.0]), Some(leader), "its leader line");
assert_eq!(crossed(&d, &through, [129.65, 3.29], [131.07, 4.71]), []);
assert_eq!(fenced(&d, &through, [130.36, 3.0], [130.36, 5.0]), []);
assert_eq!(windowed(&d, &through, [108.0, -22.0], [135.36, 2.0]), [leader], "a window around its leader and the layer 0 part");
assert_eq!(picked(&d, &[], [130.36, 4.0]), Some(leader), "where the layer is drawn");
assert_eq!(windowed(&d, &[], [108.0, -22.0], [135.36, 2.0]), []);
assert_eq!(windowed(&d, &[], [108.0, -22.0], [135.36, 6.0]), [leader]);
// The dimension: the nested reference's part on "Hidden" lies from (150, 5) to (160, 5).
assert_eq!(picked(&d, &through, [155.0, 5.0]), None, "the part of the reference nested in the dimension's block that is not drawn");
assert_eq!(crossed(&d, &through, [154.0, 4.0], [156.0, 6.0]), []);
assert_eq!(picked(&d, &through, [155.0, 0.0]), Some(dim), "the layer 0 part of that reference");
assert_eq!(picked(&d, &[], [155.0, 5.0]), Some(dim), "where the layer is drawn");
}
/// A drawing, built by hand with the coordinates AutoCAD 2022 was given, whose model space holds
/// one reference, and that reference: to a block with a line on layer 0 from (60, 36) to (70, 36)
/// and a reference to a block of one line on "Hidden", from (60, 30) to (70, 30), clipped (XCLIP)
/// to the rectangle from (58, 27) to (72, 33).
fn framed_reference() -> (cadcraft_engine::doc::Drawing, Handle) {
use cadcraft_engine::doc::{Block, ClipBoundary, Common, Drawing, Entity, EntityKind, Insert, Line, Space};
use cadcraft_engine::geom::Vec3;
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let line = |a: [f64; 2], b: [f64; 2]| EntityKind::Line(Line { a: Vec3::new(a[0], a[1], 0.0), b: Vec3::new(b[0], b[1], 0.0) });
let reference = |block: &str, at: [f64; 2]| Insert { block: block.into(), insert: Vec3::new(at[0], at[1], 0.0), ..Insert::default() };
let mut define = |name: &str, parts: Vec<(EntityKind, &str)>| {
let mut block = Block::new(name);
for (i, (kind, layer)) in parts.into_iter().enumerate() {
let mut part = Entity::new(Handle(i as u64 + 1), kind);
part.common.layer = layer.into();
block.entities.push(part);
}
d.blocks.insert(name.into(), std::sync::Arc::new(block));
};
// BC2: one line, on "Hidden". BNC: a reference to it, clipped to a rectangle given in the
// coordinates of BC2, and a line on layer 0.
define("BC2", vec![(line([0.0, 0.0], [10.0, 0.0]), "Hidden")]);
let boundary = ClipBoundary::new(vec![Vec2::new(-2.0, -3.0), Vec2::new(12.0, 3.0)]);
let inner = Insert { clip: Some(boundary), ..reference("BC2", [60.0, 30.0]) };
define("BNC", vec![(EntityKind::Insert(inner), "0"), (line([60.0, 36.0], [70.0, 36.0]), "0")]);
let framed = d.add(&Space::Model, Common::default(), EntityKind::Insert(reference("BNC", [0.0, 0.0]))).unwrap();
(d, framed)
}
/// A clipped reference (XCLIP) that is a part of a block keeps its boundary as well: AutoCAD 2022
/// selects the outer reference by a pick or a crossing window on the boundary of the clipped one
/// with every part inside it on a layer frozen in the viewport, and a window must hold that
/// boundary. A pick on the part that is not drawn takes nothing. The pick on the top side of the
/// boundary holds the hit geometry: it lies inside the outer reference's box, away from its
/// sides. The shape is the one AutoCAD was given. The frozen layers are given to the selection
/// as a viewport gives them.
#[test]
fn a_clipped_reference_inside_a_block_is_selected_by_its_boundary() {
let (d, framed) = framed_reference();
let through = ["Hidden".to_string()];
assert_eq!(picked(&d, &through, [58.0, 30.0]), Some(framed), "the left side of the nested clip boundary");
assert_eq!(picked(&d, &through, [65.0, 33.0]), Some(framed), "its top side");
assert_eq!(crossed(&d, &through, [57.0, 29.0], [59.0, 31.0]), [framed], "a crossing window over its left side");
assert_eq!(picked(&d, &through, [65.0, 30.0]), None, "the clipped reference's line, which is not drawn");
assert_eq!(picked(&d, &through, [65.0, 36.0]), Some(framed), "the outer reference's own line");
assert_eq!(windowed(&d, &through, [59.0, 35.0], [71.0, 37.0]), [], "a window around its own line alone");
assert_eq!(windowed(&d, &through, [56.0, 25.0], [74.0, 38.0]), [framed], "a window around its own line and the boundary");
assert_eq!(picked(&d, &[], [65.0, 30.0]), Some(framed), "where the layer is drawn");
}
/// A dimension is drawn from its block, and a crossing window inside the rectangle around a
/// dimension does not take it as one inside a block reference's does (#2991), so a dimension
/// shows what a crossing window itself tests. Over a part of that block the viewport does not
/// draw, between two parts it draws, the window takes nothing, and neither do a pick and a
/// fence; over a drawn part they take the dimension. The frozen layers are given to the
/// selection as a viewport gives them.
#[test]
fn a_crossing_window_tests_the_parts_the_viewport_draws() {
use cadcraft_engine::doc::{Block, Common, DimKind, Dimension, Drawing, Entity, EntityKind, Line, Space};
use cadcraft_engine::geom::Vec3;
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let mut block = Block::new("*D1");
for (handle, y, layer) in [(1, 0.0, "0"), (2, 10.0, "0"), (3, 5.0, "Hidden")] {
let mut part = Entity::new(Handle(handle), EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) }));
part.common.layer = layer.into();
block.entities.push(part);
}
d.blocks.insert("*D1".into(), std::sync::Arc::new(block));
let dimension = Dimension {
kind: DimKind::Aligned,
defpt: Vec3::new(5.0, 1.0, 0.0),
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(10.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 0.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some("*D1".into()),
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
};
let dim = d.add(&Space::Model, Common::default(), EntityKind::Dimension(dimension)).unwrap();
let frozen = ["Hidden".to_string()];
let (model, hidden_part, drawn_part) = (Space::Model, Vec2::new(5.0, 5.0), Vec2::new(5.0, 10.0));
let over = |p: Vec2| Bounds2::new(Vec2::new(p.x - 1.0, p.y - 1.0), Vec2::new(p.x + 1.0, p.y + 1.0));
let across = |p: Vec2| [Vec2::new(p.x, p.y - 1.0), Vec2::new(p.x, p.y + 1.0)];
assert_eq!(select::select_window_in(&d, &model, &frozen, over(hidden_part), true), [], "a crossing window over the part that is not drawn");
assert_eq!(select::pick_in(&d, &model, &frozen, hidden_part, 0.2), None, "a pick on it");
assert_eq!(select::select_fence_in(&d, &model, &frozen, &across(hidden_part)), [], "a fence across it");
assert_eq!(select::select_window_in(&d, &model, &frozen, over(drawn_part), true), [dim], "a crossing window over a drawn part");
assert_eq!(select::pick_in(&d, &model, &frozen, drawn_part, 0.2), Some(dim));
assert_eq!(select::select_window_in(&d, &model, &[], over(hidden_part), true), [dim], "where the layer is drawn");
assert_eq!(select::pick_in(&d, &model, &[], hidden_part, 0.2), Some(dim));
assert_eq!(select::select_fence_in(&d, &model, &[], &across(hidden_part)), [dim]);
}
/// The selections of a grid across the five references, with what each finds: at every point a
/// pick, selection cycling's list, a crossing window, a fence, two windows and the two polygons.
fn probes(s: &Session) -> Vec<(String, Vec<Handle>)> {
let mut out = Vec::new();
for xi in -2..=92 {
for yi in -2..=12 {
let (x, y) = (f64::from(xi), f64::from(yi));
out.push((format!("pick at ({x}, {y})"), pick(s, [x, y]).into_iter().collect()));
out.push((format!("cycling list at ({x}, {y})"), pick_all(s, [x, y])));
out.push((format!("crossing window from ({x}, {y})"), window(s, [x, y], [x + 2.0, y + 2.0], true)));
out.push((format!("fence through ({x}, {y})"), fence(s, &[[x, y - 1.0], [x, y + 1.0]])));
out.push((format!("low window from ({x}, {y})"), window(s, [x, y], [x + 13.0, y + 2.0], false)));
out.push((format!("tall window from ({x}, {y})"), window(s, [x, y], [x + 13.0, y + 12.0], false)));
out.push((format!("window polygon from ({x}, {y})"), polygon(s, &[[x, y], [x + 13.0, y], [x + 6.0, y + 3.0]], false)));
out.push((format!("crossing polygon from ({x}, {y})"), polygon(s, &[[x, y], [x + 2.0, y], [x + 1.0, y + 2.0]], true)));
}
}
out
}
/// Through a viewport that freezes a layer every selection answers as it does on the Model tab
/// with that layer frozen for the whole drawing: each selection of a grid across the references,
/// with and without the spatial index. That holds for what is taken through the rectangle around
/// a reference too (#2991): it is the rectangle around the drawn parts in both, and a part that is
/// not drawn changes nothing inside it.
#[test]
fn a_layer_frozen_in_the_viewport_selects_as_one_frozen_for_the_drawing_does() {
for crowded in [false, true] {
let Parts { mut s, r, h, n, z, q, a, .. } = parts(crowded);
enter(&mut s, &a);
let through_the_viewport = probes(&s);
let Parts { s: mut model, r: r2, h: h2, n: n2, z: z2, q: q2, .. } = parts(crowded);
assert_eq!([r, h, n, z, q], [r2, h2, n2, z2, q2], "the two drawings must be made alike");
model.execute("layout.set", &json!({ "name": "Model" })).unwrap();
model.execute("layer.set", &json!({ "name": "Hidden", "frozen": true })).unwrap();
let frozen_for_the_drawing = probes(&model);
assert_eq!(through_the_viewport.len(), frozen_for_the_drawing.len());
for (through, frozen) in through_the_viewport.iter().zip(&frozen_for_the_drawing) {
assert_eq!(through, frozen, "through the viewport, then with the layer frozen for the drawing (indexed: {crowded})");
}
// The grid does select: each reference with a drawn part many times, the one without never.
let times = |x: Handle| through_the_viewport.iter().filter(|(_, hs)| hs.contains(&x)).count();
assert!([r, n, z, q].iter().all(|x| times(*x) > 50), "taken {:?} times (indexed: {crowded})", [r, n, z, q].map(times));
assert_eq!(times(h), 0, "a reference with nothing drawn was selected (indexed: {crowded})");
}
}
/// Nothing changes where no viewport freezes the layer: on the Model tab both parts are hit and
/// both take room, and with the layer frozen for the whole drawing the part is left out there
/// as it always was.
#[test]
fn the_model_tab_and_a_layer_frozen_for_the_drawing_are_as_before() {
for crowded in [false, true] {
let Parts { mut s, r, h, .. } = parts(crowded);
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
assert_eq!(pick(&s, [5.0, 5.0]), Some(r), "the Model tab draws both parts (indexed: {crowded})");
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), []);
assert_eq!(pick(&s, [25.0, 5.0]), Some(h));
s.execute("layer.set", &json!({ "name": "Hidden", "frozen": true })).unwrap();
assert_eq!(pick(&s, [5.0, 5.0]), None, "frozen for the whole drawing (indexed: {crowded})");
assert_eq!(window(&s, [4.0, 4.0], [6.0, 6.0], true), []);
assert_eq!(window(&s, [-1.0, -1.0], [11.0, 1.0], false), [r]);
assert_eq!(pick(&s, [25.0, 5.0]), None);
assert_eq!(pick(&s, [5.0, 0.0]), Some(r));
}
}
+1 -1
View File
@@ -387,7 +387,7 @@ mod viewports;
pub use dim_draw::{dim_text, dimension_in};
pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha};
pub use pipeline::{Options, build, build_entities, build_plot};
pub use pipeline::{Options, build, build_entities, build_entities_in_viewport, build_plot};
use props::{default_lineweight, resolve_common};
use text_entity::text_style;
pub use text_entity::{layout_mtext_entity, place_text_entity, style_font, text_align};
+10 -1
View File
@@ -196,6 +196,15 @@ pub(crate) fn with_point_view(d: &Drawing, space: &Space, opts: &Options) -> Opt
/// Build the display list for a set of loose entities (previews, rubber bands).
pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents: I, opts: &Options) -> DisplayList {
build_entities_in_viewport(d, ents, opts, &[])
}
/// [`build_entities`] as a selection through a layout viewport that freezes the layers in
/// `frozen` sees them: what is on one of those layers is left out, as the viewport does not draw
/// it, the parts of a block reference too. Picking through the viewport tests objects against
/// this, so a part the viewport does not draw is not hit, and the highlight of an object seen
/// through the viewport is built from it.
pub fn build_entities_in_viewport<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents: I, opts: &Options, frozen: &[String]) -> DisplayList {
let ents: Vec<&Entity> = ents.into_iter().collect();
// Only previews holding points need the model extents for relative point sizes.
let with_view;
@@ -207,7 +216,7 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
};
let mut b = Builder { list: DisplayList::default(), opts, plotting: false, styles: None, named: None, shared_budget: None, transparency: 0 };
for e in ents {
entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, frozen, &[]), e);
}
b.list
}
+28
View File
@@ -34,6 +34,34 @@ fn linetype_dashes_line() {
assert!(l.prims.len() > 10);
}
/// Loose entities built as a layout viewport draws them leave out what is on a layer frozen in
/// it, the part of a block reference on that layer too, whatever the case of the layer's name.
/// With no such layer the list is the one [`build_entities`] gives.
#[test]
fn loose_entities_built_for_a_viewport_leave_out_its_frozen_layers() {
let line = |handle: u64, y: f64, layer: &str| {
let kind = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(10.0, y, 0.0) });
let mut e = cadcraft_doc::Entity::new(Handle(handle), kind);
e.common.layer = layer.into();
e
};
let mut d = Drawing::new_metric();
d.ensure_layer("Hidden");
let mut b = cadcraft_doc::Block::new("B");
for part in [line(1, 0.0, "0"), line(2, 5.0, "Hidden")] {
b.entities.push(part);
}
d.blocks.insert("B".into(), std::sync::Arc::new(b));
let reference = cadcraft_doc::Insert { block: "B".into(), ..Default::default() };
let ents = [cadcraft_doc::Entity::new(Handle(3), EntityKind::Insert(reference)), line(4, 5.0, "Hidden"), line(5, 8.0, "0")];
let ys = |l: &DisplayList| -> Vec<f64> { l.prims.iter().map(|p| l.points(p)[0].y).collect() };
let opts = Options::default();
let frozen = ["HIDDEN".to_string()];
assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &frozen)), [0.0, 8.0]);
assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &[])), [0.0, 5.0, 5.0, 8.0]);
assert_eq!(ys(&build_entities(&d, &ents, &opts)), [0.0, 5.0, 5.0, 8.0]);
}
#[test]
fn frozen_layer_hidden() {
let mut d = sample();
+31
View File
@@ -367,6 +367,37 @@ fn the_viewport_highlight_leaves_out_objects_the_viewport_does_not_draw() {
assert_eq!(outlined(&app, &mut highlight, both), both);
}
/// The highlight of a block reference inside the active viewport shows the parts that viewport
/// draws: not its part on a layer frozen there, which the other viewport's highlight shows.
#[test]
fn the_viewport_highlight_of_a_reference_leaves_out_the_parts_the_viewport_does_not_draw() {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
for y in [0, 30] {
app.run("line", serde_json::json!({ "points": [[0, y], [100, y]] })).unwrap();
}
let lines = app.session.doc().unwrap().model.handles();
let (a, b) = viewports_freezing_hidden(&mut app);
// Inside a viewport the block's reference is made in model space, where the lines are.
app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap();
app.session.execute("properties.set", &serde_json::json!({ "handles": [lines[1].hex()], "layer": "Hidden" })).unwrap();
let parts: Vec<String> = lines.iter().map(|h| h.hex()).collect();
let made = app.session.execute("block", &serde_json::json!({ "name": "B", "base": [0, 0], "handles": parts })).unwrap();
let reference = Handle::parse_hex(made["insert"].as_str().unwrap()).unwrap();
assert_eq!(app.session.doc().unwrap().model.handles(), [reference], "the reference must be the one object in model space");
/// The heights at which `highlight` draws something for the reference.
fn heights(app: &CadApp, highlight: &mut VpHighlight, reference: Handle) -> Vec<f64> {
highlight.update(app.session.state().unwrap(), &[reference], 10.0);
let mut ys: Vec<f64> = highlight.list.prims.iter().map(|p| highlight.list.points(p)[0].y).collect();
ys.sort_by(f64::total_cmp);
ys
}
let mut highlight = VpHighlight::default();
app.session.execute("mspace", &serde_json::json!({ "handle": b })).unwrap();
assert_eq!(heights(&app, &mut highlight, reference), [0.0, 30.0], "this viewport draws both parts");
app.session.execute("mspace", &serde_json::json!({ "handle": a })).unwrap();
assert_eq!(heights(&app, &mut highlight, reference), [0.0], "a part the viewport does not draw was highlighted");
}
/// Selection cycling's badge beside a resting pointer follows the layers frozen in the active
/// viewport: over two overlapping lines it shows while the viewport draws both, goes when the
/// layer of one of them is frozen there, and comes back when the layer is thawed.
+6 -4
View File
@@ -273,7 +273,8 @@ pub(super) fn viewport_highlight_tolerance(scale: f64) -> f64 {
/// the hover are kept apart, so moving the cursor over objects doesn't tessellate the selection
/// again; each is rebuilt only when the drawing, the objects, the zoom band or the layers frozen
/// in the viewport change. An object on one of those layers is not drawn in the viewport, so it
/// is not highlighted there either.
/// is not highlighted there either, and neither are the parts of a block reference on them
/// ([`cadcraft_render::build_entities_in_viewport`]).
#[derive(Default)]
pub(super) struct VpHighlight {
key: Option<u64>,
@@ -285,18 +286,19 @@ pub(super) struct VpHighlight {
impl VpHighlight {
pub(super) fn update(&mut self, st: &cadcraft_engine::DocState, handles: &[Handle], scale: f64) {
let tolerance = viewport_highlight_tolerance(scale);
// Entering another viewport changes what is drawn without changing the drawing.
let frozen = st.viewport_frozen();
let key = {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
// Entering another viewport changes what is drawn without changing the drawing.
let frozen = st.viewport_frozen();
(st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, tolerance.to_bits(), handles, frozen, super::list::font_generation())
.hash(&mut h);
h.finish()
};
if self.key != Some(key) {
let ents = handles.iter().filter_map(|h| st.doc.model.get(*h)).filter(|e| !st.hidden_in_viewport(e)).map(|e| e.as_ref());
self.list = cadcraft_render::build_entities(&st.doc, ents, &cadcraft_render::Options { tolerance, ..Default::default() });
self.list =
cadcraft_render::build_entities_in_viewport(&st.doc, ents, &cadcraft_render::Options { tolerance, ..Default::default() }, frozen);
self.key = Some(key);
self.list_gen = self.list_gen.wrapping_add(1);
}