mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-02 20:22:15 -05:00
A value of nothing but underline and overline toggles (%%u%%u) has no drawn character, and the box floored the count at one: Aligned over a span of 20 that was a box of 20 by 120 for text that draws nothing. The box is empty when no character is drawn, for an empty value too. Co-Authored-By: Claude Fable 5.2 <[email protected]>
2463 lines
125 KiB
Rust
2463 lines
125 KiB
Rust
use crate::raster::{RasterOptions, View, render};
|
||
use crate::*;
|
||
use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space};
|
||
use cadcraft_geom::{PolyVertex, Vec3};
|
||
|
||
// The synthetic TrueType file both this suite and the PDF writer's build: the fonts layer's
|
||
// test-only helper, inlined rather than published or depended on.
|
||
#[path = "../../fonts/tests/support/sfnt.rs"]
|
||
mod sfnt;
|
||
|
||
fn sample() -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))
|
||
.unwrap();
|
||
d.add(
|
||
&Space::Model,
|
||
Common { color: Color::Index(1), ..Default::default() },
|
||
EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(5.0, 5.0, 0.0), radius: 3.0 }),
|
||
)
|
||
.unwrap();
|
||
d
|
||
}
|
||
|
||
#[test]
|
||
fn builds_lines_and_circles() {
|
||
let d = sample();
|
||
let l = build(&d, &Space::Model, &Options { tolerance: 0.01, ..Default::default() });
|
||
assert_eq!(l.prims.len(), 2);
|
||
assert!(l.prims[1].len > 20);
|
||
assert_eq!(l.prims[1].color, Rgb(255, 0, 0));
|
||
}
|
||
|
||
#[test]
|
||
fn linetype_dashes_line() {
|
||
let mut d = sample();
|
||
d.linetypes.extend(cadcraft_doc::library::standard_linetypes());
|
||
d.layer_mut("0").unwrap().linetype = "DASHED".into();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
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]);
|
||
}
|
||
|
||
/// A drawing with the layers Defpoints and "Hidden" and the block P: a line along y = 0 on layer
|
||
/// 0, a point at y = 5 and a line along y = 6 on Defpoints, and a line along y = 7 on "Hidden".
|
||
/// The block N holds a dimension that draws P ([`dimension_of_p`]).
|
||
fn drawing_with_p() -> Drawing {
|
||
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 point = cadcraft_doc::Entity::new(Handle(2), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 }));
|
||
point.common.layer = "Defpoints".into();
|
||
let mut d = Drawing::new_metric();
|
||
d.ensure_layer("Defpoints");
|
||
d.ensure_layer("Hidden");
|
||
let mut p = cadcraft_doc::Block::new("P");
|
||
for part in [line(1, 0.0, "0"), point, line(3, 6.0, "Defpoints"), line(4, 7.0, "Hidden")] {
|
||
p.entities.push(part);
|
||
}
|
||
d.blocks.insert("P".into(), std::sync::Arc::new(p));
|
||
let mut n = cadcraft_doc::Block::new("N");
|
||
n.entities.push(cadcraft_doc::Entity::new(Handle(1), dimension_of_p()));
|
||
d.blocks.insert("N".into(), std::sync::Arc::new(n));
|
||
d
|
||
}
|
||
|
||
/// A dimension that draws the block P of [`drawing_with_p`].
|
||
fn dimension_of_p() -> EntityKind {
|
||
EntityKind::Dimension(cadcraft_doc::Dimension {
|
||
kind: cadcraft_doc::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("P".into()),
|
||
insertion_point: Vec3::ZERO,
|
||
overrides: Default::default(),
|
||
assoc: Vec::new(),
|
||
marks: Default::default(),
|
||
})
|
||
}
|
||
|
||
/// Built for a selection through a viewport that freezes the layer Defpoints, a point on that
|
||
/// layer that is a part of a block is kept: in the block a dimension draws, where its definition
|
||
/// points are, in that of a dimension inside a block and in that of a plain reference. The line
|
||
/// on Defpoints in the same block is left out, in a dimension too, like the line on the other
|
||
/// frozen layer. A point on Defpoints that is not a part of a block is left out with its layer,
|
||
/// like every object on a layer the viewport freezes: the rule is about the parts of blocks.
|
||
#[test]
|
||
fn entities_built_for_a_viewport_keep_the_points_on_defpoints_in_a_block() {
|
||
let d = drawing_with_p();
|
||
let reference = |handle: u64, block: &str| {
|
||
cadcraft_doc::Entity::new(Handle(handle), EntityKind::Insert(cadcraft_doc::Insert { block: block.into(), ..Default::default() }))
|
||
};
|
||
let mut loose = cadcraft_doc::Entity::new(Handle(7), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 9.0, 0.0), angle: 0.0 }));
|
||
loose.common.layer = "Defpoints".into();
|
||
let ents = [cadcraft_doc::Entity::new(Handle(4), dimension_of_p()), reference(5, "N"), reference(6, "P"), loose];
|
||
let ys = |l: &DisplayList| -> Vec<f64> { l.prims.iter().map(|p| l.points(p)[0].y).collect() };
|
||
let opts = Options::default();
|
||
let frozen = ["defpoints".to_string(), "Hidden".to_string()];
|
||
assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &frozen)), [0.0, 5.0, 0.0, 5.0, 0.0, 5.0]);
|
||
assert_eq!(ys(&build_entities_in_viewport(&d, &ents, &opts, &[])), [0.0, 5.0, 6.0, 7.0, 0.0, 5.0, 6.0, 7.0, 0.0, 5.0, 6.0, 7.0, 9.0]);
|
||
}
|
||
|
||
/// A layout viewport that freezes the layer Defpoints does not draw the points on it, a part of a
|
||
/// dimension's block or of a reference's: only a selection through the viewport counts them
|
||
/// ([`build_entities_in_viewport`]). A viewport that draws the layer draws them.
|
||
#[test]
|
||
fn a_viewport_that_freezes_defpoints_does_not_draw_the_points_on_it() {
|
||
let drawn = |frozen: &[&str]| -> Vec<f64> {
|
||
let mut d = drawing_with_p();
|
||
d.add(&Space::Model, Common::default(), dimension_of_p()).unwrap();
|
||
let held = cadcraft_doc::Insert { block: "N".into(), insert: Vec3::new(0.0, 10.0, 0.0), ..Default::default() };
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(held)).unwrap();
|
||
let plain = cadcraft_doc::Insert { block: "P".into(), insert: Vec3::new(0.0, 20.0, 0.0), ..Default::default() };
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(plain)).unwrap();
|
||
// The viewport shows model space at 1:1 around (5, 15), so paper and model coordinates
|
||
// are the same.
|
||
let mut v = vp(Vec2::new(5.0, 15.0), 60.0, 60.0, Vec2::new(5.0, 15.0), 60.0, 2);
|
||
v.frozen_layers = frozen.iter().map(|layer| layer.to_string()).collect();
|
||
let paper = Space::Paper("Layout1".into());
|
||
d.add(&paper, Common::default(), EntityKind::Viewport(v)).unwrap();
|
||
viewport_points(&build(&d, &paper, &Options::default())).iter().map(|p| p[0].y).collect()
|
||
};
|
||
assert_eq!(drawn(&["defpoints"]), [0.0, 7.0, 10.0, 17.0, 20.0, 27.0]);
|
||
assert_eq!(drawn(&[]), [0.0, 5.0, 6.0, 7.0, 10.0, 15.0, 16.0, 17.0, 20.0, 25.0, 26.0, 27.0]);
|
||
}
|
||
|
||
#[test]
|
||
fn frozen_layer_hidden() {
|
||
let mut d = sample();
|
||
d.layer_mut("0").unwrap().frozen = true;
|
||
assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn text_produces_strokes() {
|
||
let mut d = Drawing::new_imperial();
|
||
d.add(
|
||
&Space::Model,
|
||
Common::default(),
|
||
EntityKind::Text(cadcraft_doc::Text {
|
||
insert: Vec3::ZERO,
|
||
align_pt: None,
|
||
height: 1.0,
|
||
value: "CAD".into(),
|
||
rotation: 0.0,
|
||
width_factor: 1.0,
|
||
oblique: 0.0,
|
||
style: "Standard".into(),
|
||
halign: Default::default(),
|
||
valign: Default::default(),
|
||
backwards: false,
|
||
upside_down: false,
|
||
}),
|
||
)
|
||
.unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert!(l.prims.len() >= 3);
|
||
}
|
||
|
||
/// What is drawn of one TEXT whose two points are `span` apart, and the drawing's extents.
|
||
fn drawn_and_extents(
|
||
halign: cadcraft_doc::HAlign,
|
||
value: &str,
|
||
height: f64,
|
||
width_factor: f64,
|
||
span: f64,
|
||
) -> (cadcraft_geom::Bounds2, cadcraft_geom::Bounds2) {
|
||
drawn_and_extents_at(halign, Default::default(), value, height, width_factor, span, (false, false))
|
||
}
|
||
|
||
/// The same for a vertical justification and the text's generation flags (backwards, upside down).
|
||
fn drawn_and_extents_at(
|
||
halign: cadcraft_doc::HAlign,
|
||
valign: cadcraft_doc::VAlign,
|
||
value: &str,
|
||
height: f64,
|
||
width_factor: f64,
|
||
span: f64,
|
||
(backwards, upside_down): (bool, bool),
|
||
) -> (cadcraft_geom::Bounds2, cadcraft_geom::Bounds2) {
|
||
let mut d = Drawing::new_imperial();
|
||
let text = cadcraft_doc::Text {
|
||
insert: Vec3::ZERO,
|
||
align_pt: Some(Vec3::new(span, 0.0, 0.0)),
|
||
height,
|
||
value: value.into(),
|
||
rotation: 0.0,
|
||
width_factor,
|
||
oblique: 0.0,
|
||
style: "Standard".into(),
|
||
halign,
|
||
valign,
|
||
backwards,
|
||
upside_down,
|
||
};
|
||
d.add(&Space::Model, Common::default(), EntityKind::Text(text)).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
let drawn = cadcraft_geom::Bounds2::from_points(l.prims.iter().flat_map(|p| l.points(p).iter().copied()));
|
||
assert!(!drawn.is_empty(), "{value:?} over {span}: the text is drawn");
|
||
(drawn, d.extents(&Space::Model))
|
||
}
|
||
|
||
/// Fit text whose two points are so close that the fitted width factor is too small to shape
|
||
/// is drawn unstretched, far wider than the span between its points: the drawing's extents hold
|
||
/// what is drawn, as they do for the same text fitted over a span it can be stretched to.
|
||
#[test]
|
||
fn fit_text_extents_hold_the_drawn_text_when_the_span_is_too_short_to_fit() {
|
||
for span in [1e-7, 10.0] {
|
||
let (drawn, extents) = drawn_and_extents(cadcraft_doc::HAlign::Fit, "AB", 1.0, 1.0, span);
|
||
let slack = 1e-6;
|
||
assert!(
|
||
drawn.min.x >= extents.min.x - slack
|
||
&& drawn.max.x <= extents.max.x + slack
|
||
&& drawn.min.y >= extents.min.y - slack
|
||
&& drawn.max.y <= extents.max.y + slack,
|
||
"span {span}: drawn {drawn:?} outside extents {extents:?}"
|
||
);
|
||
}
|
||
// The short span is the case the fitted factor falls back in: the text is wider than its span.
|
||
assert!(drawn_and_extents(cadcraft_doc::HAlign::Fit, "AB", 1.0, 1.0, 1e-7).0.width() > 1e-7 * 1000.0);
|
||
}
|
||
|
||
/// Backwards and upside-down text over two points is mirrored about its first point, along the
|
||
/// line through both. The drawing's extents are mirrored the same way: they are the plain text's
|
||
/// extents reflected, as what is drawn is the plain text reflected.
|
||
#[test]
|
||
fn mirrored_aligned_and_fit_text_extents_follow_the_drawn_text() {
|
||
use cadcraft_doc::HAlign::{Aligned, Fit};
|
||
use cadcraft_geom::{Bounds2, Vec2};
|
||
let near = |a: Bounds2, b: Bounds2| a.min.dist(b.min) < 1e-9 && a.max.dist(b.max) < 1e-9;
|
||
for halign in [Aligned, Fit] {
|
||
// The first point is the origin and the second is at +x.
|
||
let (plain_drawn, plain_extents) = drawn_and_extents(halign, "AB", 1.0, 1.0, 10.0);
|
||
assert!(plain_drawn.min.x > -1e-9 && plain_drawn.max.y > 0.5, "{halign:?}: drawn {plain_drawn:?}");
|
||
for flags in [(true, false), (false, true), (true, true)] {
|
||
let (mx, my) = (if flags.0 { -1.0 } else { 1.0 }, if flags.1 { -1.0 } else { 1.0 });
|
||
let reflect = |b: Bounds2| Bounds2::from_points([b.min, b.max].map(|p| Vec2::new(p.x * mx, p.y * my)));
|
||
let (drawn, extents) = drawn_and_extents_at(halign, Default::default(), "AB", 1.0, 1.0, 10.0, flags);
|
||
assert!(near(drawn, reflect(plain_drawn)), "{halign:?} {flags:?}: drawn {drawn:?}, plain {plain_drawn:?}");
|
||
assert!(near(extents, reflect(plain_extents)), "{halign:?} {flags:?}: extents {extents:?}, plain {plain_extents:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The extents estimate a line's width where the fonts measure it, so near the fonts' cutoffs
|
||
/// the two could decide differently. The extents then take the larger outcome, and stay near
|
||
/// what is drawn in each of these cases.
|
||
#[test]
|
||
fn aligned_and_fit_text_extents_stay_near_the_drawn_text_at_the_cutoffs() {
|
||
use cadcraft_doc::HAlign::{Aligned, Fit};
|
||
// Wide letters over a span just where the fitted factor reaches the cutoff: the estimate says
|
||
// the text is stretched, the fonts draw it unstretched, a million times wider than its span.
|
||
let (drawn, extents) = drawn_and_extents(Fit, "AAAAAAAAA", 1.0, 1.0, 8.12e-6);
|
||
assert!(drawn.width() > 1.0, "drawn unstretched: {drawn:?}");
|
||
assert!(extents.width() > drawn.width() * 0.9, "drawn {drawn:?}, extents {extents:?}");
|
||
// A narrow letter shrunk into a short span by Aligned stays about as tall as it was.
|
||
let (drawn, extents) = drawn_and_extents(Aligned, "I", 1.0, 1.0, 1.0 / 3.0);
|
||
assert!(extents.max.y >= drawn.max.y - 1e-6, "drawn {drawn:?}, extents {extents:?}");
|
||
// A line of next to no width is left as it is: the extents do not reach for the second point.
|
||
for halign in [Aligned, Fit] {
|
||
let (drawn, extents) = drawn_and_extents(halign, "I", 1e-8, 1e-5, 10.0);
|
||
assert!(drawn.width() < 1e-3 && drawn.height() < 1e-3, "{halign:?}: drawn as it is: {drawn:?}");
|
||
assert!(extents.width() < 1e-3 && extents.height() < 1e-3, "{halign:?}: extents {extents:?}");
|
||
}
|
||
}
|
||
|
||
/// Aligned text is as tall as its span makes it, and narrow letters over a long span are drawn far
|
||
/// taller than their own height: the extents hold them, without growing out of proportion for
|
||
/// wide letters.
|
||
#[test]
|
||
fn aligned_text_extents_hold_narrow_letters_stretched_over_a_long_span() {
|
||
// The last two are control codes: toggles that draw nothing around "AB", and two symbols.
|
||
for value in ["I", "IIII", "W", "WWWW", "AB", "%%uAB%%u", "%%c%%d"] {
|
||
let (drawn, extents) = drawn_and_extents(cadcraft_doc::HAlign::Aligned, value, 1.0, 1.0, 20.0);
|
||
assert!(drawn.height() > 1.0, "{value:?}: stretched taller than its own height: {drawn:?}");
|
||
assert!(extents.max.y >= drawn.max.y - 1e-6, "{value:?}: drawn {drawn:?} above extents {extents:?}");
|
||
assert!(extents.height() < drawn.height() * 5.0, "{value:?}: drawn {drawn:?}, extents {extents:?}");
|
||
}
|
||
}
|
||
|
||
/// The fitted height also sets how far a vertical justification moves Aligned text, and the box
|
||
/// does not know that height exactly: it holds the text from its lowest possible bottom to its
|
||
/// highest possible top, whichever way it is justified.
|
||
#[test]
|
||
fn aligned_text_extents_hold_the_text_at_every_vertical_justification() {
|
||
use cadcraft_doc::VAlign::{Baseline, Bottom, Middle, Top};
|
||
for valign in [Baseline, Bottom, Middle, Top] {
|
||
for value in ["I", "W", "WWWW"] {
|
||
// Plain, and mirrored each way about the point the text is placed by.
|
||
for flags in [(false, false), (true, false), (false, true), (true, true)] {
|
||
let (drawn, extents) = drawn_and_extents_at(cadcraft_doc::HAlign::Aligned, valign, value, 1.0, 1.0, 20.0, flags);
|
||
assert!(
|
||
extents.min.y <= drawn.min.y + 1e-6 && extents.max.y >= drawn.max.y - 1e-6,
|
||
"{valign:?} {value:?} {flags:?}: drawn {drawn:?} outside extents {extents:?}"
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Text of next to no width is left as it is by the fonts, neither stretched nor scaled, and its
|
||
/// extents stay its own size: they follow the fonts' own cutoff.
|
||
#[test]
|
||
fn unfitted_text_of_next_to_no_width_keeps_extents_of_its_own_size() {
|
||
for halign in [cadcraft_doc::HAlign::Aligned, cadcraft_doc::HAlign::Fit] {
|
||
let (drawn, extents) = drawn_and_extents(halign, "I", 1e-7, 1e-5, 10.0);
|
||
assert!(drawn.width() < 1e-3 && drawn.height() < 1e-3, "{halign:?}: drawn as it is: {drawn:?}");
|
||
assert!(extents.width() < 1e-3 && extents.height() < 1e-3, "{halign:?}: extents {extents:?}");
|
||
}
|
||
}
|
||
|
||
/// A value of nothing but underline and overline toggles draws nothing and has no extents: not
|
||
/// those of one character, which Aligned text would stretch over its span.
|
||
#[test]
|
||
fn text_that_draws_nothing_has_no_extents() {
|
||
use cadcraft_doc::HAlign::{Aligned, Fit, Left};
|
||
for halign in [Left, Aligned, Fit] {
|
||
for value in ["%%u%%u", "%%o", ""] {
|
||
let mut d = Drawing::new_imperial();
|
||
let text = cadcraft_doc::Text {
|
||
insert: Vec3::ZERO,
|
||
align_pt: Some(Vec3::new(20.0, 0.0, 0.0)),
|
||
height: 1.0,
|
||
value: value.into(),
|
||
rotation: 0.0,
|
||
width_factor: 1.0,
|
||
oblique: 0.0,
|
||
style: "Standard".into(),
|
||
halign,
|
||
valign: Default::default(),
|
||
backwards: false,
|
||
upside_down: false,
|
||
};
|
||
d.add(&Space::Model, Common::default(), EntityKind::Text(text)).unwrap();
|
||
assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty(), "{halign:?} {value:?}: nothing is drawn");
|
||
let extents = d.extents(&Space::Model);
|
||
assert!(extents.is_empty(), "{halign:?} {value:?}: extents {extents:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn hatch_pattern_and_solid() {
|
||
let mut d = Drawing::new_imperial();
|
||
let sq = vec![
|
||
PolyVertex::new(Vec2::new(0.0, 0.0)),
|
||
PolyVertex::new(Vec2::new(4.0, 0.0)),
|
||
PolyVertex::new(Vec2::new(4.0, 4.0)),
|
||
PolyVertex::new(Vec2::new(0.0, 4.0)),
|
||
];
|
||
let h = Hatch {
|
||
pattern: "ANSI31".into(),
|
||
solid: false,
|
||
loops: vec![HatchLoop { vertices: sq.clone(), outer: true, boundary_flags: None, sources: Vec::new() }],
|
||
scale: 1.0,
|
||
angle: 0.0,
|
||
associative: false,
|
||
style: 0,
|
||
elevation: 0.0,
|
||
gradient: None,
|
||
origin: Vec2::ZERO,
|
||
background: None,
|
||
pattern_lines: Vec::new(),
|
||
};
|
||
d.add(&Space::Model, Common::default(), EntityKind::Hatch(h.clone())).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
// 45° lines at 0.125 spacing across a 4x4 square: about 4*sqrt(2)/0.125 ≈ 45 lines.
|
||
assert!(l.prims.len() > 35 && l.prims.len() < 60, "{}", l.prims.len());
|
||
let mut d2 = Drawing::new_imperial();
|
||
d2.add(&Space::Model, Common::default(), EntityKind::Hatch(Hatch { solid: true, pattern: "SOLID".into(), ..h })).unwrap();
|
||
let l2 = build(&d2, &Space::Model, &Options::default());
|
||
assert_eq!(l2.prims.len(), 1);
|
||
assert_eq!(l2.prims[0].kind, Kind::Tris);
|
||
}
|
||
|
||
#[test]
|
||
fn raster_draws_pixels() {
|
||
let d = sample();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
let v = View::fit(&l.bounds, 200, 200, 0.1);
|
||
let pm = render(&l, &v, &RasterOptions::default()).unwrap();
|
||
let bg = pm.pixels().iter().filter(|p| p.red() == 33).count();
|
||
assert!(bg < 200 * 200);
|
||
// A red pixel exists from the circle.
|
||
assert!(pm.pixels().iter().any(|p| p.red() > 200 && p.green() < 60));
|
||
}
|
||
|
||
#[test]
|
||
fn raster_rejects_bad_size() {
|
||
let l = DisplayList::default();
|
||
assert!(render(&l, &View { center: Vec2::ZERO, scale: 1.0, width: 0, height: 10 }, &RasterOptions::default()).is_none());
|
||
}
|
||
|
||
fn layout_with_viewport(vp: cadcraft_doc::Viewport) -> Drawing {
|
||
let mut d = sample(); // line (0,0)-(10,0) and red circle at (5,5) r3
|
||
let paper = Space::Paper("Layout1".into());
|
||
d.add(&paper, Common::default(), EntityKind::Viewport(vp)).unwrap();
|
||
d
|
||
}
|
||
|
||
fn vp(center: Vec2, w: f64, h: f64, view_center: Vec2, view_height: f64, id: u32) -> cadcraft_doc::Viewport {
|
||
cadcraft_doc::Viewport {
|
||
center: center.to3(0.0),
|
||
width: w,
|
||
height: h,
|
||
view_center,
|
||
view_height,
|
||
id,
|
||
locked: false,
|
||
frozen_layers: Vec::new(),
|
||
layer_colors: Vec::new(),
|
||
clip: None,
|
||
on: true,
|
||
twist: 0.0,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn layout_viewport_shows_model_clipped() {
|
||
// Viewport 4x4 paper units centred at (5,4), showing model window centred at (5,5), 8 high:
|
||
// scale 0.5, so model (5,5) → paper (5,4); the visible model window is (1,1)..(9,9).
|
||
let d = layout_with_viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2));
|
||
let l = build(&d, &Space::Paper("Layout1".into()), &Options { tolerance: 0.01, ..Default::default() });
|
||
let sheet = l.sheet.unwrap();
|
||
assert!(sheet.size.x > sheet.size.y, "landscape sheet");
|
||
let rect = Bounds2::new(Vec2::new(3.0, 2.0), Vec2::new(7.0, 6.0)).expand(1e-9);
|
||
let content: Vec<&DPrim> = l.prims.iter().filter(|p| p.handle == VIEWPORT_CONTENT).collect();
|
||
assert!(!content.is_empty(), "model geometry is drawn in the viewport");
|
||
for p in &content {
|
||
for q in l.points(p) {
|
||
assert!(rect.contains(*q), "{q:?} outside the viewport");
|
||
}
|
||
}
|
||
// The circle (red) is visible, scaled by 0.5 about the view centre: radius 1.5 around (5,4).
|
||
let red: Vec<Vec2> = content.iter().filter(|p| p.color == Rgb(255, 0, 0)).flat_map(|p| l.points(p).to_vec()).collect();
|
||
assert!(!red.is_empty());
|
||
assert!(red.iter().all(|q| (q.dist(Vec2::new(5.0, 4.0)) - 1.5).abs() < 0.02));
|
||
// The line y=0 maps to paper y=1.5, below the viewport: clipped away entirely.
|
||
assert!(content.iter().filter(|p| p.color != Rgb(255, 0, 0)).all(|p| l.points(p).iter().all(|q| q.y > 1.9)));
|
||
// The border is drawn with the viewport's own handle.
|
||
assert!(l.prims.iter().any(|p| p.handle != VIEWPORT_CONTENT));
|
||
}
|
||
|
||
#[test]
|
||
fn layout_viewport_frozen_layer_and_id1() {
|
||
let mut v = vp(Vec2::new(5.0, 4.0), 20.0, 20.0, Vec2::new(5.0, 5.0), 20.0, 2);
|
||
v.frozen_layers = vec!["0".into()];
|
||
let d = layout_with_viewport(v);
|
||
let l = build(&d, &Space::Paper("Layout1".into()), &Options::default());
|
||
assert!(l.prims.iter().all(|p| p.handle != VIEWPORT_CONTENT), "layer 0 is frozen in this viewport");
|
||
// Viewport id 1 (the paper-space view) draws nothing.
|
||
let d = layout_with_viewport(vp(Vec2::new(5.0, 4.0), 20.0, 20.0, Vec2::new(5.0, 5.0), 20.0, 1));
|
||
assert!(build(&d, &Space::Paper("Layout1".into()), &Options::default()).prims.is_empty());
|
||
// Model space never draws viewport contents; plotting skips non-plot layers.
|
||
let mut d = sample();
|
||
d.layer_mut("0").unwrap().plot = false;
|
||
assert!(build_plot(&d, &Space::Model, &Options::default()).prims.is_empty());
|
||
assert!(!build(&d, &Space::Model, &Options::default()).prims.is_empty());
|
||
}
|
||
|
||
/// The points of each primitive drawn through a viewport.
|
||
fn viewport_points(l: &DisplayList) -> Vec<Vec<Vec2>> {
|
||
l.prims.iter().filter(|p| p.handle == VIEWPORT_CONTENT).map(|p| l.points(p).to_vec()).collect()
|
||
}
|
||
|
||
#[test]
|
||
fn viewport_contents_can_be_left_out_and_built_for_any_area() {
|
||
let d = layout_with_viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2));
|
||
let paper = Space::Paper("Layout1".into());
|
||
let h = d.space(&paper).unwrap().iter().find(|e| matches!(e.kind, EntityKind::Viewport(_))).unwrap().handle;
|
||
let opts = Options { tolerance: 0.01, ..Default::default() };
|
||
// Left out of the layout: only the border remains.
|
||
let skipped = build(&d, &paper, &Options { skip_viewport: Some(h), ..opts.clone() });
|
||
assert!(viewport_points(&skipped).is_empty());
|
||
assert!(skipped.prims.iter().any(|p| p.handle == h));
|
||
// Built for the viewport's own rectangle: what the layout draws there.
|
||
let rect = Bounds2::new(Vec2::new(3.0, 2.0), Vec2::new(7.0, 6.0));
|
||
let full = build(&d, &paper, &opts);
|
||
assert!(!viewport_points(&full).is_empty());
|
||
assert_eq!(viewport_points(&viewport_content(&d, &paper, h, rect, &opts)), viewport_points(&full));
|
||
// Built for a larger area, clipped to it instead of the viewport: the line y=0 (paper y=1.5,
|
||
// below the viewport) is there.
|
||
let wide = viewport_content(&d, &paper, h, rect.expand(2.0), &opts);
|
||
assert!(viewport_points(&wide).iter().any(|pts| pts.iter().all(|q| (q.y - 1.5).abs() < 1e-9)));
|
||
// Not a viewport, or an empty or non-finite area: nothing.
|
||
assert!(viewport_content(&d, &paper, Handle(0xDEAD), rect, &opts).prims.is_empty());
|
||
assert!(viewport_content(&d, &paper, h, Bounds2::EMPTY, &opts).prims.is_empty());
|
||
let nan = Bounds2::new(Vec2::new(f64::NAN, 0.0), Vec2::new(1.0, 1.0));
|
||
assert!(viewport_content(&d, &paper, h, nan, &opts).prims.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn viewport_contents_built_on_all_cores_match_one_thread() {
|
||
// Enough model objects for the parallel path; plots build on one thread.
|
||
let mut d = layout_with_viewport(vp(Vec2::new(5.0, 4.0), 8.0, 6.0, Vec2::new(30.0, 30.0), 60.0, 2));
|
||
for i in 0..1200 {
|
||
let (x, y) = (f64::from(i % 40) * 1.5, f64::from(i / 40) * 2.0);
|
||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(x, y, 0.0), b: Vec3::new(x + 1.0, y + 1.5, 0.0) });
|
||
d.add(&Space::Model, Common::default(), line).unwrap();
|
||
}
|
||
let paper = Space::Paper("Layout1".into());
|
||
let screen = build(&d, &paper, &Options::default());
|
||
let plot = build_plot(&d, &paper, &Options::default());
|
||
let pts = |l: &DisplayList| -> Vec<Vec<Vec2>> {
|
||
let border: Vec<Handle> = d.space(&paper).unwrap().iter().map(|e| e.handle).collect();
|
||
l.prims.iter().filter(|p| !border.contains(&p.handle)).map(|p| l.points(p).to_vec()).collect()
|
||
};
|
||
assert!(pts(&screen).len() > 1000);
|
||
assert_eq!(pts(&screen), pts(&plot));
|
||
}
|
||
|
||
#[test]
|
||
fn hostile_viewports_do_not_panic() {
|
||
for v in [
|
||
vp(Vec2::new(f64::NAN, 0.0), 1.0, 1.0, Vec2::ZERO, 1.0, 2),
|
||
vp(Vec2::ZERO, -1.0, 1.0, Vec2::ZERO, 1.0, 2),
|
||
vp(Vec2::ZERO, 1.0, 1.0, Vec2::ZERO, 0.0, 2),
|
||
vp(Vec2::ZERO, 1e308, 1e308, Vec2::new(1e308, -1e308), 1e-308, 2),
|
||
vp(Vec2::ZERO, 1.0, 1.0, Vec2::new(f64::INFINITY, 0.0), 1.0, 2),
|
||
] {
|
||
let d = layout_with_viewport(v);
|
||
let _ = build(&d, &Space::Paper("Layout1".into()), &Options::default());
|
||
}
|
||
}
|
||
|
||
fn text_doc(style_font: &str, value: &str) -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
d.text_styles.push(cadcraft_doc::TextStyle { name: "TT".into(), font: style_font.into(), ..Default::default() });
|
||
d.add(
|
||
&Space::Model,
|
||
Common::default(),
|
||
EntityKind::Text(cadcraft_doc::Text {
|
||
insert: Vec3::ZERO,
|
||
align_pt: None,
|
||
height: 1.0,
|
||
value: value.into(),
|
||
rotation: 0.0,
|
||
width_factor: 1.0,
|
||
oblique: 0.0,
|
||
style: "TT".into(),
|
||
halign: Default::default(),
|
||
valign: Default::default(),
|
||
backwards: false,
|
||
upside_down: false,
|
||
}),
|
||
)
|
||
.unwrap();
|
||
d
|
||
}
|
||
|
||
/// The first common system TrueType font, if any is installed (tests skip otherwise).
|
||
fn system_font() -> Option<&'static str> {
|
||
["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find(|n| cadcraft_fonts::ttf::find(n).is_some())
|
||
}
|
||
|
||
/// #666: on screen, filled glyphs outside the area being looked at are left out (the canvas
|
||
/// builds again when the view leaves it); plots and builds without a view keep every glyph.
|
||
#[test]
|
||
fn glyphs_outside_the_view_are_left_out_of_screen_builds_only() {
|
||
let Some(font) = system_font() else { return };
|
||
let d = text_doc(font, "OH");
|
||
let tris = |o: &Options| build(&d, &Space::Model, o).prims.iter().filter(|p| p.kind == Kind::Tris).count();
|
||
let all = tris(&Options::default());
|
||
assert!(all > 0);
|
||
let near = Options { view: Some(Bounds2::new(Vec2::new(-1.0, -1.0), Vec2::new(3.0, 2.0))), ..Options::default() };
|
||
assert_eq!(tris(&near), all, "a view over the text keeps it");
|
||
let far = Options { view: Some(Bounds2::new(Vec2::new(100.0, 100.0), Vec2::new(110.0, 110.0))), ..Options::default() };
|
||
assert_eq!(tris(&far), 0, "a view far from the text leaves its glyphs out");
|
||
let plot = build_plot(&d, &Space::Model, &far);
|
||
assert_eq!(plot.prims.iter().filter(|p| p.kind == Kind::Tris).count(), all, "plots keep every glyph");
|
||
}
|
||
|
||
// ---------- a fixture TrueType font: no font file, no installed font ----------
|
||
|
||
/// A closed ellipse round (500, 350), wound by `clockwise`: one contour of a glyph outline.
|
||
fn ring(rx: f64, ry: f64, points: usize, clockwise: bool) -> Vec<(i16, i16)> {
|
||
let dir = if clockwise { -1.0 } else { 1.0 };
|
||
(0..points)
|
||
.map(|i| {
|
||
(
|
||
(500.0 + rx * (dir * std::f64::consts::TAU * i as f64 / points as f64).cos()) as i16,
|
||
(350.0 + ry * (dir * std::f64::consts::TAU * i as f64 / points as f64).sin()) as i16,
|
||
)
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
/// A TrueType font whose only glyph, "O", is a 128-point ring: the flattened outline a real font's
|
||
/// curve gives, at the same scale, with plenty of detail to simplify. It is built in code so the
|
||
/// level-of-detail test needs no installed font and no font file in the repository (#651).
|
||
fn fixture_font() -> &'static str {
|
||
const NAME: &str = "cadcraft-render-lod.ttf";
|
||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||
ONCE.call_once(|| cadcraft_fonts::ttf::register(NAME, fixture_font_bytes()));
|
||
NAME
|
||
}
|
||
|
||
fn fixture_font_bytes() -> Vec<u8> {
|
||
sfnt::bytes(&sfnt::Sfnt {
|
||
// Glyph 1 is "O": a 128-point ring, its counter a second, oppositely wound contour.
|
||
glyphs: &[sfnt::notdef(), sfnt::glyph(&[ring(500.0, 350.0, 128, false), ring(250.0, 150.0, 128, true)])],
|
||
cmap: &[(0x4F, 0x4F, 1 - 0x4F)], // "O" → glyph 1
|
||
advance: 1000, // one em wide
|
||
lsb: 0,
|
||
metrics: 2, // hmtx matches the two metrics hhea declares
|
||
fs_type: 0, // any use
|
||
ink_box: [0, 0, 1000, 700], // the ring's box; the 700-unit cap height is the unit scale
|
||
})
|
||
}
|
||
|
||
#[test]
|
||
fn truetype_text_is_filled_or_outlined() {
|
||
let Some(font) = system_font() else { return };
|
||
let mut d = text_doc(font, "OH");
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert!(l.prims.iter().any(|p| p.kind == Kind::Tris), "TEXTFILL=1 fills glyphs");
|
||
// The O's counter is a hole: filled area is well below the glyph box area.
|
||
let area: f64 = l
|
||
.prims
|
||
.iter()
|
||
.filter(|p| p.kind == Kind::Tris)
|
||
.flat_map(|p| l.points(p).chunks(3).map(|t| ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs()).collect::<Vec<_>>())
|
||
.sum();
|
||
assert!(area > 0.1 && area < l.bounds.width() * l.bounds.height() * 0.8, "area {area}");
|
||
assert!((l.bounds.max.y - 1.0).abs() < 0.1, "cap height = text height");
|
||
d.header.set_i64("TEXTFILL", 0);
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert!(l.prims.iter().all(|p| p.kind == Kind::Polyline), "TEXTFILL=0 outlines");
|
||
assert!(l.prims.len() >= 3, "O has two contours, H one");
|
||
}
|
||
|
||
// Regression test for #651: filled TrueType text was triangulated at full outline detail at every
|
||
// zoom, so a page of small text on screen produced millions of triangles and froze the canvas.
|
||
#[test]
|
||
fn small_filled_text_on_screen_is_simplified_but_plots_keep_full_detail() {
|
||
let d = text_doc(fixture_font(), "OOOO");
|
||
let tris = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Tris).map(|p| l.points(p).len() / 3).sum::<usize>();
|
||
let plot = build_plot(&d, &Space::Model, &Options::default());
|
||
let full = tris(&plot);
|
||
assert!(full > 100, "a plot keeps every point of the 128-point rings: {full} triangles");
|
||
// One pixel is a tenth of the cap height: the rings are simplified to a few points, the shapes
|
||
// stay.
|
||
let reduced = build(&d, &Space::Model, &screen(0.1, None));
|
||
assert!(tris(&reduced) < full / 2, "{} triangles at 10 px per cap height, {full} in a plot", tris(&reduced));
|
||
assert!(tris(&reduced) > 0 && reduced.bounds.width() > plot.bounds.width() * 0.9, "{:?} vs {:?}", reduced.bounds, plot.bounds);
|
||
// An em under two pixels is drawn as the ink's box: two triangles a glyph, same extent.
|
||
let tiny = build(&d, &Space::Model, &screen(2.0, None));
|
||
assert_eq!(tris(&tiny), 2 * 4, "one box per glyph");
|
||
assert!(
|
||
tiny.bounds.width() > plot.bounds.width() * 0.9 && tiny.bounds.height() > plot.bounds.height() * 0.9,
|
||
"{:?} vs {:?}",
|
||
tiny.bounds,
|
||
plot.bounds
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn missing_font_falls_back_to_stroke() {
|
||
let d = text_doc("NoSuchFontAnywhere.ttf", "OH");
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert!(!l.prims.is_empty() && l.prims.iter().all(|p| p.kind == Kind::Polyline));
|
||
}
|
||
|
||
#[test]
|
||
fn backwards_and_upside_down_mirror_text() {
|
||
let mut d = text_doc("CADCraft Stroke", "ABC");
|
||
let normal = build(&d, &Space::Model, &Options::default()).bounds;
|
||
assert!(normal.min.x >= -1e-9 && normal.min.y >= -1e-9);
|
||
// The text's own flags (DXF 71) mirror it, as AutoCAD's do; its style's are what new text
|
||
// starts with and don't change it.
|
||
let set = |d: &mut Drawing, backwards: bool, upside_down: bool| {
|
||
let h = d.model.iter().next().map(|e| e.handle).unwrap();
|
||
d.modify_entity(h, |e| {
|
||
if let EntityKind::Text(t) = &mut e.kind {
|
||
t.backwards = backwards;
|
||
t.upside_down = upside_down;
|
||
}
|
||
})
|
||
.unwrap();
|
||
};
|
||
d.text_styles.iter_mut().for_each(|s| s.backwards = true);
|
||
let styled = build(&d, &Space::Model, &Options::default()).bounds;
|
||
assert!((styled.min.x - normal.min.x).abs() < 1e-9, "the style's flag doesn't mirror existing text");
|
||
set(&mut d, true, false);
|
||
let back = build(&d, &Space::Model, &Options::default()).bounds;
|
||
assert!(back.max.x <= 1e-9 && (back.width() - normal.width()).abs() < 1e-9, "mirrored to the left");
|
||
set(&mut d, false, true);
|
||
let up = build(&d, &Space::Model, &Options::default()).bounds;
|
||
assert!(up.max.y <= 1e-9 && up.min.y < -0.9, "mirrored below the baseline");
|
||
}
|
||
|
||
#[test]
|
||
fn truetype_mtext_and_dimension_text() {
|
||
let Some(font) = system_font() else { return };
|
||
let mut d = Drawing::new_imperial();
|
||
d.text_styles.iter_mut().for_each(|s| s.font = font.into());
|
||
d.add(
|
||
&Space::Model,
|
||
Common::default(),
|
||
EntityKind::MText(cadcraft_doc::MText {
|
||
insert: Vec3::ZERO,
|
||
height: 1.0,
|
||
width: 0.0,
|
||
attach: 1,
|
||
rotation: 0.0,
|
||
style: "Standard".into(),
|
||
contents: "A{\\C1;B}\\P\\S1/2;".into(),
|
||
line_spacing: 1.0,
|
||
line_spacing_exact: false,
|
||
columns: None,
|
||
}),
|
||
)
|
||
.unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert!(l.prims.iter().any(|p| p.kind == Kind::Tris && p.color == Rgb(255, 0, 0)), "red B");
|
||
assert!(l.prims.iter().any(|p| p.kind == Kind::Tris && p.color != Rgb(255, 0, 0)));
|
||
let mut d = Drawing::new_imperial();
|
||
d.text_styles.iter_mut().for_each(|s| s.font = font.into());
|
||
d.add(&Space::Model, Common::default(), EntityKind::Dimension(lin_dim())).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert!(l.prims.iter().filter(|p| p.kind == Kind::Tris).count() > 2, "arrows plus filled glyphs");
|
||
}
|
||
|
||
fn lin_dim() -> cadcraft_doc::Dimension {
|
||
cadcraft_doc::Dimension {
|
||
kind: cadcraft_doc::DimKind::Linear { rotation: 0.0 },
|
||
defpt: Vec3::new(0.0, 2.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: None,
|
||
overrides: Default::default(),
|
||
assoc: Vec::new(),
|
||
marks: Default::default(),
|
||
insertion_point: Vec3::ZERO,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn dimension_colours_by_role() {
|
||
let mut d = Drawing::new_imperial();
|
||
if let Some(st) = d.dim_styles.first_mut() {
|
||
st.dim_line_color = Color::Index(1);
|
||
st.ext_line_color = Color::Index(3);
|
||
st.text_color = Color::Index(5);
|
||
}
|
||
d.add(&Space::Model, Common::default(), EntityKind::Dimension(lin_dim())).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
let has = |c: Rgb, k: Kind| l.prims.iter().any(|p| p.color == c && p.kind == k);
|
||
assert!(has(Rgb(255, 0, 0), Kind::Polyline) && has(Rgb(255, 0, 0), Kind::Tris), "dimension line and arrows red");
|
||
assert!(has(Rgb(0, 255, 0), Kind::Polyline), "extension lines green");
|
||
assert!(has(Rgb(0, 0, 255), Kind::Polyline), "text blue");
|
||
// ByBlock (the default) takes the dimension's own colour.
|
||
let mut d = Drawing::new_imperial();
|
||
d.add(&Space::Model, Common { color: Color::Index(6), ..Default::default() }, EntityKind::Dimension(lin_dim())).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert!(l.prims.iter().all(|p| p.color == Rgb(255, 0, 255)));
|
||
}
|
||
|
||
#[test]
|
||
fn table_title_is_centred_and_merged() {
|
||
let mut d = Drawing::new_imperial();
|
||
let cell = |t: &str| cadcraft_doc::TableCell { text: t.into(), ..Default::default() };
|
||
let mut title = vec![cell("TITLE"), cell(""), cell("")];
|
||
title[0].merged = Some((1, 3));
|
||
let t = cadcraft_doc::Table {
|
||
insert: Vec3::new(0.0, 0.0, 0.0),
|
||
col_widths: vec![2.0, 2.0, 2.0],
|
||
row_heights: vec![1.0, 1.0],
|
||
cells: vec![title, vec![cell("a"), cell("b"), cell("c")]],
|
||
style: "Standard".into(),
|
||
text_height: 0.2,
|
||
title: true,
|
||
header: false,
|
||
..Default::default()
|
||
};
|
||
d.add(&Space::Model, Common::default(), EntityKind::Table(t)).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
// No vertical cell borders cross the merged title row (y in 0..-1) except the outer ones.
|
||
let inner_vertical_in_title = l.prims.iter().filter(|p| p.kind == Kind::Polyline).any(|p| {
|
||
l.points(p).windows(2).any(|w| {
|
||
(w[0].x - w[1].x).abs() < 1e-12
|
||
&& (w[0].y - w[1].y).abs() > 0.5
|
||
&& w[0].x > 0.1
|
||
&& w[0].x < 5.9
|
||
&& w[0].y.max(w[1].y) > -0.99
|
||
&& w[0].y.min(w[1].y) < -0.01
|
||
})
|
||
});
|
||
assert!(!inner_vertical_in_title);
|
||
// Title text centred on the table width.
|
||
let text: Vec<Vec2> = l
|
||
.prims
|
||
.iter()
|
||
.filter(|p| p.kind == Kind::Polyline)
|
||
.flat_map(|p| l.points(p).to_vec())
|
||
.filter(|q| q.y > -0.95 && q.y < -0.05 && q.x > 0.05 && q.x < 5.95)
|
||
.collect();
|
||
let b = Bounds2::from_points(text);
|
||
assert!((b.center().x - 3.0).abs() < 0.05, "{b:?}");
|
||
}
|
||
|
||
// ---------- hatch level of detail (on-screen builds, issue #544) ----------
|
||
|
||
fn pattern_hatch(pattern: &str, scale: f64, (x0, y0, x1, y1): (f64, f64, f64, f64)) -> Hatch {
|
||
let sq = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y)));
|
||
Hatch {
|
||
pattern: pattern.into(),
|
||
solid: false,
|
||
loops: vec![HatchLoop { vertices: sq.to_vec(), outer: true, boundary_flags: None, sources: Vec::new() }],
|
||
scale,
|
||
angle: 0.0,
|
||
associative: false,
|
||
style: 0,
|
||
elevation: 0.0,
|
||
gradient: None,
|
||
origin: Vec2::ZERO,
|
||
background: None,
|
||
pattern_lines: Vec::new(),
|
||
}
|
||
}
|
||
|
||
fn drawing_with(h: Hatch) -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
d.add(&Space::Model, Common::default(), EntityKind::Hatch(h)).unwrap();
|
||
d
|
||
}
|
||
|
||
fn loops_of(h: &Hatch) -> Vec<Vec<Vec2>> {
|
||
crate::hatch::fill_loops(h, 0.001)
|
||
}
|
||
|
||
/// On-screen options for a view where one pixel is `px` drawing units.
|
||
fn screen(px: f64, view: Option<Bounds2>) -> Options {
|
||
Options { tolerance: px / 2.0, min_dash: px * 2.0, view, ..Default::default() }
|
||
}
|
||
|
||
#[test]
|
||
fn dense_hatch_on_screen_is_one_solid_fill() {
|
||
// ANSI31 at scale 0.01: lines 0.00125 apart over a 4x4 square. On a 1000 px view of it a
|
||
// pixel is 0.004, so the lines run together: one solid fill. Plots keep every line.
|
||
let d = drawing_with(pattern_hatch("ANSI31", 0.01, (0.0, 0.0, 4.0, 4.0)));
|
||
let plot = build(&d, &Space::Model, &Options::default());
|
||
assert!(plot.prims.len() > 4000, "plots keep every line: {}", plot.prims.len());
|
||
let l = build(&d, &Space::Model, &screen(0.004, None));
|
||
assert_eq!(l.prims.len(), 1);
|
||
assert_eq!(l.prims[0].kind, Kind::Tris);
|
||
}
|
||
|
||
#[test]
|
||
fn sparse_dots_keep_their_look_when_lines_are_close() {
|
||
// Dot rows half a pixel apart but dots five pixels apart along them: not solid colour.
|
||
let fam = |dashes: &[f64]| cadcraft_doc::library::PatternLine { angle: 0.0, origin: (0.0, 0.0), delta: (0.0, 0.5), dashes: dashes.to_vec() };
|
||
let sparse = Hatch { pattern_lines: vec![fam(&[0.0, -5.0])], ..pattern_hatch("MYDOTS", 1.0, (0.0, 0.0, 40.0, 40.0)) };
|
||
assert!(!crate::hatch::reads_solid(&cadcraft_doc::Drawing::new_imperial(), &sparse, 1.0));
|
||
// Dots closer than a pixel along rows closer than a pixel: solid.
|
||
let dense = Hatch { pattern_lines: vec![fam(&[0.0, -0.5])], ..sparse.clone() };
|
||
assert!(crate::hatch::reads_solid(&cadcraft_doc::Drawing::new_imperial(), &dense, 1.0));
|
||
// A family with only gaps draws nothing, so it never reads as solid.
|
||
let blank = Hatch { pattern_lines: vec![fam(&[-0.5])], ..sparse.clone() };
|
||
assert!(!crate::hatch::reads_solid(&cadcraft_doc::Drawing::new_imperial(), &blank, 1.0));
|
||
assert!(crate::hatch::pattern_lines(&cadcraft_doc::Drawing::new_imperial(), &blank, &loops_of(&blank), 1.0, None).is_empty());
|
||
// Full detail is never solid.
|
||
assert!(!crate::hatch::reads_solid(&cadcraft_doc::Drawing::new_imperial(), &dense, 0.0));
|
||
}
|
||
|
||
#[test]
|
||
fn scattered_dot_pattern_reads_solid_once_dots_fill_the_pixels() {
|
||
// AR-SAND at scale 3/16 (the library pattern is drawn 16x coarser since #643, so this is the
|
||
// geometry of the old scale 3): three dot families, no single one dense enough on its own at
|
||
// 0.5 per pixel, but together about four dots on every pixel. Zoomed in 4x the dots stand apart.
|
||
let h = pattern_hatch("AR-SAND", 3.0 / 16.0, (0.0, 0.0, 100.0, 100.0));
|
||
assert!(crate::hatch::reads_solid(&cadcraft_doc::Drawing::new_imperial(), &h, 0.5));
|
||
assert!(!crate::hatch::reads_solid(&cadcraft_doc::Drawing::new_imperial(), &h, 0.125));
|
||
}
|
||
|
||
/// Same polylines up to float noise: the view-limited path rotates into the family frame and back,
|
||
/// so a start point can differ by ~1e-16 between platforms (#804). Structure must match exactly.
|
||
fn assert_lines_close(a: &[Vec<Vec2>], b: &[Vec<Vec2>], what: &str) {
|
||
assert_eq!(a.len(), b.len(), "{what}: line count");
|
||
for (i, (ra, rb)) in a.iter().zip(b).enumerate() {
|
||
assert_eq!(ra.len(), rb.len(), "{what}: run {i} length");
|
||
for (pa, pb) in ra.iter().zip(rb) {
|
||
assert!((pa.x - pb.x).abs() < 1e-9 && (pa.y - pb.y).abs() < 1e-9, "{what}: run {i}: {pa:?} vs {pb:?}");
|
||
}
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn normal_zoom_pattern_is_unchanged() {
|
||
// Lines and dash repeats a few pixels long or more: the level of detail changes nothing.
|
||
for (pattern, px) in [("ANSI31", 0.05), ("ANSI33", 0.05), ("AR-CONC", 0.02), ("AR-SAND", 0.01), ("DOTS", 0.01)] {
|
||
let h = pattern_hatch(pattern, 1.0, (0.0, 0.0, 6.0, 4.0));
|
||
let loops = loops_of(&h);
|
||
let full = crate::hatch::pattern_lines(&cadcraft_doc::Drawing::new_imperial(), &h, &loops, 0.0, None);
|
||
assert!(!full.is_empty(), "{pattern}");
|
||
assert!(!crate::hatch::reads_solid(&cadcraft_doc::Drawing::new_imperial(), &h, px), "{pattern}");
|
||
let same_res = crate::hatch::pattern_lines(&cadcraft_doc::Drawing::new_imperial(), &h, &loops, px, None);
|
||
assert_lines_close(&same_res, &full, pattern);
|
||
// A view covering the whole hatch changes nothing either.
|
||
let all = Bounds2::new(Vec2::new(-1.0, -1.0), Vec2::new(7.0, 5.0));
|
||
let in_view = crate::hatch::pattern_lines(&cadcraft_doc::Drawing::new_imperial(), &h, &loops, px, Some(&all));
|
||
assert_lines_close(&in_view, &full, pattern);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn dash_repeat_under_two_pixels_is_one_run() {
|
||
// ANSI33's dashed family repeats every 0.1875: at 0.1 per pixel it reads as a continuous line,
|
||
// drawn as one run per span covering the same length as the full-detail span.
|
||
let h = pattern_hatch("ANSI33", 1.0, (0.0, 0.0, 6.0, 4.0));
|
||
let loops = loops_of(&h);
|
||
let full = crate::hatch::pattern_lines(&cadcraft_doc::Drawing::new_imperial(), &h, &loops, 0.0, None);
|
||
let lod = crate::hatch::pattern_lines(&cadcraft_doc::Drawing::new_imperial(), &h, &loops, 0.1, None);
|
||
assert!(lod.len() < full.len(), "{} vs {}", lod.len(), full.len());
|
||
assert!(lod.iter().all(|r| r.len() == 2));
|
||
// The continuous family: identical runs in both.
|
||
let solid_runs = |v: &[Vec<Vec2>]| v.iter().filter(|r| r.len() == 2).count();
|
||
assert!(solid_runs(&lod) > 0 && solid_runs(&full) > solid_runs(&lod));
|
||
}
|
||
|
||
#[test]
|
||
fn hatch_pattern_only_inside_the_view() {
|
||
// A 40x40 ANSI31 hatch looked at through a 2x2 view in a corner, at full pixel detail.
|
||
let d = drawing_with(pattern_hatch("ANSI31", 1.0, (0.0, 0.0, 40.0, 40.0)));
|
||
let full = build(&d, &Space::Model, &Options::default());
|
||
let far = Some(Bounds2::new(Vec2::new(100.0, 100.0), Vec2::new(110.0, 110.0)));
|
||
assert_eq!(build(&d, &Space::Model, &Options { view: far, ..Default::default() }).prims.len(), 0);
|
||
let corner = Bounds2::new(Vec2::new(0.0, 0.0), Vec2::new(2.0, 2.0));
|
||
let part = build(&d, &Space::Model, &Options { view: Some(corner), ..Default::default() });
|
||
assert!(!part.prims.is_empty() && part.prims.len() * 10 < full.prims.len(), "{} of {}", part.prims.len(), full.prims.len());
|
||
// Runs are cut in the family's rotated frame: a 2x2 view at 45° reaches 1 unit out, plus one
|
||
// line spacing (0.125 × √2 along an axis) from rounding the line range outwards.
|
||
let near = corner.expand(1.0 + 0.125 * 2f64.sqrt() + 1e-9);
|
||
assert!(part.verts.iter().all(|p| near.contains(*p)));
|
||
// Nothing is lost inside the view: the drawn length within an inner box is the same.
|
||
let inner = Bounds2::new(Vec2::new(0.2, 0.2), Vec2::new(1.8, 1.8));
|
||
let (a, b) = (length_inside(&full, &inner), length_inside(&part, &inner));
|
||
assert!(a > 1.0 && (a - b).abs() < 1e-9, "{a} vs {b}");
|
||
}
|
||
|
||
/// Total length of a display list's polylines inside an axis-aligned box (Liang–Barsky).
|
||
fn length_inside(l: &DisplayList, bx: &Bounds2) -> f64 {
|
||
let mut total = 0.0;
|
||
for p in l.prims.iter().filter(|p| p.kind == Kind::Polyline) {
|
||
for w in l.points(p).windows(2) {
|
||
let (p0, d) = (w[0], w[1] - w[0]);
|
||
let (mut t0, mut t1) = (0.0f64, 1.0f64);
|
||
let mut ok = true;
|
||
for (pp, q) in [(-d.x, p0.x - bx.min.x), (d.x, bx.max.x - p0.x), (-d.y, p0.y - bx.min.y), (d.y, bx.max.y - p0.y)] {
|
||
if pp == 0.0 {
|
||
ok &= q >= 0.0;
|
||
} else if pp < 0.0 {
|
||
t0 = t0.max(q / pp);
|
||
} else {
|
||
t1 = t1.min(q / pp);
|
||
}
|
||
}
|
||
if ok && t1 > t0 {
|
||
total += d.len() * (t1 - t0);
|
||
}
|
||
}
|
||
}
|
||
total
|
||
}
|
||
|
||
#[test]
|
||
fn big_hatch_seen_through_a_wide_view_is_drawn() {
|
||
// ANSI31 (0.125 apart) over ±1e5 seen through a 3000-unit view: about 34,000 lines in the
|
||
// family's rotated frame, past the 20,000-line guard of a whole-hatch sweep, but still drawn
|
||
// when the sweep is limited to the view.
|
||
let d = drawing_with(pattern_hatch("ANSI31", 1.0, (-1e5, -1e5, 1e5, 1e5)));
|
||
let view = Some(Bounds2::new(Vec2::new(-1500.0, -1500.0), Vec2::new(1500.0, 1500.0)));
|
||
let l = build(&d, &Space::Model, &Options { view, ..Default::default() });
|
||
assert!(l.prims.len() > 20_000, "{}", l.prims.len());
|
||
}
|
||
|
||
#[test]
|
||
fn hatch_in_a_squashed_block_keeps_lines_that_show() {
|
||
// A block hatch inserted 100x wider than tall: along x its lines are spread far apart on
|
||
// screen, so it is drawn with lines, not merged into a fill.
|
||
let mut d = Drawing::new_imperial();
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
let mut e = cadcraft_doc::Entity::new(cadcraft_doc::Handle(1), EntityKind::Hatch(pattern_hatch("ANSI31", 1.0, (0.0, 0.0, 4.0, 4.0))));
|
||
e.common = Common::default();
|
||
blk.entities.push(e);
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
let ins = cadcraft_doc::Insert {
|
||
block: "B".into(),
|
||
insert: Vec3::new(0.0, 0.0, 0.0),
|
||
scale: Vec3::new(100.0, 1.0, 1.0),
|
||
rotation: 0.0,
|
||
attribs: vec![],
|
||
cols: 1,
|
||
rows: 1,
|
||
col_spacing: 0.0,
|
||
row_spacing: 0.0,
|
||
clip: None,
|
||
};
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
// One pixel = 1 unit: 0.125 spacing × 100 along x is far more than a pixel.
|
||
let l = build(&d, &Space::Model, &screen(1.0, None));
|
||
assert!(l.prims.iter().all(|p| p.kind != Kind::Tris), "merged into a fill");
|
||
assert!(l.prims.len() > 10, "{}", l.prims.len());
|
||
}
|
||
|
||
#[test]
|
||
fn max_scale_is_the_most_stretched_axis() {
|
||
let m = Mat3::scale(1.0, 0.1);
|
||
assert!((max_scale(&m) - 1.0).abs() < 1e-12);
|
||
let r = Mat3::rotate(0.7).then(Mat3::scale(2.0, 2.0));
|
||
assert!((max_scale(&r) - 2.0).abs() < 1e-12);
|
||
assert!((max_scale(&Mat3::IDENTITY) - 1.0).abs() < 1e-12);
|
||
}
|
||
|
||
// ---------- transparency ----------
|
||
|
||
fn line_common(c: Common) -> (Common, EntityKind) {
|
||
(c, EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) }))
|
||
}
|
||
|
||
fn with_transparency() -> Options {
|
||
Options { transparency: true, ..Default::default() }
|
||
}
|
||
|
||
fn block_entity(handle: u64, common: Common, kind: EntityKind) -> cadcraft_doc::Entity {
|
||
let mut e = cadcraft_doc::Entity::new(cadcraft_doc::Handle(handle), kind);
|
||
e.common = common;
|
||
e
|
||
}
|
||
|
||
fn insert_of(block: &str) -> EntityKind {
|
||
EntityKind::Insert(cadcraft_doc::Insert {
|
||
block: block.into(),
|
||
insert: Vec3::ZERO,
|
||
scale: Vec3::new(1.0, 1.0, 1.0),
|
||
rotation: 0.0,
|
||
attribs: vec![],
|
||
cols: 1,
|
||
rows: 1,
|
||
col_spacing: 0.0,
|
||
row_spacing: 0.0,
|
||
clip: None,
|
||
})
|
||
}
|
||
|
||
#[test]
|
||
fn transparency_resolves_by_object_layer_and_block() {
|
||
use cadcraft_doc::Transparency::{ByBlock, ByLayer, Percent};
|
||
let mut d = Drawing::new_imperial();
|
||
d.layers.push(cadcraft_doc::Layer { name: "Walls".into(), transparency: 40, ..Default::default() });
|
||
let add = |d: &mut Drawing, c: Common| {
|
||
let (c, k) = line_common(c);
|
||
d.add(&Space::Model, c, k).unwrap();
|
||
};
|
||
add(&mut d, Common { transparency: Percent(25), ..Default::default() });
|
||
add(&mut d, Common { layer: "Walls".into(), transparency: ByLayer, ..Default::default() });
|
||
// ByBlock outside a block: opaque.
|
||
add(&mut d, Common { transparency: ByBlock, ..Default::default() });
|
||
// Block "Inner": a ByBlock line and a ByLayer line on layer 0 (the reference's layer).
|
||
let mut inner = cadcraft_doc::Block::new("Inner");
|
||
let (c, k) = line_common(Common { transparency: ByBlock, ..Default::default() });
|
||
inner.entities.push(block_entity(1, c, k));
|
||
let (c, k) = line_common(Common::default());
|
||
inner.entities.push(block_entity(2, c, k));
|
||
d.blocks.insert("Inner".into(), std::sync::Arc::new(inner));
|
||
// Block "Outer": a ByBlock reference to Inner, on layer Walls.
|
||
let mut outer = cadcraft_doc::Block::new("Outer");
|
||
outer.entities.push(block_entity(3, Common { layer: "Walls".into(), transparency: ByBlock, ..Default::default() }, insert_of("Inner")));
|
||
d.blocks.insert("Outer".into(), std::sync::Arc::new(outer));
|
||
d.add(&Space::Model, Common { transparency: Percent(70), ..Default::default() }, insert_of("Outer")).unwrap();
|
||
let l = build(&d, &Space::Model, &with_transparency());
|
||
let t: Vec<u8> = l.prims.iter().map(|p| p.transparency).collect();
|
||
// Nested: Inner's ByBlock line takes Outer's reference (70, through the ByBlock reference to
|
||
// Inner); its layer-0 line takes the reference's layer, Walls (40).
|
||
assert_eq!(t, vec![25, 40, 0, 70, 40]);
|
||
// Off (the default): everything is opaque, as before.
|
||
assert!(build(&d, &Space::Model, &Options::default()).prims.iter().all(|p| p.transparency == 0 && p.alpha() == 255));
|
||
}
|
||
|
||
#[test]
|
||
fn hostile_transparency_values_are_clamped() {
|
||
let mut d = Drawing::new_imperial();
|
||
d.layers.push(cadcraft_doc::Layer { name: "Odd".into(), transparency: 250, ..Default::default() });
|
||
let (c, k) = line_common(Common { transparency: cadcraft_doc::Transparency::Percent(u8::MAX), ..Default::default() });
|
||
d.add(&Space::Model, c, k).unwrap();
|
||
let (c, k) = line_common(Common { layer: "Odd".into(), ..Default::default() });
|
||
d.add(&Space::Model, c, k).unwrap();
|
||
// A ByLayer object on a layer that isn't in the table: opaque.
|
||
let (c, k) = line_common(Common { layer: "Missing".into(), ..Default::default() });
|
||
d.add(&Space::Model, c, k).unwrap();
|
||
let l = build(&d, &Space::Model, &with_transparency());
|
||
assert_eq!(l.prims.iter().map(|p| p.transparency).collect::<Vec<_>>(), vec![90, 90, 0]);
|
||
assert_eq!((alpha(0), alpha(50), alpha(90), alpha(200)), (255, 128, 26, 26));
|
||
}
|
||
|
||
#[test]
|
||
fn transparent_solid_hatch_blends_with_the_line_under_it() {
|
||
let mut d = Drawing::new_imperial();
|
||
// The line runs mid-pixel (y = 2.025 is screen row 99.5) so it fills one row exactly.
|
||
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(-2.0, 2.025, 0.0), b: Vec3::new(6.0, 2.025, 0.0) }))
|
||
.unwrap();
|
||
let solid = Hatch { solid: true, pattern: "SOLID".into(), ..pattern_hatch("SOLID", 1.0, (0.0, 0.0, 4.0, 4.0)) };
|
||
d.add(
|
||
&Space::Model,
|
||
Common { color: Color::Index(1), transparency: cadcraft_doc::Transparency::Percent(50), ..Default::default() },
|
||
EntityKind::Hatch(solid),
|
||
)
|
||
.unwrap();
|
||
let pixel = |o: &Options, x: f64, y: f64| {
|
||
let l = build(&d, &Space::Model, o);
|
||
let v = View { center: Vec2::new(2.0, 2.0), scale: 20.0, width: 200, height: 200 };
|
||
let pm = render(&l, &v, &RasterOptions { background: Rgb(0, 0, 0), antialias: false, ..Default::default() }).unwrap();
|
||
let (px, py) = v.to_screen(Vec2::new(x, y));
|
||
let c = pm.pixel(px as u32, py as u32).unwrap();
|
||
(c.red(), c.green(), c.blue())
|
||
};
|
||
let near = |a: (u8, u8, u8), b: (u8, u8, u8)| [(a.0, b.0), (a.1, b.1), (a.2, b.2)].iter().all(|(x, y)| x.abs_diff(*y) <= 2);
|
||
// 50 %: half red over black, and half red over the white line, which shows through.
|
||
let inside = pixel(&with_transparency(), 1.0, 1.0);
|
||
assert!(near(inside, (128, 0, 0)), "{inside:?}");
|
||
let on_line = pixel(&with_transparency(), 1.0, 2.025);
|
||
assert!(near(on_line, (255, 127, 127)), "{on_line:?}");
|
||
// Transparency off: the hatch hides the line, as before.
|
||
assert_eq!(pixel(&Options::default(), 1.0, 2.025), (255, 0, 0));
|
||
}
|
||
|
||
fn attrib(tag: &str) -> cadcraft_doc::Attrib {
|
||
cadcraft_doc::Attrib {
|
||
tag: tag.into(),
|
||
text: cadcraft_doc::Text {
|
||
insert: Vec3::new(1.0, 1.0, 0.0),
|
||
align_pt: None,
|
||
height: 1.0,
|
||
value: "A1".into(),
|
||
rotation: 0.0,
|
||
width_factor: 1.0,
|
||
oblique: 0.0,
|
||
style: "Standard".into(),
|
||
halign: Default::default(),
|
||
valign: Default::default(),
|
||
backwards: false,
|
||
upside_down: false,
|
||
},
|
||
invisible: false,
|
||
constant: false,
|
||
prompt: String::new(),
|
||
props: Default::default(),
|
||
multiline: None,
|
||
modes: Default::default(),
|
||
}
|
||
}
|
||
|
||
/// A block "B" with a line (layer 0, ByLayer) and an attribute definition with `def`'s
|
||
/// properties, and a reference to it with `reference`'s, carrying the attribute.
|
||
fn attributed(def: Common, reference: Common) -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
let (c, k) = line_common(Common::default());
|
||
blk.entities.push(block_entity(1, c, k));
|
||
blk.entities.push(block_entity(2, def, EntityKind::AttDef(attrib("TAG"))));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||
ins.attribs.push(attrib("TAG"));
|
||
d.add(&Space::Model, reference, EntityKind::Insert(ins)).unwrap();
|
||
d
|
||
}
|
||
|
||
/// The transparency of the block's line and of the attribute's text, from a list built with
|
||
/// transparency on (the line is drawn first, then the text).
|
||
fn line_and_text(d: &Drawing) -> (u8, Vec<u8>) {
|
||
let l = build(d, &Space::Model, &with_transparency());
|
||
let (first, rest) = l.prims.split_first().unwrap();
|
||
assert!(!rest.is_empty(), "the attribute is drawn");
|
||
(first.transparency, rest.iter().map(|p| p.transparency).collect())
|
||
}
|
||
|
||
#[test]
|
||
fn attributes_draw_with_their_own_transparency() {
|
||
use cadcraft_doc::Transparency::{ByBlock, Percent};
|
||
// A reference at 60 % on an opaque layer: layer-0 ByLayer contents (the line and the
|
||
// attribute) take the reference's layer, so both are opaque.
|
||
let d = attributed(Common::default(), Common { transparency: Percent(60), ..Default::default() });
|
||
let (line, text) = line_and_text(&d);
|
||
assert_eq!(line, 0);
|
||
assert!(text.iter().all(|t| *t == 0), "{text:?}");
|
||
// An attribute definition with its own 50 % in an opaque reference.
|
||
let d = attributed(Common { transparency: Percent(50), ..Default::default() }, Common::default());
|
||
let (line, text) = line_and_text(&d);
|
||
assert_eq!(line, 0);
|
||
assert!(text.iter().all(|t| *t == 50), "{text:?}");
|
||
// ByBlock follows the reference.
|
||
let d = attributed(Common { transparency: ByBlock, ..Default::default() }, Common { transparency: Percent(30), ..Default::default() });
|
||
assert!(line_and_text(&d).1.iter().all(|t| *t == 30));
|
||
// Off: everything opaque.
|
||
assert!(build(&d, &Space::Model, &Options::default()).prims.iter().all(|p| p.transparency == 0));
|
||
}
|
||
|
||
/// A block "K" with a line along y = 0 and the definition `def` (its text at y = 1), referenced
|
||
/// at `at` with `attribs`, under ATTMODE `attmode`: the points drawn above the line.
|
||
fn drawn_above_line(def: cadcraft_doc::Attrib, attribs: Vec<cadcraft_doc::Attrib>, attmode: i64, at: Vec3) -> Vec<cadcraft_geom::Vec2> {
|
||
let mut d = Drawing::new_imperial();
|
||
d.header.set_i64("ATTMODE", attmode);
|
||
let mut blk = cadcraft_doc::Block::new("K");
|
||
let (c, k) = line_common(Common::default());
|
||
blk.entities.push(block_entity(1, c, k));
|
||
blk.entities.push(block_entity(2, Common::default(), EntityKind::AttDef(def)));
|
||
d.blocks.insert("K".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("K") else { panic!("an insert") };
|
||
ins.insert = at;
|
||
ins.attribs = attribs;
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
l.prims.iter().flat_map(|p| l.points(p).iter().copied()).filter(|p| p.y > at.y + 0.5).collect()
|
||
}
|
||
|
||
fn constant(invisible: bool) -> cadcraft_doc::Attrib {
|
||
cadcraft_doc::Attrib { constant: true, invisible, ..attrib("C") }
|
||
}
|
||
|
||
#[test]
|
||
fn a_constant_attribute_definition_draws_its_value_with_the_reference() {
|
||
// #3413: a constant value isn't copied into the reference's attributes; the block draws it.
|
||
let at = Vec3::new(100.0, 200.0, 0.0);
|
||
let pts = drawn_above_line(constant(false), vec![], 1, at);
|
||
assert!(!pts.is_empty(), "the constant value is drawn");
|
||
// Where the definition puts it, moved with the reference.
|
||
assert!(pts.iter().all(|p| p.x > at.x && p.x < at.x + 10.0 && p.y < at.y + 3.0), "{pts:?}");
|
||
// A variable definition draws nothing from the block (its attribute is drawn instead).
|
||
assert!(drawn_above_line(attrib("C"), vec![], 1, at).is_empty());
|
||
// A reference that carries an attribute for the constant (placed, as attributes are, in
|
||
// drawing coordinates where the definition's text lands) draws it once, not twice.
|
||
let mut own = attrib("c");
|
||
own.text.insert = own.text.insert + at;
|
||
assert_eq!(drawn_above_line(constant(false), vec![own], 1, at).len(), pts.len());
|
||
}
|
||
|
||
#[test]
|
||
fn many_constant_definitions_are_matched_to_the_attributes_without_comparing_every_pair() {
|
||
// #1923: a reference with N attributes of a block with N constant definitions, the tags N long
|
||
// ones alike up to their last characters, no attribute's a definition's. Asking for each
|
||
// definition whether the reference carries its tag by comparing it with every attribute cost
|
||
// N x N comparisons of whole tags for each copy drawn (many seconds here); gathering the
|
||
// reference's tags once costs milliseconds. The values are empty and the attributes invisible,
|
||
// so drawing them costs nothing.
|
||
const N: usize = 4000;
|
||
let tag = |kind: char, i: usize| format!("{}{kind}{i:05}", "T".repeat(1000));
|
||
let mut d = Drawing::new_imperial();
|
||
let mut blk = cadcraft_doc::Block::new("K");
|
||
for (h, i) in (1..).zip(0..N) {
|
||
let mut a = cadcraft_doc::Attrib { constant: true, ..attrib(&tag('D', i)) };
|
||
a.text.value.clear();
|
||
blk.entities.push(block_entity(h, Common::default(), EntityKind::AttDef(a)));
|
||
}
|
||
d.blocks.insert("K".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("K") else { panic!("an insert") };
|
||
ins.attribs = (0..N).map(|i| cadcraft_doc::Attrib { invisible: true, ..attrib(&tag('A', i)) }).collect();
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
let t = std::time::Instant::now();
|
||
build(&d, &Space::Model, &Options::default());
|
||
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
|
||
}
|
||
|
||
#[test]
|
||
fn constant_attribute_definitions_follow_attmode() {
|
||
let at = Vec3::ZERO;
|
||
// ATTMODE 0 hides every attribute; 1 the invisible ones; 2 shows them all.
|
||
assert!(drawn_above_line(constant(false), vec![], 0, at).is_empty());
|
||
assert!(drawn_above_line(constant(true), vec![], 1, at).is_empty());
|
||
assert!(!drawn_above_line(constant(true), vec![], 2, at).is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn attributes_follow_the_reference_layer_and_have_no_definition() {
|
||
use cadcraft_doc::Transparency::Percent;
|
||
// A layer-0 ByLayer definition in a reference on a 40 % layer: the line and the attribute
|
||
// both take the reference's layer.
|
||
let mut d = attributed(Common::default(), Common { layer: "Glass".into(), ..Default::default() });
|
||
// Adding the reference made the layer.
|
||
d.layer_mut("Glass").unwrap().transparency = 40;
|
||
let (line, text) = line_and_text(&d);
|
||
assert_eq!(line, 40);
|
||
assert!(text.iter().all(|t| *t == 40), "{text:?}");
|
||
// No definition in the block: the attribute follows the reference (30 %), with or without
|
||
// properties of its own.
|
||
for props in [cadcraft_doc::AttribProps::default(), cadcraft_doc::AttribProps { color: Some(Color::Index(3)), ..Default::default() }] {
|
||
let mut d = Drawing::new_imperial();
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
let (c, k) = line_common(Common::default());
|
||
blk.entities.push(block_entity(1, c, k));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||
ins.attribs.push(cadcraft_doc::Attrib { props: props.clone(), ..attrib("TAG") });
|
||
d.add(&Space::Model, Common { transparency: Percent(30), ..Default::default() }, EntityKind::Insert(ins)).unwrap();
|
||
let (line, text) = line_and_text(&d);
|
||
assert_eq!(line, 0, "layer-0 ByLayer contents take the reference's opaque layer");
|
||
assert!(text.iter().all(|t| *t == 30), "{props:?}: {text:?}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn attribute_set_on_layer_zero_does_not_take_the_reference_layer() {
|
||
// #3492: a layer-0 definition in a reference on a 40 % layer. An attribute that takes layer 0
|
||
// from its definition is drawn on the reference's layer, like the line; one set on layer 0
|
||
// itself is drawn on the opaque layer 0.
|
||
let drawn = |layer: Option<&str>| {
|
||
let mut d = Drawing::new_imperial();
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
let (c, k) = line_common(Common::default());
|
||
blk.entities.push(block_entity(1, c, k));
|
||
blk.entities.push(block_entity(2, Common::default(), EntityKind::AttDef(attrib("TAG"))));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||
let props = cadcraft_doc::AttribProps { layer: layer.map(Into::into), ..Default::default() };
|
||
ins.attribs.push(cadcraft_doc::Attrib { props, ..attrib("TAG") });
|
||
d.add(&Space::Model, Common { layer: "Glass".into(), ..Default::default() }, EntityKind::Insert(ins)).unwrap();
|
||
d.layer_mut("Glass").unwrap().transparency = 40;
|
||
line_and_text(&d)
|
||
};
|
||
let (inherited_line, inherited) = drawn(None);
|
||
let (line, own) = drawn(Some("0"));
|
||
assert_eq!(line, inherited_line, "the block's contents still take the reference's layer");
|
||
assert!(inherited.iter().all(|t| *t == line), "{inherited:?}");
|
||
assert!(own.iter().all(|t| *t < line), "{own:?}");
|
||
}
|
||
|
||
#[test]
|
||
fn attribute_on_layer_zero_of_a_nested_reference_follows_the_outer_reference() {
|
||
// A reference on the opaque layer A, with an attribute set on layer 0, sits inside block
|
||
// Outer beside a layer-0 line; Outer is placed on a 40 % layer. In Outer the attribute is
|
||
// layer-0 content like that line, so both take the outer reference's layer: not layer 0
|
||
// itself, and not layer A, which only the inner block's own line takes.
|
||
let mut d = Drawing::new_imperial();
|
||
d.layers.push(cadcraft_doc::Layer { name: "A".into(), ..Default::default() });
|
||
let mut inner = cadcraft_doc::Block::new("B");
|
||
let (c, k) = line_common(Common::default());
|
||
inner.entities.push(block_entity(1, c, k));
|
||
inner.entities.push(block_entity(2, Common::default(), EntityKind::AttDef(attrib("TAG"))));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(inner));
|
||
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||
let props = cadcraft_doc::AttribProps { layer: Some("0".into()), ..Default::default() };
|
||
ins.attribs.push(cadcraft_doc::Attrib { props, ..attrib("TAG") });
|
||
let mut outer = cadcraft_doc::Block::new("Outer");
|
||
let (c, k) = line_common(Common::default());
|
||
outer.entities.push(block_entity(3, c, k));
|
||
outer.entities.push(block_entity(4, Common { layer: "A".into(), ..Default::default() }, EntityKind::Insert(ins)));
|
||
d.blocks.insert("Outer".into(), std::sync::Arc::new(outer));
|
||
d.add(&Space::Model, Common { layer: "Glass".into(), ..Default::default() }, insert_of("Outer")).unwrap();
|
||
d.layer_mut("Glass").unwrap().transparency = 40;
|
||
let l = build(&d, &Space::Model, &with_transparency());
|
||
let [outer_line, inner_line, text @ ..] = l.prims.as_slice() else { panic!("two lines and the attribute") };
|
||
assert!(!text.is_empty(), "the attribute is drawn");
|
||
assert!(inner_line.transparency < outer_line.transparency, "the inner block's line is on layer A");
|
||
assert!(text.iter().all(|p| p.transparency == outer_line.transparency), "the attribute follows the outer reference's layer");
|
||
}
|
||
|
||
#[test]
|
||
fn mtext_exact_spacing_ignores_taller_lines() {
|
||
// #711: a doubled middle line pushes the next baseline down with At least, not with Exactly.
|
||
let mtext = |contents: &str, line_spacing: f64, line_spacing_exact: bool| cadcraft_doc::MText {
|
||
insert: Vec3::ZERO,
|
||
height: 1.0,
|
||
width: 10.0,
|
||
attach: 1,
|
||
rotation: 0.0,
|
||
style: "Standard".into(),
|
||
contents: contents.into(),
|
||
line_spacing,
|
||
line_spacing_exact,
|
||
columns: None,
|
||
};
|
||
let d = Drawing::new_imperial();
|
||
let height = |contents: &str, ls: f64, exact: bool| layout_mtext_entity(&d, &mtext(contents, ls, exact)).bounds.height();
|
||
// The plain layout and the paragraph layout (`\p`) both honour the style.
|
||
for mixed in ["A\\P{\\H2x;BB}\\PCC", "\\pxi1;A\\P{\\H2x;BB}\\PCC"] {
|
||
assert!((height(mixed, 1.0, false) - (1.0 + 2.0 * 5.0 / 3.0 + 5.0 / 3.0)).abs() < 1e-9, "{mixed}: at least");
|
||
assert!((height(mixed, 1.0, true) - (1.0 + 2.0 * 5.0 / 3.0)).abs() < 1e-9, "{mixed}: exactly");
|
||
assert!((height(mixed, 2.0, true) - (1.0 + 2.0 * 5.0 / 3.0 * 2.0)).abs() < 1e-9, "{mixed}: exactly, factor 2");
|
||
}
|
||
for exact in [false, true] {
|
||
assert!((height("A\\PBB\\PCC", 1.0, exact) - (1.0 + 2.0 * 5.0 / 3.0)).abs() < 1e-9, "uniform lines, exact {exact}");
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn table_cell_text_height_scales_with_the_table() {
|
||
let height = |table_h: f64, own: Option<f64>| {
|
||
let d = Drawing::new_imperial();
|
||
let st = crate::table_style_of(&d, &cadcraft_doc::Table::default());
|
||
let cell = cadcraft_doc::TableCell { text: "a".into(), text_height: own, ..Default::default() };
|
||
let t = cadcraft_doc::Table {
|
||
col_widths: vec![500.0],
|
||
row_heights: vec![500.0],
|
||
cells: vec![vec![cell]],
|
||
text_height: table_h * st.text_height,
|
||
..Default::default()
|
||
};
|
||
crate::table_geometry(&d, &t).texts.first().map(|x| x.height)
|
||
};
|
||
let base = height(1.0, None).unwrap();
|
||
assert_eq!(height(1.0, Some(150.0)), Some(150.0));
|
||
assert_eq!(height(2.0, Some(150.0)), Some(300.0));
|
||
assert_eq!(height(2.0, None), Some(base * 2.0));
|
||
}
|
||
|
||
#[test]
|
||
fn cancelled_build_stops_early() {
|
||
use std::sync::Arc;
|
||
use std::sync::atomic::AtomicBool;
|
||
let d = sample();
|
||
let set = Some(Arc::new(AtomicBool::new(true)));
|
||
let full = build(&d, &Space::Model, &Options::default());
|
||
assert!(!full.prims.is_empty());
|
||
let opts = Options { cancel: set.clone(), ..Default::default() };
|
||
assert!(opts.cancelled());
|
||
assert!(build(&d, &Space::Model, &opts).prims.is_empty(), "no entity is drawn once cancelled");
|
||
// A hatch sweep stops at its next pattern line.
|
||
let h = pattern_hatch("ANSI31", 1.0, (0.0, 0.0, 6.0, 4.0));
|
||
let loops = loops_of(&h);
|
||
let drawing = cadcraft_doc::Drawing::new_imperial();
|
||
assert!(!crate::hatch::pattern_lines_until(&drawing, &h, &loops, 0.0, None, None).is_empty());
|
||
assert!(crate::hatch::pattern_lines_until(&drawing, &h, &loops, 0.0, None, set.as_deref()).is_empty());
|
||
}
|
||
|
||
// ---------- locked-layer fade ----------
|
||
|
||
/// A line on locked layer "Locked" (own transparency `own`) and a line on layer 0.
|
||
fn locked_lines(own: cadcraft_doc::Transparency) -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() });
|
||
let (c, k) = line_common(Common { layer: "Locked".into(), transparency: own, ..Default::default() });
|
||
d.add(&Space::Model, c, k).unwrap();
|
||
let (c, k) = line_common(Common::default());
|
||
d.add(&Space::Model, c, k).unwrap();
|
||
d
|
||
}
|
||
|
||
fn faded(l: &DisplayList) -> Vec<u8> {
|
||
l.prims.iter().map(|p| p.transparency).collect()
|
||
}
|
||
|
||
fn on_screen(o: Options) -> Options {
|
||
Options { on_screen: true, ..o }
|
||
}
|
||
|
||
#[test]
|
||
fn objects_on_locked_layers_fade_on_screen() {
|
||
use cadcraft_doc::Transparency::{ByLayer, Percent};
|
||
let mut d = locked_lines(ByLayer);
|
||
// Default 50, whether transparency display is on or off; the unlocked line is unchanged.
|
||
for opts in [on_screen(Options::default()), on_screen(with_transparency())] {
|
||
let l = build(&d, &Space::Model, &opts);
|
||
assert_eq!(faded(&l), vec![50, 0]);
|
||
assert!(l.prims[0].alpha() < 255);
|
||
assert_eq!(l.prims[1].alpha(), 255);
|
||
}
|
||
// Builds without the on-screen flag (exports) and plots never fade.
|
||
for opts in [Options::default(), with_transparency()] {
|
||
assert_eq!(faded(&build(&d, &Space::Model, &opts)), vec![0, 0]);
|
||
}
|
||
assert_eq!(faded(&build_plot(&d, &Space::Model, &on_screen(Options::default()))), vec![0, 0]);
|
||
for (v, want) in [(0, 0), (-30, 0), (70, 70)] {
|
||
d.header.set_i64("LAYLOCKFADECTL", v);
|
||
assert_eq!(faded(&build(&d, &Space::Model, &on_screen(Options::default()))), vec![want, 0], "LAYLOCKFADECTL {v}");
|
||
}
|
||
// An object more transparent than the fade keeps its own transparency.
|
||
let d = locked_lines(Percent(80));
|
||
assert_eq!(faded(&build(&d, &Space::Model, &on_screen(with_transparency()))), vec![80, 0]);
|
||
assert_eq!(faded(&build(&d, &Space::Model, &on_screen(Options::default()))), vec![50, 0]);
|
||
assert_eq!(faded(&build(&d, &Space::Model, &with_transparency())), vec![80, 0]);
|
||
}
|
||
|
||
#[test]
|
||
fn layer_zero_in_a_block_on_a_locked_layer_fades() {
|
||
let mut d = Drawing::new_imperial();
|
||
d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() });
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
let (c, k) = line_common(Common::default());
|
||
blk.entities.push(block_entity(1, c, k));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
d.add(&Space::Model, Common { layer: "Locked".into(), ..Default::default() }, insert_of("B")).unwrap();
|
||
assert_eq!(faded(&build(&d, &Space::Model, &on_screen(Options::default()))), vec![50]);
|
||
assert_eq!(faded(&build(&d, &Space::Model, &Options::default())), vec![0]);
|
||
}
|
||
#[test]
|
||
fn byblock_child_on_an_unlocked_layer_does_not_inherit_the_fade() {
|
||
use cadcraft_doc::Transparency::{ByBlock, ByLayer, Percent};
|
||
// A ByBlock line on unlocked layer "Open" in a block inserted on locked layer "Locked".
|
||
let drawing = |insert_transparency| {
|
||
let mut d = Drawing::new_imperial();
|
||
d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() });
|
||
d.layers.push(cadcraft_doc::Layer { name: "Open".into(), ..Default::default() });
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
let (c, k) = line_common(Common { layer: "Open".into(), transparency: ByBlock, ..Default::default() });
|
||
blk.entities.push(block_entity(1, c, k));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
let common = Common { layer: "Locked".into(), transparency: insert_transparency, ..Default::default() };
|
||
d.add(&Space::Model, common, insert_of("B")).unwrap();
|
||
d
|
||
};
|
||
// The child takes the reference's own transparency, not its display fade.
|
||
assert_eq!(faded(&build(&drawing(ByLayer), &Space::Model, &on_screen(with_transparency()))), vec![0]);
|
||
assert_eq!(faded(&build(&drawing(Percent(20)), &Space::Model, &on_screen(with_transparency()))), vec![20]);
|
||
}
|
||
|
||
#[test]
|
||
fn byblock_attribute_on_an_unlocked_layer_does_not_inherit_the_fade() {
|
||
use cadcraft_doc::Transparency::{ByBlock, Percent};
|
||
// A ByBlock attribute definition on unlocked layer "Open", in a reference on locked "Locked".
|
||
for (reference, want) in [(cadcraft_doc::Transparency::ByLayer, 0), (Percent(20), 20)] {
|
||
let mut d = attributed(
|
||
Common { layer: "Open".into(), transparency: ByBlock, ..Default::default() },
|
||
Common { layer: "Locked".into(), transparency: reference, ..Default::default() },
|
||
);
|
||
d.layers.push(cadcraft_doc::Layer { name: "Open".into(), ..Default::default() });
|
||
d.layer_mut("Locked").unwrap().locked = true;
|
||
let l = build(&d, &Space::Model, &on_screen(with_transparency()));
|
||
let (line, text) = l.prims.split_first().unwrap();
|
||
assert_eq!(line.transparency, 50, "the layer-0 line takes the locked reference layer's fade");
|
||
assert!(!text.is_empty() && text.iter().all(|p| p.transparency == want), "{:?}", faded(&l));
|
||
}
|
||
}
|
||
|
||
/// #1434: a closed polyline with a global width narrower than a pixel loses whole sides at
|
||
/// some zooms, while the same polyline with width 0 always shows every side.
|
||
#[test]
|
||
fn thin_wide_polyline_keeps_every_side_at_every_zoom() {
|
||
let square = |const_width: f64| {
|
||
let mut d = Drawing::new_imperial();
|
||
let vertices = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
|
||
let p = cadcraft_doc::LwPolyline { vertices, closed: true, const_width, elevation: 0.0, plinegen: false };
|
||
d.add(&Space::Model, Common::default(), EntityKind::LwPolyline(p)).unwrap();
|
||
d
|
||
};
|
||
// Side midpoints and the direction across each side.
|
||
let sides = [("bottom", Vec2::new(5.0, 0.0)), ("right", Vec2::new(10.0, 5.0)), ("top", Vec2::new(5.0, 10.0)), ("left", Vec2::new(0.0, 5.0))];
|
||
let mut missing = Vec::new();
|
||
for const_width in [0.0, 0.01, 0.05] {
|
||
let d = square(const_width);
|
||
for step in 0..40 {
|
||
let scale = 20.0 + f64::from(step) * 0.37;
|
||
let px = 1.0 / scale;
|
||
let l = build(&d, &Space::Model, &screen(px, None));
|
||
let v = View { center: Vec2::new(5.17, 4.62), scale, width: 400, height: 400 };
|
||
// No anti-aliasing: pixel-centre coverage, as the GPU canvas rasterises (no MSAA).
|
||
let pm = render(&l, &v, &RasterOptions { background: Rgb(0, 0, 0), antialias: false, ..Default::default() }).unwrap();
|
||
for (name, mid) in sides {
|
||
let (sx, sy) = v.to_screen(mid);
|
||
let lit = (-2i32..=2)
|
||
.flat_map(|dy| (-2i32..=2).map(move |dx| (dx, dy)))
|
||
.any(|(dx, dy)| pm.pixel((sx as i32 + dx) as u32, (sy as i32 + dy) as u32).is_some_and(|c| c.red() > 0));
|
||
if !lit {
|
||
missing.push(format!("width {const_width} scale {scale:.2} ({:.2} px wide): {name} side missing", const_width * scale));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
assert!(missing.is_empty(), "{} misses:\n{}", missing.len(), missing.join("\n"));
|
||
}
|
||
|
||
/// #1434: on screen a wide polyline also draws its centre line (a hairline in its colour, solid and
|
||
/// dashed alike); plots and exports (`min_dash` 0) draw the band alone.
|
||
#[test]
|
||
fn wide_polyline_centre_line_is_drawn_on_screen_only() {
|
||
for lt in ["Continuous", "DASHED"] {
|
||
let drawing = |transparency: u8| {
|
||
let mut d = Drawing::new_imperial();
|
||
d.linetypes.extend(cadcraft_doc::library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
|
||
let vertices = [(0.0, 0.0), (3.0, 0.0), (3.0, 3.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
|
||
let p = cadcraft_doc::LwPolyline { vertices, closed: false, const_width: 0.2, elevation: 0.0, plinegen: false };
|
||
let common = Common {
|
||
color: Color::Index(1),
|
||
linetype: lt.into(),
|
||
lineweight: cadcraft_doc::Lineweight::Mm100(50),
|
||
transparency: cadcraft_doc::Transparency::Percent(transparency),
|
||
..Default::default()
|
||
};
|
||
d.add(&Space::Model, common, EntityKind::LwPolyline(p)).unwrap();
|
||
d
|
||
};
|
||
let d = drawing(0);
|
||
let opts = Options { lineweights: true, transparency: true, ..screen(0.01, None) };
|
||
let lines = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Polyline).count();
|
||
let on_screen = build(&d, &Space::Model, &opts);
|
||
assert!(on_screen.prims.iter().any(|p| p.kind == Kind::Tris), "{lt}: the band");
|
||
let hair: Vec<&DPrim> = on_screen.prims.iter().filter(|p| p.kind == Kind::Polyline).collect();
|
||
assert!(!hair.is_empty(), "{lt}: the centre line on screen");
|
||
assert!(hair.iter().all(|p| p.color == Rgb(255, 0, 0) && p.lw == 0.0), "{lt}: hairline in the polyline's colour");
|
||
assert!(on_screen.points(hair[0]).iter().all(|q| q.y.abs() < 1e-9 || (q.x - 3.0).abs() < 1e-9), "{lt}: on the centre line");
|
||
assert_eq!(lines(&build(&d, &Space::Model, &Options { min_dash: 0.0, ..opts.clone() })), 0, "{lt}: exports draw the band alone");
|
||
assert_eq!(lines(&build_plot(&d, &Space::Model, &opts)), 0, "{lt}: plots draw the band alone");
|
||
// Its alpha would add up along the centre: a transparent band gets no hairline.
|
||
let see_through = build(&drawing(50), &Space::Model, &opts);
|
||
assert!(see_through.prims.iter().any(|p| p.kind == Kind::Tris && p.transparency == 50), "{lt}: the transparent band");
|
||
assert_eq!(lines(&see_through), 0, "{lt}: a transparent band gets no hairline");
|
||
}
|
||
}
|
||
|
||
/// Each primitive stroked or filled on its own, as `render` did before it batched hairlines.
|
||
fn render_one_by_one(list: &DisplayList, view: &View, o: &RasterOptions) -> tiny_skia::Pixmap {
|
||
use tiny_skia::{FillRule, LineCap, LineJoin, Paint, PathBuilder, Pixmap, Stroke, Transform};
|
||
let mut pm = Pixmap::new(view.width, view.height).unwrap();
|
||
pm.fill(tiny_skia::Color::from_rgba8(o.background.0, o.background.1, o.background.2, 255));
|
||
for p in &list.prims {
|
||
let c = p.display_rgb(o.background);
|
||
let mut paint = Paint::default();
|
||
paint.set_color_rgba8(c.0, c.1, c.2, p.alpha());
|
||
paint.anti_alias = o.antialias;
|
||
let mut pb = PathBuilder::new();
|
||
match p.kind {
|
||
Kind::Polyline => {
|
||
for (i, q) in list.points(p).iter().enumerate() {
|
||
let (x, y) = view.to_screen(*q);
|
||
if i == 0 {
|
||
pb.move_to(x, y);
|
||
} else {
|
||
pb.line_to(x, y);
|
||
}
|
||
}
|
||
if let Some(path) = pb.finish() {
|
||
let w = if o.px_per_mm > 0.0 && p.lw > 0.0 { (p.lw * o.px_per_mm).max(o.hairline) } else { o.hairline };
|
||
let stroke = Stroke { width: w, line_cap: LineCap::Round, line_join: LineJoin::Round, ..Default::default() };
|
||
pm.stroke_path(&path, &paint, &stroke, Transform::identity(), None);
|
||
}
|
||
}
|
||
Kind::Tris => {
|
||
for t in list.points(p).chunks(3) {
|
||
let [a, b, c] = t else { continue };
|
||
let ((ax, ay), (bx, by), (cx, cy)) = (view.to_screen(*a), view.to_screen(*b), view.to_screen(*c));
|
||
pb.move_to(ax, ay);
|
||
pb.line_to(bx, by);
|
||
pb.line_to(cx, cy);
|
||
pb.close();
|
||
}
|
||
if let Some(path) = pb.finish() {
|
||
pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
|
||
}
|
||
}
|
||
_ => panic!("not drawn by this reference"),
|
||
}
|
||
}
|
||
pm
|
||
}
|
||
|
||
fn push_prim(l: &mut DisplayList, kind: Kind, color: Rgb, transparency: u8, lw: f32, pts: &[Vec2]) {
|
||
let arr = if kind == Kind::Tris { &mut l.tris } else { &mut l.verts };
|
||
let start = arr.len() as u32;
|
||
arr.extend_from_slice(pts);
|
||
for p in pts.iter().filter(|p| p.is_finite() && p.x.abs() < 1e6) {
|
||
l.bounds.add(*p);
|
||
}
|
||
l.prims.push(DPrim { handle: VIEWPORT_CONTENT, color, aci7: false, lw, transparency, kind, start, len: pts.len() as u32 });
|
||
}
|
||
|
||
/// Hairline polylines with the same paint are stroked as one path; the pixels must be exactly
|
||
/// those of stroking each on its own, whatever breaks a run (colour, transparency, lineweight,
|
||
/// fills, unusable coordinates) and with overlaps, caps and dots.
|
||
#[test]
|
||
fn raster_hairline_batches_match_one_by_one() {
|
||
let red = Rgb(255, 0, 0);
|
||
let blue = Rgb(0, 0, 255);
|
||
let mut l = DisplayList::default();
|
||
// A hatch-like run of crossing, overlapping and touching lines in one colour.
|
||
for i in 0..40 {
|
||
let x = f64::from(i) * 0.37;
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(x, 0.0), Vec2::new(x + 6.0, 9.0)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(x + 3.0, 0.0), Vec2::new(x - 2.0, 9.0), Vec2::new(x + 1.0, 4.0)]);
|
||
}
|
||
// Zero-length (a dot), single-point (nothing), and repeated lines.
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(2.0, 2.0), Vec2::new(2.0, 2.0)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(3.0, 3.0)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(1.0, 1.0), Vec2::new(8.0, 2.0)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(1.0, 1.0), Vec2::new(8.0, 2.0)]);
|
||
// Transparent lines build up where they overlap, within a run and across runs.
|
||
for i in 0..10 {
|
||
let y = f64::from(i) * 0.2;
|
||
push_prim(&mut l, Kind::Polyline, blue, 50, 0.0, &[Vec2::new(0.0, y), Vec2::new(12.0, 8.0 - y)]);
|
||
}
|
||
push_prim(&mut l, Kind::Polyline, blue, 20, 0.0, &[Vec2::new(0.0, 5.0), Vec2::new(12.0, 5.0)]);
|
||
// A lineweight (a filled outline when lineweights are shown), a fill, then the run again.
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.5, &[Vec2::new(0.0, 6.0), Vec2::new(12.0, 7.0), Vec2::new(5.0, 2.0)]);
|
||
push_prim(&mut l, Kind::Tris, blue, 30, 0.0, &[Vec2::new(4.0, 4.0), Vec2::new(9.0, 4.0), Vec2::new(6.0, 8.0)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(0.0, 8.0), Vec2::new(12.0, 1.0)]);
|
||
// Unusable or far-out coordinates are stroked on their own, as before.
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(1.0, 1.0), Vec2::new(f64::NAN, 3.0), Vec2::new(9.0, 9.0)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(-1e12, 4.0), Vec2::new(1e12, 4.5)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(5.0, -1e7), Vec2::new(5.5, 1e7)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(0.0, 0.5), Vec2::new(12.0, 0.5)]);
|
||
// Partly and wholly off screen.
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(-30.0, -30.0), Vec2::new(40.0, 30.0)]);
|
||
push_prim(&mut l, Kind::Polyline, red, 0, 0.0, &[Vec2::new(100.0, 100.0), Vec2::new(120.0, 101.0)]);
|
||
let view = View::fit(&l.bounds, 160, 120, 0.05);
|
||
let bg = Rgb(33, 40, 48);
|
||
for o in [
|
||
RasterOptions::default(),
|
||
RasterOptions { antialias: false, ..Default::default() },
|
||
RasterOptions { hairline: 0.5, ..Default::default() },
|
||
RasterOptions { hairline: 0.0, antialias: false, ..Default::default() },
|
||
RasterOptions { px_per_mm: 4.0, background: Rgb(255, 255, 255), ..Default::default() },
|
||
RasterOptions { hairline: 1.5, background: bg, ..Default::default() },
|
||
] {
|
||
let fast = render(&l, &view, &o).unwrap();
|
||
let reference = render_one_by_one(&l, &view, &o);
|
||
assert!(fast.data() == reference.data(), "pixels differ with {o:?}");
|
||
}
|
||
}
|
||
|
||
/// A real hatch pattern (many parallel lines in one colour) renders exactly as stroked line by
|
||
/// line.
|
||
#[test]
|
||
fn raster_hatch_pattern_matches_one_by_one() {
|
||
let mut d = sample();
|
||
d.add(&Space::Model, Common::default(), EntityKind::Hatch(pattern_hatch("ANSI31", 0.2, (0.0, 0.0, 10.0, 10.0)))).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert!(l.prims.len() > 20);
|
||
let view = View::fit(&l.bounds, 300, 200, 0.05);
|
||
for o in [RasterOptions::default(), RasterOptions { background: Rgb(255, 255, 255), ..Default::default() }] {
|
||
assert!(render(&l, &view, &o).unwrap().data() == render_one_by_one(&l, &view, &o).data());
|
||
}
|
||
}
|
||
|
||
/// An OLE2FRAME draws its frame, the rectangle from its two corner points (#2422), and nothing
|
||
/// when a corner is missing.
|
||
#[test]
|
||
fn ole_frame_draws_its_outline() {
|
||
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
|
||
let frame =
|
||
|tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags, graphics: Vec::new() });
|
||
let mut d = Drawing::new_imperial();
|
||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
|
||
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "1"), tag(20, "2")])).unwrap();
|
||
let l = build(&d, &Space::Model, &Options { tolerance: 0.01, ..Default::default() });
|
||
assert_eq!(l.prims.len(), 1, "only the frame with both corners is drawn");
|
||
assert_eq!(l.prims[0].len, 5, "a closed rectangle: five points");
|
||
}
|
||
|
||
/// `Options::linetypes` off draws a dashed line, a dashed wide polyline and a linetype on a layer
|
||
/// as the same whole line a Continuous one draws: what hit tests look at.
|
||
#[test]
|
||
fn without_linetypes_every_line_is_drawn_whole() {
|
||
let drawing = |lt: &str| {
|
||
let mut d = Drawing::new_imperial();
|
||
d.linetypes.extend(cadcraft_doc::library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
|
||
d.layer_mut("0").unwrap().linetype = lt.into();
|
||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(30.0, 0.0, 0.0) });
|
||
d.add(&Space::Model, Common::default(), line).unwrap();
|
||
let vertices = [(0.0, 5.0), (30.0, 5.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
|
||
let wide = cadcraft_doc::LwPolyline { vertices, closed: false, const_width: 0.2, elevation: 0.0, plinegen: false };
|
||
d.add(&Space::Model, Common::default(), EntityKind::LwPolyline(wide)).unwrap();
|
||
d
|
||
};
|
||
let whole = Options { linetypes: false, ..Options::default() };
|
||
let continuous = build(&drawing("Continuous"), &Space::Model, &Options::default());
|
||
let dashed = build(&drawing("DASHED"), &Space::Model, &whole);
|
||
assert_eq!(dashed.prims.len(), continuous.prims.len());
|
||
assert_eq!(dashed.verts, continuous.verts);
|
||
assert_eq!(dashed.tris, continuous.tris);
|
||
let drawn = build(&drawing("DASHED"), &Space::Model, &Options::default());
|
||
assert!(drawn.prims.len() > 2 * continuous.prims.len(), "drawn with its linetype: {} primitives", drawn.prims.len());
|
||
}
|
||
|
||
/// A proxy draws its proxy graphics like block contents: layer 0 and ByBlock in the picture are
|
||
/// the proxy's own, and the proxy's layer hides all of it.
|
||
#[test]
|
||
fn proxy_graphics_draw_like_block_contents() {
|
||
let mut d = Drawing::new_imperial();
|
||
d.layers.push(cadcraft_doc::Layer { name: "Notes".into(), color: Color::Index(3), ..Default::default() });
|
||
let byblock = Common { color: Color::ByBlock, ..Default::default() };
|
||
let graphics = vec![
|
||
block_entity(7, byblock, EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(10.0, 0.0, 0.0) })),
|
||
block_entity(
|
||
7,
|
||
Common { color: Color::Index(1), ..Default::default() },
|
||
EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::new(15.0, 0.0, 0.0), radius: 5.0 }),
|
||
),
|
||
];
|
||
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
|
||
d.add(&Space::Model, Common { layer: "Notes".into(), ..Default::default() }, proxy).unwrap();
|
||
let l = build(&d, &Space::Model, &Options::default());
|
||
assert_eq!(l.prims.iter().map(|p| p.color).collect::<Vec<_>>(), [Rgb(0, 255, 0), Rgb(255, 0, 0)]);
|
||
let b = d.extents(&Space::Model);
|
||
assert!((b.min.x, b.max.x, b.max.y) == (0.0, 20.0, 5.0), "{b:?}");
|
||
d.layer_mut("Notes").unwrap().frozen = true;
|
||
assert!(build(&d, &Space::Model, &Options::default()).prims.is_empty());
|
||
}
|
||
|
||
/// On a locked layer, a proxy's graphics fade like a block's contents: layer 0 in the picture takes
|
||
/// the proxy's fade, a ByBlock part on an unlocked layer only the proxy's own transparency.
|
||
#[test]
|
||
fn proxy_graphics_on_a_locked_layer_fade_like_block_contents() {
|
||
use cadcraft_doc::Transparency::{ByBlock, ByLayer, Percent};
|
||
for (own, want) in [(ByLayer, 0), (Percent(20), 20)] {
|
||
let mut d = Drawing::new_imperial();
|
||
d.layers.push(cadcraft_doc::Layer { name: "Locked".into(), locked: true, ..Default::default() });
|
||
d.layers.push(cadcraft_doc::Layer { name: "Open".into(), ..Default::default() });
|
||
let line = |x: f64| EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(x, 0.0, 0.0), b: Vec3::new(x + 1.0, 0.0, 0.0) });
|
||
let graphics = vec![
|
||
block_entity(7, Common::default(), line(0.0)),
|
||
block_entity(7, Common { layer: "Open".into(), transparency: ByBlock, ..Default::default() }, line(2.0)),
|
||
];
|
||
let proxy = EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "ACAD_PROXY_ENTITY".into(), tags: Vec::new(), graphics });
|
||
d.add(&Space::Model, Common { layer: "Locked".into(), transparency: own, ..Default::default() }, proxy).unwrap();
|
||
assert_eq!(faded(&build(&d, &Space::Model, &on_screen(with_transparency()))), vec![50.max(want), want], "{own:?}");
|
||
}
|
||
}
|
||
|
||
/// A broken table whose parts, with their repeated labels, together hold more cells than a table may
|
||
/// lay out is drawn as its outline, though the table's own cells are within the limit.
|
||
#[test]
|
||
fn broken_table_cells_count_across_its_parts() {
|
||
let d = Drawing::new_imperial();
|
||
let t = cadcraft_doc::Table {
|
||
col_widths: vec![1.0; 600],
|
||
row_heights: vec![1.0; 1000],
|
||
title: true,
|
||
header: true,
|
||
breaks: Some(cadcraft_doc::TableBreak { enabled: true, height: 3.0, ..Default::default() }),
|
||
..Default::default()
|
||
};
|
||
assert!(t.parts().len() > 500 && 1000 * 600 <= crate::MAX_LAYOUT_CELLS);
|
||
let g = crate::table_geometry(&d, &t);
|
||
let parts = t.parts();
|
||
assert_eq!((g.lines.len(), g.texts.len(), g.fills.len()), (4 * parts.len(), 0, 0));
|
||
// Each part's box starts at its own origin.
|
||
let top = |i: usize| g.lines[4 * i].a;
|
||
assert!((0..parts.len()).all(|i| top(i) == parts[i].origin));
|
||
}
|
||
|
||
#[test]
|
||
fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() {
|
||
let ring = |rot: usize, rev: bool| {
|
||
let mut v: Vec<PolyVertex> = [(0.0, 0.0, 0.5), (4.0, 0.0, -0.25), (4.0, 3.0, 0.0), (0.0, 3.0, 0.1)]
|
||
.map(|(x, y, bulge)| PolyVertex { bulge, ..PolyVertex::new(Vec2::new(x, y)) })
|
||
.to_vec();
|
||
if rev {
|
||
// The same boundary wound the other way: bulges move to the other end of their edge and flip.
|
||
let b: Vec<f64> = v.iter().map(|q| q.bulge).collect();
|
||
v.reverse();
|
||
let n = v.len();
|
||
for (j, q) in v.iter_mut().enumerate() {
|
||
q.bulge = -b[(n - 1 - j + n - 1) % n];
|
||
}
|
||
}
|
||
v.rotate_left(rot);
|
||
HatchLoop { vertices: v, outer: true, boundary_flags: None, sources: Vec::new() }
|
||
};
|
||
let mut h = pattern_hatch("SOLID", 1.0, (0.0, 0.0, 1.0, 1.0));
|
||
h.loops = vec![ring(0, false), ring(2, false), ring(1, true), ring(3, true)];
|
||
assert_eq!(loops_of(&h).len(), 1);
|
||
// A different boundary is kept.
|
||
h.loops.push(HatchLoop {
|
||
vertices: ring(0, false).vertices.into_iter().map(|q| PolyVertex { bulge: 0.0, ..q }).collect(),
|
||
outer: true,
|
||
boundary_flags: None,
|
||
sources: Vec::new(),
|
||
});
|
||
assert_eq!(loops_of(&h).len(), 2);
|
||
}
|
||
|
||
// ---------- point and primitive budgets (#1922, #1603) ----------
|
||
|
||
fn circle() -> EntityKind {
|
||
EntityKind::Circle(cadcraft_doc::Circle { center: Vec3::ZERO, radius: 100.0 })
|
||
}
|
||
|
||
/// A block of one circle referenced as 1,000 copies in place: every copy is cheap to the
|
||
/// block-expansion budget but costs hundreds of points.
|
||
fn arrayed_circles() -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
blk.entities.push(block_entity(1, Common::default(), circle()));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||
ins.cols = 1000;
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
d
|
||
}
|
||
|
||
fn points(l: &DisplayList) -> usize {
|
||
l.verts.len() + l.tris.len()
|
||
}
|
||
|
||
#[test]
|
||
fn block_copies_stop_at_the_point_budget_and_say_so() {
|
||
let d = arrayed_circles();
|
||
let full = build(&d, &Space::Model, &Options::default());
|
||
assert!(!full.truncated && points(&full) > 100_000, "{}", points(&full));
|
||
let l = crate::pipeline::build_space_within(
|
||
&d,
|
||
&Space::Model,
|
||
&Options::default(),
|
||
false,
|
||
10_000,
|
||
crate::MAX_DISPLAY_PRIMS,
|
||
crate::MAX_DASH_ELEMENTS,
|
||
);
|
||
assert!(l.truncated);
|
||
assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l));
|
||
assert!(l.prims.iter().all(|p| p.start as usize + p.len as usize <= l.verts.len()));
|
||
}
|
||
|
||
#[test]
|
||
fn objects_built_on_all_cores_stop_at_the_point_budget_and_say_so() {
|
||
// Enough objects for the parallel build: the parts share one budget and report together.
|
||
let mut d = Drawing::new_imperial();
|
||
for _ in 0..600 {
|
||
d.add(&Space::Model, Common::default(), circle()).unwrap();
|
||
}
|
||
let l = crate::pipeline::build_space_within(
|
||
&d,
|
||
&Space::Model,
|
||
&Options::default(),
|
||
false,
|
||
10_000,
|
||
crate::MAX_DISPLAY_PRIMS,
|
||
crate::MAX_DASH_ELEMENTS,
|
||
);
|
||
assert!(l.truncated);
|
||
assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l));
|
||
}
|
||
|
||
fn point_at(x: f64) -> EntityKind {
|
||
EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(x, 0.0, 0.0), angle: 0.0 })
|
||
}
|
||
|
||
/// A block of one point referenced as 1,000 copies in place: every copy is one primitive of one
|
||
/// point, so the point budget holds far more of them than a 32-bit target's primitive vector
|
||
/// (#1603).
|
||
fn arrayed_points() -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
blk.entities.push(block_entity(1, Common::default(), point_at(0.0)));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||
ins.cols = 1000;
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
d
|
||
}
|
||
|
||
#[test]
|
||
fn one_point_primitives_stop_at_the_primitive_budget_and_say_so() {
|
||
let d = arrayed_points();
|
||
let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
|
||
assert!(!full.truncated && full.prims.len() >= 1000, "{}", full.prims.len());
|
||
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 100, MAX_DASH_ELEMENTS);
|
||
assert!(l.truncated);
|
||
assert!(!l.prims.is_empty() && l.prims.len() <= 100, "{}", l.prims.len());
|
||
// And the copies past it are not visited.
|
||
assert!(l.expanded < full.expanded / 2, "{} of {}", l.expanded, full.expanded);
|
||
}
|
||
|
||
#[test]
|
||
fn primitives_built_on_all_cores_stop_at_the_primitive_budget_and_say_so() {
|
||
// Enough references of a one-point block for the parallel build: the parts share one
|
||
// primitive count, and stop visiting their blocks once it is spent.
|
||
let mut d = Drawing::new_imperial();
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
blk.entities.push(block_entity(1, Common::default(), point_at(0.0)));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
for i in 0..600 {
|
||
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||
ins.insert = Vec3::new(f64::from(i), 0.0, 0.0);
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
}
|
||
let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
|
||
assert_eq!(full.prims.len(), 600);
|
||
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 100, MAX_DASH_ELEMENTS);
|
||
assert!(l.truncated);
|
||
assert!(!l.prims.is_empty() && l.prims.len() <= 100, "{}", l.prims.len());
|
||
assert!(l.expanded < full.expanded / 2, "{} of {}", l.expanded, full.expanded);
|
||
// A limit no one part reaches (parts of 256 objects): only the shared count stops the parts
|
||
// at the limit together. Counted per part, each would build its whole chunk, and the join
|
||
// would keep the first part alone.
|
||
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 300, MAX_DASH_ELEMENTS);
|
||
assert!(l.truncated);
|
||
assert_eq!(l.prims.len(), 300);
|
||
}
|
||
|
||
/// A polyline of 200 points zigzagging across y = 1 between x = 1.5 and 8.5: a clip whose edge
|
||
/// is y = 1 cuts it into about 100 pieces of three points each.
|
||
fn zigzag() -> EntityKind {
|
||
let vertices = (0..200).map(|i| PolyVertex::new(Vec2::new(1.5 + 7.0 * f64::from(i) / 199.0, if i % 2 == 0 { 0.0 } else { 2.0 }))).collect();
|
||
EntityKind::LwPolyline(cadcraft_doc::LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false })
|
||
}
|
||
|
||
#[test]
|
||
fn pieces_cut_by_a_clip_stop_at_the_list_limits_and_say_so() {
|
||
// Seen through a viewport whose model window starts at y = 1, the zigzag and then a point
|
||
// inside the window. Each drawing ends with a point the budgets alone would still take after
|
||
// the pieces: a full list stops the build.
|
||
let mut through_viewport = Drawing::new_imperial();
|
||
through_viewport.add(&Space::Model, Common::default(), zigzag()).unwrap();
|
||
through_viewport
|
||
.add(&Space::Model, Common::default(), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 }))
|
||
.unwrap();
|
||
let paper = Space::Paper("Layout1".into());
|
||
through_viewport.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2))).unwrap();
|
||
through_viewport.add(&paper, Common::default(), point_at(5.0)).unwrap();
|
||
// In a block reference clipped (XCLIP) to a rectangle from y = 1 up, without its frame.
|
||
let mut xclipped = Drawing::new_imperial();
|
||
xclipped.header.set_i64("XCLIPFRAME", 0);
|
||
let mut blk = cadcraft_doc::Block::new("Z");
|
||
blk.entities.push(block_entity(1, Common::default(), zigzag()));
|
||
blk.entities.push(block_entity(2, Common::default(), EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 })));
|
||
xclipped.blocks.insert("Z".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("Z") else { panic!("an insert") };
|
||
ins.clip = Some(cadcraft_doc::ClipBoundary::new(vec![Vec2::new(0.0, 1.0), Vec2::new(10.0, 10.0)]));
|
||
xclipped.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
xclipped.add(&Space::Model, Common::default(), point_at(5.0)).unwrap();
|
||
for (d, space) in [(&through_viewport, &paper), (&xclipped, &Space::Model)] {
|
||
let build = |max_points, max_prims| {
|
||
crate::pipeline::build_space_within(d, space, &Options::default(), false, max_points, max_prims, MAX_DASH_ELEMENTS)
|
||
};
|
||
// The one polyline the build charges becomes many pieces with more points.
|
||
let full = build(MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS);
|
||
assert!(!full.truncated && full.prims.len() > 50 && points(&full) > 250, "{space:?}: {} prims, {} points", full.prims.len(), points(&full));
|
||
let l = build(10_000, 20);
|
||
assert!(l.truncated && !l.prims.is_empty() && l.prims.len() <= 20, "{space:?}: {}", l.prims.len());
|
||
// The pieces stop at the first that doesn't fit: neither point comes after them.
|
||
let l = build(220, MAX_DISPLAY_PRIMS);
|
||
assert!(l.truncated && points(&l) > 0 && points(&l) <= 220, "{space:?}: {}", points(&l));
|
||
assert!(full.prims.iter().any(|p| p.kind == Kind::Point) && l.prims.iter().all(|p| p.kind != Kind::Point), "{space:?}");
|
||
// Pieces that fill the list exactly leave no room for the last point.
|
||
for l in [build(MAX_DISPLAY_POINTS, full.prims.len() - 1), build(points(&full) - 1, MAX_DISPLAY_PRIMS)] {
|
||
assert!(l.truncated && l.prims.len() == full.prims.len() - 1, "{space:?}: {} of {}", l.prims.len(), full.prims.len());
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The zigzag drawn 0.2 wide: one primitive of triangles, seen through a viewport whose model
|
||
/// window starts at y = 1, and a point after it on the layout.
|
||
fn wide_zigzag_through_viewport() -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
let EntityKind::LwPolyline(mut wide) = zigzag() else { panic!("a polyline") };
|
||
wide.const_width = 0.2;
|
||
d.add(&Space::Model, Common::default(), EntityKind::LwPolyline(wide)).unwrap();
|
||
let paper = Space::Paper("Layout1".into());
|
||
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2))).unwrap();
|
||
d.add(&paper, Common::default(), point_at(5.0)).unwrap();
|
||
d
|
||
}
|
||
|
||
#[test]
|
||
fn fills_cut_by_a_clip_stop_at_the_list_limits_and_say_so() {
|
||
// Each triangle the window's edge crosses becomes a fan with more points. With room for part
|
||
// of the clipped fill, the triangles that fit are drawn up to the limit, the rest is not built,
|
||
// and the list says it was left out; the point after the viewport is not drawn either.
|
||
let d = wide_zigzag_through_viewport();
|
||
let paper = Space::Paper("Layout1".into());
|
||
let build =
|
||
|max_points| crate::pipeline::build_space_within(&d, &paper, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
|
||
let full = build(MAX_DISPLAY_POINTS);
|
||
let fills = full.prims.iter().filter(|p| p.kind == Kind::Tris).count();
|
||
// The build charges the fill's points before it is clipped: fewer than the clip makes.
|
||
let charged =
|
||
crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
|
||
assert!(
|
||
!full.truncated && fills == 1 && full.tris.len() > charged.tris.len() + 100,
|
||
"{fills} fills, {} of {}",
|
||
full.tris.len(),
|
||
charged.tris.len()
|
||
);
|
||
// Limits the charge passes and the clipped fill does not fit.
|
||
for limit in [points(&full) - (full.tris.len() - charged.tris.len()) / 2, full.verts.len() + charged.tris.len()] {
|
||
let l = build(limit);
|
||
assert!(l.truncated && !l.tris.is_empty() && full.tris.starts_with(&l.tris), "{limit}: {}", l.tris.len());
|
||
// Whole triangles, up to the limit.
|
||
assert!(l.tris.len() % 3 == 0 && points(&l) <= limit && points(&l) + 3 > limit, "{limit}: {}", points(&l));
|
||
assert!(l.prims.iter().all(|p| p.kind != Kind::Point), "{limit}");
|
||
}
|
||
// Clipped into a list of its own (as a preview's clipped copy is, with no build to stop), the
|
||
// cut fill marks that list truncated too.
|
||
let mut list = DisplayList::default();
|
||
let window = crate::viewports::Clip::Rect(Bounds2::new(Vec2::new(1.0, 1.0), Vec2::new(9.0, 9.0)));
|
||
let fits = crate::viewports::append_clipped(&mut list, &charged, &window, crate::viewports::Limits { points: 300, prims: 10 });
|
||
assert!(!fits && list.truncated && list.tris.len() == 300, "{}", list.tris.len());
|
||
}
|
||
|
||
#[test]
|
||
fn a_clipped_preview_keeps_what_its_list_left_out() {
|
||
// A point, then a zigzag the point budget leaves out: the list says so, and so does its copy
|
||
// clipped to a viewport's outline (the preview of a command inside a clipped viewport).
|
||
let mut d = Drawing::new_imperial();
|
||
d.add(&Space::Model, Common::default(), point_at(5.0)).unwrap();
|
||
d.add(&Space::Model, Common::default(), zigzag()).unwrap();
|
||
let mut l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 100, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
|
||
assert!(l.truncated && l.prims.len() == 1, "{} prims", l.prims.len());
|
||
(l.undashed, l.expanded) = (2, 3);
|
||
let square = [Vec2::new(-100.0, -100.0), Vec2::new(100.0, -100.0), Vec2::new(100.0, 100.0), Vec2::new(-100.0, 100.0)];
|
||
let c = crate::clip_list(&l, &crate::clip::PolyClip::new(&square).unwrap());
|
||
assert_eq!(c.prims.len(), 1);
|
||
assert!(c.truncated);
|
||
assert_eq!((c.undashed, c.expanded), (2, 3));
|
||
}
|
||
|
||
#[test]
|
||
fn layout_plot_style_outlines_stop_at_the_list_limits_and_say_so() {
|
||
// A plot style's line ends turn each wide line into a filled outline after the build, outside
|
||
// its budgets (#1603). Drawn on a layout or inside one of its viewports, the outlines stop at
|
||
// the build's point limit: every line is still drawn, those past it as plain lines.
|
||
let round = cadcraft_doc::PlotStyleTable::color_dependent("round.ctb", "", |i| {
|
||
(i == 1).then(|| cadcraft_doc::PlotStyle { lineweight: Some(100), end: cadcraft_doc::EndStyle::Round, ..Default::default() })
|
||
});
|
||
let opts = Options { plot_style_table: Some(std::sync::Arc::new(round)), lineweights: true, ..Default::default() };
|
||
let paper = Space::Paper("Layout1".into());
|
||
for space in [paper.clone(), Space::Model] {
|
||
let mut d = Drawing::new_metric();
|
||
for k in 0..20 {
|
||
let y = 10.0 + 4.0 * f64::from(k);
|
||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(10.0, y, 0.0), b: Vec3::new(90.0, y, 0.0) });
|
||
d.add(&space, Common { color: Color::Index(1), ..Default::default() }, line).unwrap();
|
||
}
|
||
if space == Space::Model {
|
||
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(50.0, 50.0), 100.0, 100.0, Vec2::new(50.0, 50.0), 100.0, 2))).unwrap();
|
||
}
|
||
let build = |max_points| crate::pipeline::build_space_within(&d, &paper, &opts, false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
|
||
let full = build(MAX_DISPLAY_POINTS);
|
||
let outlines = full.prims.iter().filter(|p| p.kind == Kind::Tris).count();
|
||
assert!(!full.truncated && outlines == 20, "{space:?}: {outlines} outlines");
|
||
let limit = points(&full) / 2;
|
||
let l = build(limit);
|
||
let plain = l.prims.iter().filter(|p| p.kind == Kind::Polyline).count();
|
||
assert!(l.truncated && points(&l) <= limit, "{space:?}: {} of {limit}", points(&l));
|
||
assert!(l.prims.len() == full.prims.len() && plain > 0 && plain < 20, "{space:?}: {plain} plain of {}", l.prims.len());
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn viewport_outlines_stop_at_the_room_the_layout_has_left() {
|
||
// Viewport contents get their plot style outlines before they are clipped into the layout's
|
||
// list, which already holds the objects drawn before the viewport. Outlines made within the
|
||
// build's whole limit could fit the contents' own list but not the layout's: the append then
|
||
// stopped part-way and spent the build, so the last line in the viewport and the layout
|
||
// objects after it were left out, though their plain lines fit. Within the room the layout's
|
||
// list has left, every object is drawn and only outlines are left out.
|
||
let round = cadcraft_doc::PlotStyleTable::color_dependent("round.ctb", "", |i| {
|
||
(i == 1).then(|| cadcraft_doc::PlotStyle { lineweight: Some(100), end: cadcraft_doc::EndStyle::Round, ..Default::default() })
|
||
});
|
||
let opts = Options { plot_style_table: Some(std::sync::Arc::new(round)), lineweights: true, ..Default::default() };
|
||
let paper = Space::Paper("Layout1".into());
|
||
let line = |y: f64| EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(10.0, y, 0.0), b: Vec3::new(90.0, y, 0.0) });
|
||
let plain = || Common { color: Color::Index(2), ..Default::default() };
|
||
let mut d = Drawing::new_metric();
|
||
// Before the viewport: 40 plain lines and 10 solids on the layout.
|
||
for k in 0..40 {
|
||
d.add(&paper, plain(), line(150.0 + f64::from(k))).unwrap();
|
||
}
|
||
for k in 0..10 {
|
||
let x = 120.0 + 5.0 * f64::from(k);
|
||
let corners = [Vec3::new(x, 0.0, 0.0), Vec3::new(x + 4.0, 0.0, 0.0), Vec3::new(x, 4.0, 0.0), Vec3::new(x + 4.0, 4.0, 0.0)];
|
||
d.add(&paper, plain(), EntityKind::Solid(cadcraft_doc::Solid { corners })).unwrap();
|
||
}
|
||
// 20 round-ended lines seen through the viewport, and 5 plain lines on the layout after it.
|
||
for k in 0..20 {
|
||
d.add(&Space::Model, Common { color: Color::Index(1), ..Default::default() }, line(10.0 + 4.0 * f64::from(k))).unwrap();
|
||
}
|
||
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(50.0, 50.0), 100.0, 100.0, Vec2::new(50.0, 50.0), 100.0, 2))).unwrap();
|
||
let after = [200.0, 201.0, 202.0, 203.0, 204.0];
|
||
for y in after {
|
||
d.add(&paper, plain(), line(y)).unwrap();
|
||
}
|
||
let build = |max_points| crate::pipeline::build_space_within(&d, &paper, &opts, false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
|
||
let plain_lines = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Polyline).count();
|
||
let full = build(MAX_DISPLAY_POINTS);
|
||
assert!(!full.truncated && full.prims.iter().filter(|p| p.kind == Kind::Tris).count() == 30);
|
||
// Room for every object but the last outline. The contents' own list (their plain lines'
|
||
// vertices and every outline) fits that limit; after the objects before the viewport it
|
||
// doesn't.
|
||
let tail: usize = full.prims.iter().rev().take(after.len()).map(|p| full.points(p).len()).sum();
|
||
let limit = points(&full) - tail - 1;
|
||
let l = build(limit);
|
||
assert!(l.truncated && points(&l) <= limit, "{} of {limit}", points(&l));
|
||
assert_eq!(l.prims.len(), full.prims.len(), "every object is drawn");
|
||
assert!(plain_lines(&l) > plain_lines(&full), "some lines in the viewport keep their plain line");
|
||
}
|
||
|
||
/// A block reference clipped (XCLIP, frame off) to a large rectangle, of block "Z" holding `kind`.
|
||
fn xclipped_ref(d: &mut Drawing, kind: EntityKind, at: Vec3) -> EntityKind {
|
||
if d.block("Z").is_none() {
|
||
let mut blk = cadcraft_doc::Block::new("Z");
|
||
blk.entities.push(block_entity(1, Common::default(), kind));
|
||
d.blocks.insert("Z".into(), std::sync::Arc::new(blk));
|
||
}
|
||
let EntityKind::Insert(mut ins) = insert_of("Z") else { panic!("an insert") };
|
||
ins.insert = at;
|
||
ins.clip = Some(cadcraft_doc::ClipBoundary::new(vec![Vec2::new(-100.0, 1.0), Vec2::new(100.0, 100.0)]));
|
||
EntityKind::Insert(ins)
|
||
}
|
||
|
||
#[test]
|
||
fn attributes_cut_by_a_clip_say_what_the_budget_left_out() {
|
||
// The last object of the drawing: a clipped reference whose attribute text runs out of points.
|
||
let mut d = Drawing::new_imperial();
|
||
d.header.set_i64("XCLIPFRAME", 0);
|
||
let kind = xclipped_ref(&mut d, line_common(Common::default()).1, Vec3::ZERO);
|
||
let EntityKind::Insert(mut ins) = kind else { panic!("an insert") };
|
||
let mut a = attrib("TAG");
|
||
a.text.insert = Vec3::new(1.0, 2.0, 0.0);
|
||
a.text.value = "ABCDEFGHIJKLMNOP".into();
|
||
ins.attribs.push(a);
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
let build = |max_points| {
|
||
crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS)
|
||
};
|
||
let full = build(MAX_DISPLAY_POINTS);
|
||
assert!(!full.truncated && points(&full) > 20, "{}", points(&full));
|
||
let l = build(points(&full) - 1);
|
||
assert!(l.truncated && points(&l) < points(&full), "{} of {}", points(&l), points(&full));
|
||
}
|
||
|
||
#[test]
|
||
fn parts_built_on_all_cores_are_joined_within_the_list_limits() {
|
||
// Two clipped zigzags in different parts of the parallel build: each part fits the list's
|
||
// limits and the build's counts, which hold the zigzags and not their pieces; together they
|
||
// don't fit.
|
||
let mut d = Drawing::new_imperial();
|
||
d.header.set_i64("XCLIPFRAME", 0);
|
||
for i in 0..600 {
|
||
let kind = if i == 0 || i == 300 { xclipped_ref(&mut d, zigzag(), Vec3::ZERO) } else { point_at(f64::from(i)) };
|
||
d.add(&Space::Model, Common::default(), kind).unwrap();
|
||
}
|
||
let build = |max_points, max_prims| {
|
||
crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, max_points, max_prims, MAX_DASH_ELEMENTS)
|
||
};
|
||
let full = build(MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS);
|
||
assert!(!full.truncated && full.prims.len() > 700 && points(&full) > 1000, "{} prims, {} points", full.prims.len(), points(&full));
|
||
let max = full.prims.len() - 50;
|
||
let l = build(MAX_DISPLAY_POINTS, max);
|
||
assert!(l.truncated && l.prims.len() <= max, "{} of {max}", l.prims.len());
|
||
let max = points(&full) - 50;
|
||
let l = build(max, MAX_DISPLAY_PRIMS);
|
||
assert!(l.truncated && points(&l) <= max, "{} of {max}", points(&l));
|
||
// Exactly as much as the parts hold is joined whole.
|
||
for l in [build(MAX_DISPLAY_POINTS, full.prims.len()), build(points(&full), MAX_DISPLAY_PRIMS)] {
|
||
assert!(!l.truncated && l.prims.len() == full.prims.len(), "{} of {}", l.prims.len(), full.prims.len());
|
||
}
|
||
}
|
||
|
||
// ---------- dash budget (#1069, #1923) ----------
|
||
|
||
/// A drawing of lines on DASHED (0.5, -0.25), one per entry of `periods` and that many periods
|
||
/// long, on rows 1 apart.
|
||
fn dashed_lines(periods: &[f64]) -> Drawing {
|
||
let mut d = Drawing::new_imperial();
|
||
d.linetypes.push(cadcraft_doc::Linetype::simple("DASHED", "", &[0.5, -0.25]));
|
||
for (row, n) in periods.iter().enumerate() {
|
||
let y = row as f64;
|
||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(n * 0.75, y, 0.0) });
|
||
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, line).unwrap();
|
||
}
|
||
d
|
||
}
|
||
|
||
/// The primitives drawn for each top-level entity, in drawing order.
|
||
fn prims_per_entity(l: &DisplayList) -> Vec<usize> {
|
||
let mut out: Vec<(Handle, usize)> = Vec::new();
|
||
for p in &l.prims {
|
||
match out.last_mut() {
|
||
Some((h, n)) if *h == p.handle => *n += 1,
|
||
_ => out.push((p.handle, 1)),
|
||
}
|
||
}
|
||
out.into_iter().map(|(_, n)| n).collect()
|
||
}
|
||
|
||
/// A run whose pattern repeats past [`MAX_RUN_DASH_ELEMENTS`] is drawn continuous, and the list
|
||
/// says so: 1,000,001 DASHED periods are (n + 2) × 2 elements, past two million (#1069). A plot
|
||
/// keeps the dashes of 50,001 periods and says nothing.
|
||
#[test]
|
||
fn a_run_past_its_dash_limit_is_drawn_continuous_and_says_so() {
|
||
let l = build_plot(&dashed_lines(&[1_000_001.0]), &Space::Model, &Options::default());
|
||
assert_eq!(l.prims.len(), 1);
|
||
assert!(l.truncated);
|
||
let l = build_plot(&dashed_lines(&[50_001.0]), &Space::Model, &Options::default());
|
||
assert!(l.prims.len() > 50_001 && !l.truncated, "{}", l.prims.len());
|
||
// The band of a wide polyline as well.
|
||
let mut d = dashed_lines(&[]);
|
||
let vertices = vec![PolyVertex::new(Vec2::ZERO), PolyVertex::new(Vec2::new(1_000_001.0 * 0.75, 0.0))];
|
||
let band = cadcraft_doc::LwPolyline { vertices, closed: false, const_width: 0.1, elevation: 0.0, plinegen: false };
|
||
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(band)).unwrap();
|
||
assert!(build_plot(&d, &Space::Model, &Options::default()).truncated);
|
||
}
|
||
|
||
/// Past the build's dash budget the rest of the dashed runs are drawn continuous and counted
|
||
/// (#1923): 40 lines of 1,000 periods, 2,004 elements each, against a budget of 40,000.
|
||
#[test]
|
||
fn dashed_runs_past_the_build_dash_budget_are_drawn_continuous_and_counted() {
|
||
let d = dashed_lines(&[1000.0; 40]);
|
||
let full =
|
||
crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, MAX_DASH_ELEMENTS);
|
||
assert!(!full.truncated && full.undashed == 0);
|
||
let each = prims_per_entity(&full);
|
||
assert!(each.len() == 40 && each.iter().all(|n| *n > 1000), "{each:?}");
|
||
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 40_000);
|
||
let dashed = 40 - l.undashed;
|
||
assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed);
|
||
assert!(dashed * 2004 <= 40_000, "{dashed} lines dashed");
|
||
// The first lines keep their dashes; from the first that does not fit, each is one stroke.
|
||
let got = prims_per_entity(&l);
|
||
assert_eq!(got[..dashed], each[..dashed]);
|
||
assert!(got[dashed..].iter().all(|n| *n == 1), "{got:?}");
|
||
}
|
||
|
||
/// Parts built on all cores spend one dash budget, and their counts add up.
|
||
#[test]
|
||
fn dashed_runs_built_on_all_cores_share_the_dash_budget() {
|
||
// 600 lines of 100 periods (204 elements each): enough for the parallel build.
|
||
let d = dashed_lines(&[100.0; 600]);
|
||
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 20_000);
|
||
let dashed = 600 - l.undashed;
|
||
assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed);
|
||
assert!(dashed * 204 <= 20_000, "{dashed} lines dashed");
|
||
let each = prims_per_entity(&l);
|
||
assert_eq!(each.iter().filter(|n| **n == 1).count(), l.undashed, "{each:?}");
|
||
}
|
||
|
||
/// Model space seen through a layout viewport reports a run it draws continuous on the layout's
|
||
/// list too, and spends the layout's dash budget.
|
||
#[test]
|
||
fn runs_seen_through_a_viewport_are_counted_and_spend_the_layout_dash_budget() {
|
||
let mut d = dashed_lines(&[]);
|
||
// 3,000,000 periods, past the limit also at the viewport's linetype scale (PSLTSCALE); and
|
||
// 1,000 periods, within it.
|
||
for (y, len) in [(5.0, 2_250_000.0), (6.0, 750.0)] {
|
||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(len, y, 0.0) });
|
||
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, line).unwrap();
|
||
}
|
||
let paper = Space::Paper("Layout1".into());
|
||
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2))).unwrap();
|
||
let l = build_plot(&d, &paper, &Options::default());
|
||
assert!(l.prims.iter().any(|p| p.handle == VIEWPORT_CONTENT), "the lines show in the viewport");
|
||
assert!(l.truncated && l.undashed == 1, "{}", l.undashed);
|
||
let l = crate::pipeline::build_space_within(&d, &paper, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 100);
|
||
assert_eq!(l.undashed, 2);
|
||
}
|
||
|
||
/// Viewports after a spent layout build draw nothing, and the list says what they leave out: also
|
||
/// when the build was spent by a list filled exactly, before anything was left out. A list that
|
||
/// left out only dashes still draws them.
|
||
#[test]
|
||
fn viewports_after_a_spent_layout_build_say_what_they_leave_out() {
|
||
// A point seen through a rectangular viewport and then through a clipped one (which has no
|
||
// border), on a layout with a dashed line and the clip outline first: nothing on the layout
|
||
// after the viewports marks the list.
|
||
let paper = Space::Paper("Layout1".into());
|
||
let layout = |second_on: bool| {
|
||
let mut d = dashed_lines(&[]);
|
||
let point = EntityKind::Point(cadcraft_doc::Point { p: Vec3::new(5.0, 5.0, 0.0), angle: 0.0 });
|
||
d.add(&Space::Model, Common::default(), point).unwrap();
|
||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 12.0, 0.0), b: Vec3::new(750.0, 12.0, 0.0) });
|
||
d.add(&paper, Common { linetype: "DASHED".into(), ..Default::default() }, line).unwrap();
|
||
let vertices = [(20.0, 0.0), (30.0, 0.0), (30.0, 10.0), (20.0, 10.0)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec();
|
||
let square = cadcraft_doc::LwPolyline { vertices, closed: true, const_width: 0.0, elevation: 0.0, plinegen: false };
|
||
let outline = d.add(&paper, Common::default(), EntityKind::LwPolyline(square)).unwrap();
|
||
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 5.0), 10.0, 10.0, Vec2::new(5.0, 5.0), 10.0, 2))).unwrap();
|
||
let mut clipped = vp(Vec2::new(25.0, 5.0), 10.0, 10.0, Vec2::new(5.0, 5.0), 10.0, 3);
|
||
clipped.clip = Some(outline);
|
||
clipped.on = second_on;
|
||
d.add(&paper, Common::default(), EntityKind::Viewport(clipped)).unwrap();
|
||
d
|
||
};
|
||
let build = |d: &Drawing, max_points, max_dashes| {
|
||
crate::pipeline::build_space_within(d, &paper, &Options::default(), false, max_points, MAX_DISPLAY_PRIMS, max_dashes)
|
||
};
|
||
let shown = |l: &DisplayList| l.prims.iter().filter(|p| p.handle == VIEWPORT_CONTENT).count();
|
||
let (both, first) = (layout(true), layout(false));
|
||
let full = build(&both, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS);
|
||
assert!(!full.truncated && shown(&full) == 2, "{}", shown(&full));
|
||
// The layout up to the first viewport's point fills the list exactly: whole when the second
|
||
// viewport is off, and its point said to be left out when it is on.
|
||
let exact = points(&build(&first, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS));
|
||
let l = build(&first, exact, MAX_DASH_ELEMENTS);
|
||
assert!(!l.truncated && shown(&l) == 1, "{}", shown(&l));
|
||
let l = build(&both, exact, MAX_DASH_ELEMENTS);
|
||
assert!(l.truncated && shown(&l) == 1, "{}", shown(&l));
|
||
let l = build(&both, exact - 1, MAX_DASH_ELEMENTS);
|
||
assert!(l.truncated && shown(&l) == 0, "{}", shown(&l));
|
||
// The dashed line past the dash budget: drawn continuous, and both viewports drawn.
|
||
let l = build(&both, MAX_DISPLAY_POINTS, 100);
|
||
assert!(l.truncated && l.undashed == 1 && shown(&l) == 2, "{} {}", l.undashed, shown(&l));
|
||
}
|
||
|
||
/// A block reference cut by an XCLIP boundary is drawn apart and then joined: a run in it drawn
|
||
/// continuous is still counted.
|
||
#[test]
|
||
fn a_run_past_its_dash_limit_in_a_clipped_block_reference_is_counted() {
|
||
let mut d = dashed_lines(&[]);
|
||
let mut blk = cadcraft_doc::Block::new("B");
|
||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(1_000_001.0 * 0.75, 0.0, 0.0) });
|
||
blk.entities.push(block_entity(1, Common { linetype: "DASHED".into(), ..Default::default() }, line));
|
||
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
|
||
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
|
||
ins.clip = Some(cadcraft_doc::ClipBoundary::new(vec![Vec2::new(-1.0, -1.0), Vec2::new(10.0, 1.0)]));
|
||
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
|
||
let l = build_plot(&d, &Space::Model, &Options::default());
|
||
assert!(!l.prims.is_empty() && l.truncated && l.undashed == 1, "{}", l.undashed);
|
||
}
|
||
|
||
/// Text in a linetype is placed only on a run whose dashes were laid out: a line past the build's
|
||
/// dash budget is one stroke, without its texts.
|
||
#[test]
|
||
fn linetype_text_is_left_off_a_run_past_the_dash_budget() {
|
||
use cadcraft_doc::DashElement;
|
||
let mut d = Drawing::new_imperial();
|
||
let text = DashElement { text: Some("GAS".into()), style: Some("Standard".into()), scale: 0.1, ..DashElement::dash(-0.2) };
|
||
let pattern = vec![DashElement::dash(0.5), text, DashElement::dash(-0.25)];
|
||
d.linetypes.push(cadcraft_doc::Linetype { name: "GAS".into(), description: String::new(), pattern });
|
||
// Two lines of 100 periods, 306 elements each: the budget fits the first.
|
||
for y in [0.0, 1.0] {
|
||
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(95.0, y, 0.0) });
|
||
d.add(&Space::Model, Common { linetype: "GAS".into(), ..Default::default() }, line).unwrap();
|
||
}
|
||
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DISPLAY_PRIMS, 400);
|
||
let each = prims_per_entity(&l);
|
||
assert!(matches!(each.as_slice(), [first, 1] if *first > 101), "{each:?}");
|
||
assert_eq!(l.undashed, 1);
|
||
}
|