Merge pull request #2487 from 2ez4gcx/fix/linetype-dash-layout

Linetypes: lay dashes out as AutoCAD does
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 06:05:59 +01:00
commit d2587c694e
8 files changed
+575 -161

No files matched your search

+29 -20
View File
@@ -1,6 +1,7 @@
use super::blocks::{insert, proxy, sub_ctx};
use super::dim_draw::{MAX_FILL_SOLIDS, MAX_FILL_TEXTS, block_text_box, dim_text_fill, dimension, dimension_in, solid_covers, starts_text_marks};
use super::display::{Kind, NO_LAYER, VIEWPORT_CONTENT};
use super::linetype::Layout;
use super::props::{resolve, transparency};
use super::text_entity::{mtext, place_text_entity};
use super::{
@@ -89,11 +90,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
};
let tol = b.opts.tolerance / ctx.xf.scale_factor().max(1e-12);
let lw = if b.opts.lineweights { lw } else { 0.0 };
// Stroke a polyline with the entity's linetype.
let stroke = |b: &mut Builder, pts: &[Vec2]| match lt.as_ref().filter(|_| b.opts.linetypes) {
// Stroke a run with the entity's linetype, laid out as `how` says.
let stroke_as = |b: &mut Builder, pts: &[Vec2], how: Layout| match lt.as_ref().filter(|_| b.opts.linetypes) {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
for dash in linetype::apply(pts, lt, ltscale, min) {
for dash in linetype::apply_as(pts, lt, ltscale, min, how) {
if dash.len() == 1 {
if let Some(p) = dash.first() {
b.point(ctx, rgb, *p);
@@ -104,13 +105,31 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
}
// Text and shapes embedded in the linetype (shapes when their SHX file is found).
if b.opts.text {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min) {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min, how) {
b.shaped(ctx, rgb, lw, &sh);
}
}
}
None => b.polyline(ctx, rgb, lw, pts),
};
let stroke = |b: &mut Builder, pts: &[Vec2]| stroke_as(b, pts, Layout::Open);
// A polyline's centre line: with PLINEGEN the pattern runs along the whole of it (stretched
// around a closed one from its second vertex, as AutoCAD lays it); otherwise it restarts at
// every vertex.
let centre_line = |b: &mut Builder, p: &cadcraft_doc::LwPolyline| {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
if p.plinegen && p.closed {
stroke_as(b, &pl.tessellate(tol), Layout::Closed { anchor: wide::second_vertex_at(p, tol) });
} else if !b.opts.linetypes || p.plinegen || lt.is_none() {
stroke(b, &pl.tessellate(tol));
} else {
for s in pl.segments() {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
}
};
match &e.kind {
EntityKind::Text(t) => {
if !b.opts.text {
@@ -180,22 +199,11 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
}
}
} else {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
stroke(b, &pl.tessellate(tol));
}
}
EntityKind::LwPolyline(p) => {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
if !b.opts.linetypes || p.plinegen || lt.is_none() {
stroke(b, &pl.tessellate(tol));
} else {
for s in pl.segments() {
let mut pts = Vec::new();
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
// Fill off: the centre line, dashed as a polyline without width is.
centre_line(b, p);
}
}
EntityKind::LwPolyline(p) => centre_line(b, p),
EntityKind::Solid(s) | EntityKind::Trace(s) => {
let c = &s.corners;
let q = [c[0].xy(), c[1].xy(), c[3].xy(), c[2].xy()];
@@ -249,15 +257,16 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
s.tessellate(tol, &mut pts);
stroke(b, &pts);
}
// Closed runs from angle 0 (or the ellipse's start parameter).
Prim::Circle(c) => {
let mut pts = Vec::new();
c.tessellate(tol, &mut pts);
stroke(b, &pts);
stroke_as(b, &pts, Layout::Closed { anchor: 0.0 });
}
Prim::Ellipse(el) => {
let mut pts = Vec::new();
el.tessellate(tol, &mut pts);
stroke(b, &pts);
stroke_as(b, &pts, if el.is_full() { Layout::Closed { anchor: 0.0 } } else { Layout::Open });
}
Prim::Spline(s) => stroke(b, &s.tessellate(tol)),
Prim::Point(p) => b.point(ctx, rgb, p),
+392 -101
View File
@@ -1,117 +1,255 @@
//! Apply a dash pattern along a polyline.
//! Apply a dash pattern along a run (a polyline), laid out as AutoCAD lays it out.
//!
//! Measured on AutoCAD 2024 plots (DWG To PDF at a fixed scale, every stroke read back), with the
//! pattern [2, -1] unless said otherwise:
//! - An open run (a line, an arc, a spline, an open polyline with PLINEGEN, each segment of one
//! without) shorter than one period is drawn continuous. Otherwise the pattern is centred:
//! with n = floor(L / period) and p0 = (n·period + first − L) / 2, the elements sit where they
//! would if the pattern started at −p0, except that the first dash starts at the run's start
//! and the last ends at its end. A line 7 long gets [0, 1.5] [2.5, 4.5] [5.5, 7]; 6 gets
//! [0, 1] [2, 4] [5, 6]; 5.99 gets [0, 2.495] [3.495, 5.99]; 2.99 is continuous. A pattern
//! opening with a dot puts dots at both ends ([0, −1] on 5.3: 0, 1.15, 2.15, 3.15, 4.15, 5.3).
//! - A closed run (a circle, a whole ellipse, a closed polyline with PLINEGEN) is stretched to
//! n = round(L / period) periods, one starting at its anchor: a circle of radius 2 is dashed
//! 0°–60°, 90°–150°…; a 5 × 5 square polyline gets 7 periods.
//! - A pattern opening with a gap (e0 < 0), with r = L − n·period and x = (r + e0) / 2: for
//! x < 0 the elements run from −p0; otherwise a piece [0, x] is drawn (a dot when x is 0),
//! then the elements from the period's second on, n − 1 whole periods, and a last piece 2x
//! long.
use cadcraft_doc::Linetype;
use cadcraft_geom::Vec2;
/// Split `pts` into dashes. Dots come back as single-point runs. When the scaled pattern is
/// shorter than `min_pattern` (sub-pixel), the polyline is returned whole.
pub fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Vec<Vec2>> {
/// How a run lays its pattern out (see the module notes).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Layout {
/// Centred on an open run.
Open,
/// Stretched around a closed run, a period starting `anchor` along it.
Closed { anchor: f64 },
}
/// Most periods a run is dashed over in a display build (`min_pattern` above 0, a view zoomed out
/// a lot); a longer run is drawn continuous. A plot or export has no zoom (`min_pattern` is 0), so
/// it keeps the pattern, bounded by [`MAX_ELEMENTS`] (#1069).
const MAX_PERIODS: f64 = 50_000.0;
/// Most pattern elements a run is laid out over (a long pattern repeated many times); beyond
/// that it is drawn continuous too.
const MAX_ELEMENTS: f64 = 2_000_000.0;
/// The drawn stretches of a run `len` long, as (start, end) along it (a dot: start == end), in
/// order; `None` when it is drawn continuous (shorter than one period, or repeating too often).
/// `pattern` is scaled; `min_pattern` is the caller's (see [`MAX_PERIODS`]).
fn layout(len: f64, pattern: &[f64], how: Layout, min_pattern: f64) -> Option<Vec<(f64, f64)>> {
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
if !(len.is_finite() && period > 1e-12) || len < period || (min_pattern > 0.0 && len / period > MAX_PERIODS) {
return None;
}
if (len / period + 2.0) * pattern.len() as f64 > MAX_ELEMENTS {
return None;
}
let mut drawn = Vec::new();
let mut at = 0.0;
for &d in pattern {
if d >= 0.0 {
drawn.push((at, d));
}
at += d.abs();
}
if drawn.is_empty() {
return Some(Vec::new());
}
let first = pattern.first().copied().unwrap_or(0.0);
let out = match how {
Layout::Closed { anchor } => {
let n = (len / period).round().max(1.0);
let f = len / (n * period);
let a = if anchor.is_finite() { anchor.rem_euclid(period * f) } else { 0.0 };
let mut out = Vec::new();
for k in -1..=(n as i64) {
for &(o, e) in &drawn {
let s0 = a + k as f64 * period * f + o * f;
let s1 = s0 + e * f;
if e == 0.0 {
if (0.0..len).contains(&s0) {
out.push((s0, s0));
}
} else if s1.min(len) > s0.max(0.0) {
out.push((s0.max(0.0), s1.min(len)));
}
}
}
out
}
Layout::Open if first < 0.0 => gap_first(len, pattern, period),
Layout::Open => {
// A length at a multiple of the period: 6.0 / 3 is 2, not 1.
let n = (len / period + 1e-9).floor();
let p0 = (n * period + first - len) / 2.0;
let count = n as usize * drawn.len() + 1;
let mut out = Vec::with_capacity(count);
for i in 0..count {
let Some(&(o, e)) = drawn.get(i % drawn.len()) else { continue };
let mut s0 = (i / drawn.len()) as f64 * period + o - p0;
let mut s1 = s0 + e;
if i == 0 {
s0 = 0.0;
if first == 0.0 {
s1 = 0.0;
}
}
if i + 1 == count {
s1 = len;
if first == 0.0 {
s0 = len;
}
}
out.push((s0, s1));
}
out
}
};
Some(out)
}
/// [`layout`] of an open run for a pattern opening with a gap.
fn gap_first(len: f64, pattern: &[f64], period: f64) -> Vec<(f64, f64)> {
let first = pattern.first().copied().unwrap_or(0.0);
let n = (len / period + 1e-9).floor();
let x = (len - n * period + first) / 2.0;
let mut out = Vec::new();
if x < 0.0 {
let p0 = (n * period + first - len) / 2.0;
let mut u = 0.0;
for _ in 0..(n as usize + 2) {
for &e in pattern {
let (a, b) = (u, u + e.abs());
u = b;
if e < 0.0 {
continue;
}
let b = b.min(p0 + len);
if b > a.max(p0) || (e == 0.0 && (p0..=p0 + len).contains(&a)) {
out.push((a.max(p0) - p0, b - p0));
}
}
}
} else {
out.push((0.0, x));
let mut pos = x;
let whole = pattern.iter().cycle().take(pattern.len() * (n as usize).saturating_sub(1));
for &e in pattern.iter().skip(1).chain(whole) {
if e >= 0.0 {
out.push((pos, pos + e));
}
pos += e.abs();
}
if x > 0.0 {
out.push((pos, (pos + 2.0 * x).min(len)));
}
}
out.sort_by(|a, b| a.0.total_cmp(&b.0));
out
}
/// Length of a polyline.
fn length(pts: &[Vec2]) -> f64 {
pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum()
}
/// The pattern scaled, or `None` when a run is drawn continuous at any length: no pattern, or one
/// shorter than `min_pattern` (sub-pixel).
fn scaled(lt: &Linetype, scale: f64, min_pattern: f64) -> Option<Vec<f64>> {
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
if pts.len() < 2 || total <= 1e-12 || total < min_pattern {
return vec![pts.to_vec()];
}
// Guard against huge dash counts (zoomed out a lot): fall back to continuous.
let len: f64 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum();
if len / total > 50_000.0 {
return vec![pts.to_vec()];
}
let pattern: Vec<f64> = lt.pattern.iter().map(|d| d.length * scale).collect();
// AutoCAD centres the pattern so lines start and end with a dash: start at half the first dash.
let mut out: Vec<Vec<Vec2>> = Vec::new();
let mut cur: Vec<Vec2> = Vec::new();
let mut idx = 0usize;
let first = pattern.first().copied().unwrap_or(0.0);
let mut remaining = if first > 0.0 { first } else { first.abs() };
let mut on = first >= 0.0;
if on && first == 0.0 {
if let Some(p) = pts.first() {
out.push(vec![*p]);
}
idx = 1 % pattern.len();
let n = pattern.get(idx).copied().unwrap_or(0.0);
remaining = n.abs();
on = n > 0.0;
}
if on && let Some(p) = pts.first() {
cur.push(*p);
}
let mut guard = 0usize;
(total > 1e-12 && total >= min_pattern).then(|| lt.pattern.iter().map(|d| d.length * scale).collect())
}
/// The pieces of `pts` over `ranges` (in order along it), a dot as a single point.
fn cut(pts: &[Vec2], ranges: &[(f64, f64)]) -> Vec<Vec<Vec2>> {
let mut cum = Vec::with_capacity(pts.len());
let mut acc = 0.0;
cum.push(0.0);
for w in pts.windows(2) {
let (Some(&a), Some(&b)) = (w.first(), w.get(1)) else { continue };
let seg = a.dist(b);
if seg <= 1e-15 {
acc += w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0);
cum.push(acc);
}
let last = pts.len().saturating_sub(1).max(1);
// The point `s` along, and the index of the first vertex past it.
let at = |s: f64| -> (Vec2, usize) {
let j = cum.partition_point(|&c| c <= s).clamp(1, last);
let (Some(&a), Some(&b), Some(&ca), Some(&cb)) = (pts.get(j - 1), pts.get(j), cum.get(j - 1), cum.get(j)) else {
return (pts.first().copied().unwrap_or(Vec2::ZERO), j);
};
let t = if cb > ca { ((s - ca) / (cb - ca)).clamp(0.0, 1.0) } else { 0.0 };
(a + (b - a) * t, j)
};
let mut out = Vec::with_capacity(ranges.len());
for &(s0, s1) in ranges {
let (p, j) = at(s0);
if s1 <= s0 {
out.push(vec![p]);
continue;
}
let dir = (b - a) / seg;
let mut pos = 0.0;
while seg - pos > remaining {
guard += 1;
if guard > 2_000_000 {
return vec![pts.to_vec()];
}
pos += remaining;
let p = a + dir * pos;
if on {
cur.push(p);
out.push(std::mem::take(&mut cur));
}
idx = (idx + 1) % pattern.len();
let n = pattern.get(idx).copied().unwrap_or(0.0);
if n == 0.0 {
out.push(vec![p]);
idx = (idx + 1) % pattern.len();
let n2 = pattern.get(idx).copied().unwrap_or(0.0);
remaining = n2.abs();
on = n2 > 0.0;
} else {
remaining = n.abs();
on = n > 0.0;
}
if on {
cur.push(p);
let mut piece = vec![p];
let mut k = j;
while let (Some(&c), Some(&q)) = (cum.get(k), pts.get(k)) {
if c >= s1 {
break;
}
piece.push(q);
k += 1;
}
remaining -= seg - pos;
if on {
cur.push(b);
}
}
if cur.len() >= 2 {
out.push(cur);
piece.push(at(s1).0);
out.push(piece);
}
out
}
/// The dashes of the pattern along a run of length `len`, as (start, end) distances; a dot has
/// start == end. Laid out like [`apply`]. `None` when the run is drawn continuous: the scaled
/// pattern is shorter than `min_pattern` or would repeat too often.
pub fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64) -> Option<Vec<(f64, f64)>> {
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
if !(len.is_finite() && len > 0.0) || total <= 1e-12 || total < min_pattern || len / total > 50_000.0 {
return None;
/// Split `pts`, an open run, into dashes. Dots come back as single-point runs. A run shorter than
/// one period, or with a scaled pattern shorter than `min_pattern` (sub-pixel), comes back whole.
pub fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Vec<Vec2>> {
apply_as(pts, lt, scale, min_pattern, Layout::Open)
}
/// [`apply`] with the run laid out as `how` says.
pub fn apply_as(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Vec<Vec<Vec2>> {
let laid = if pts.len() >= 2 { scaled(lt, scale, min_pattern).and_then(|p| layout(length(pts), &p, how, min_pattern)) } else { None };
match laid {
Some(r) => cut(pts, &r),
None => vec![pts.to_vec()],
}
let mut out = Vec::new();
let mut pos = 0.0;
// Gap-only patterns draw nothing, matching `apply`, without walking every repeat.
if !lt.pattern.iter().any(|d| d.length >= 0.0) {
return Some(Vec::new());
}
// Bound the pattern elements visited, independent of emitted ranges, so a pattern that emits
// little still cannot cycle hundreds of millions of times.
let mut visits: u64 = 0;
for d in lt.pattern.iter().map(|d| d.length * scale).cycle() {
visits += 1;
if pos >= len || out.len() > 2_000_000 || visits > 4_000_000 {
break;
}
/// The dashes of the pattern along a run of length `len` laid out as `how` says, as (start, end)
/// distances; a dot has start == end. Laid out like [`apply_as`]. `None` when the run is drawn
/// continuous: shorter than one period, a scaled pattern shorter than `min_pattern`, or too many
/// repeats (see [`MAX_PERIODS`]).
pub fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Option<Vec<(f64, f64)>> {
if len > 0.0 { scaled(lt, scale, min_pattern).and_then(|p| layout(len, &p, how, min_pattern)) } else { None }
}
/// Where the pattern starts on a run `len` long laid out as `how`, and how much it is stretched:
/// period `k` starts at `start + k · period · stretch`. `None` when the run is drawn continuous.
pub fn phase(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Option<(f64, f64)> {
let pattern = scaled(lt, scale, min_pattern)?;
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
layout(len, &pattern, how, min_pattern)?;
let first = pattern.first().copied().unwrap_or(0.0);
Some(match how {
Layout::Open => {
let n = (len / period + 1e-9).floor();
let x = (len - n * period + first) / 2.0;
// A gap-first pattern with room for a piece of dash at the start ([`gap_first`]) has
// its second element at `x`, a gap after its period starts.
(if first < 0.0 && x >= 0.0 { x + first } else { x - first }, 1.0)
}
if d >= 0.0 {
out.push((pos, (pos + d).min(len)));
Layout::Closed { anchor } => {
let f = len / ((len / period).round().max(1.0) * period);
(if anchor.is_finite() { anchor.rem_euclid(period * f) } else { 0.0 }, f)
}
pos += d.abs();
}
Some(out)
})
}
#[cfg(test)]
@@ -122,7 +260,7 @@ mod tests {
#[test]
fn an_all_gap_pattern_draws_nothing_without_spinning() {
let lt = Linetype::simple("GAPS", "", &[-0.001, -0.002]);
assert_eq!(ranges(1.0, &lt, 1.0, 0.0), Some(Vec::new()));
assert_eq!(ranges(1.0, &lt, 1.0, 0.0, Layout::Open), Some(Vec::new()));
assert!(apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0).is_empty());
}
@@ -130,10 +268,11 @@ mod tests {
fn dashes_split_line() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 0.0);
// 3.0 / 0.75 = 4 patterns → 4 dashes.
assert_eq!(d.len(), 4);
assert!((d[0][1].x - 0.5).abs() < 1e-9);
assert!((d[1][0].x - 0.75).abs() < 1e-9);
// 3.0 / 0.75 = 4 periods, centred: a half dash at each end and four whole ones between.
assert_eq!(d.len(), 5);
assert!((d[0][1].x - 0.25).abs() < 1e-9);
assert!((d[1][0].x - 0.5).abs() < 1e-9);
assert!((d[4][0].x - 2.75).abs() < 1e-9 && (d[4][1].x - 3.0).abs() < 1e-9);
}
#[test]
@@ -157,4 +296,156 @@ mod tests {
let d = apply(&[Vec2::ZERO, Vec2::new(0.3, 0.0), Vec2::new(0.3, 1.0)], &lt, 1.0, 0.0);
assert_eq!(d[0].len(), 3); // the first dash turns the corner
}
/// The drawn stretches of a run, a continuous one as one stretch, with stretches that touch
/// joined (a plot draws them as one stroke).
fn drawn(len: f64, pattern: &[f64], how: Layout) -> Vec<(f64, f64)> {
let mut out: Vec<(f64, f64)> = Vec::new();
for (a, b) in layout(len, pattern, how, 0.0).unwrap_or_else(|| vec![(0.0, len)]) {
match out.last_mut() {
Some(last) if (last.1 - a).abs() < 1e-9 && b > a && last.1 > last.0 => last.1 = b,
_ => out.push((a, b)),
}
}
out
}
fn near(got: &[(f64, f64)], want: &[(f64, f64)], tol: f64) -> bool {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() <= tol && (g.1 - w.1).abs() <= tol)
}
/// AutoCAD 2024 plots (DWG To PDF at 10:1, every stroke read back to 0.01): open runs.
#[test]
fn open_runs_are_laid_out_as_autocad_plots_them() {
let dut = [2.0, -1.0];
for (len, want) in [
(7.0, vec![(0.0, 1.5), (2.5, 4.5), (5.5, 7.0)]),
(6.0, vec![(0.0, 1.0), (2.0, 4.0), (5.0, 6.0)]),
(5.99, vec![(0.0, 2.495), (3.495, 5.99)]),
(2.99, vec![(0.0, 2.99)]),
] {
assert!(near(&drawn(len, &dut, Layout::Open), &want, 1e-9), "{len}: {:?}", drawn(len, &dut, Layout::Open));
}
// A pattern opening with a dot: dots at both ends.
let dots = drawn(5.3, &[0.0, -1.0], Layout::Open);
assert!(near(&dots, &[(0.0, 0.0), (1.15, 1.15), (2.15, 2.15), (3.15, 3.15), (4.15, 4.15), (5.3, 5.3)], 1e-9), "{dots:?}");
// Patterns opening with a gap.
let (h1, h2, h3, h4) = ([-1.0, 2.0], [-0.5, 2.0, -0.5], [-1.0, 2.0, -2.0, 1.0], [-2.0, 1.0]);
let table: [(&[f64], f64, &[(f64, f64)]); 33] = [
(&h1, 3.0, &[(1.5, 3.0)]),
(&h1, 3.5, &[(1.75, 3.5)]),
(&h1, 4.0, &[(0.0, 0.0), (0.0, 2.0)]),
(&h1, 4.5, &[(0.0, 2.75)]),
(&h1, 5.0, &[(0.0, 3.5)]),
(&h1, 5.5, &[(0.0, 4.25)]),
(&h1, 6.0, &[(1.5, 3.5), (4.5, 6.0)]),
(&h1, 6.5, &[(1.75, 3.75), (4.75, 6.5)]),
(&h1, 7.0, &[(0.0, 0.0), (0.0, 2.0), (3.0, 5.0)]),
(&h1, 7.5, &[(0.0, 2.25), (3.25, 5.75)]),
(&h1, 8.0, &[(0.0, 2.5), (3.5, 6.5)]),
(&h1, 9.0, &[(1.5, 3.5), (4.5, 6.5), (7.5, 9.0)]),
(&h1, 10.0, &[(0.0, 0.0), (0.0, 2.0), (3.0, 5.0), (6.0, 8.0)]),
(&h1, 11.0, &[(0.0, 2.5), (3.5, 5.5), (6.5, 9.5)]),
(&h1, 12.5, &[(1.75, 3.75), (4.75, 6.75), (7.75, 9.75), (10.75, 12.5)]),
(&h1, 1.0, &[(0.0, 1.0)]),
(&h1, 2.0, &[(0.0, 2.0)]),
(&h1, 2.5, &[(0.0, 2.5)]),
(&h1, 2.9, &[(0.0, 2.9)]),
(&h2, 4.0, &[(0.0, 2.25), (2.75, 3.25)]),
(&h2, 5.0, &[(0.0, 2.75), (3.25, 4.75)]),
(&h2, 6.0, &[(0.75, 2.75), (3.75, 5.75)]),
(&h2, 7.0, &[(0.0, 2.25), (3.25, 5.25), (5.75, 6.25)]),
(&h2, 8.0, &[(0.0, 2.75), (3.75, 5.75), (6.25, 7.75)]),
(&h3, 10.0, &[(0.0, 3.5), (5.5, 9.5)]),
(&h3, 13.0, &[(0.0, 0.0), (0.0, 2.0), (4.0, 5.0), (6.0, 8.0), (10.0, 11.0)]),
(&h3, 15.5, &[(0.0, 3.25), (5.25, 6.25), (7.25, 9.25), (11.25, 14.75)]),
(&h4, 7.0, &[(3.5, 4.5), (6.5, 7.0)]),
(&h4, 8.0, &[(0.0, 0.0), (0.0, 1.0), (3.0, 4.0)]),
(&h4, 10.0, &[(3.5, 4.5), (6.5, 7.5), (9.5, 10.0)]),
(&h4, 2.0, &[(0.0, 2.0)]),
(&h2, 2.9, &[(0.0, 2.9)]),
(&h3, 5.9, &[(0.0, 5.9)]),
];
for (pattern, len, want) in table {
let got = drawn(len, pattern, Layout::Open);
assert!(near(&got, want, 0.006), "{pattern:?} on {len}: {got:?}");
}
}
/// Text in a linetype follows [`phase`]: it must say where the periods of a gap-first pattern
/// start on each side of the room left for a piece of dash at the start.
#[test]
fn phase_follows_the_dashes_of_a_gap_first_pattern() {
let lt = Linetype::simple("GF", "", &[-1.0, 2.0]);
for len in [6.5, 7.0, 7.5, 8.9, 12.5] {
let (start, f) = phase(len, &lt, 1.0, 0.0, Layout::Open).unwrap();
assert_eq!(f, 1.0);
// Every whole dash starts a gap (1) after a period (3) starts.
let whole: Vec<f64> =
ranges(len, &lt, 1.0, 0.0, Layout::Open).unwrap().into_iter().filter(|(a, b)| (b - a - 2.0).abs() < 1e-9).map(|(a, _)| a).collect();
assert!(!whole.is_empty(), "{len}");
for a in whole {
let k = (a - 1.0 - start) / 3.0;
assert!((k - k.round()).abs() < 1e-9, "{len}: a dash at {a}, periods from {start}");
}
}
}
/// Closed runs on the same plots: stretched to round(L / period) periods from their anchor.
#[test]
fn closed_runs_are_stretched_as_autocad_plots_them() {
let dut = [2.0, -1.0];
// A circle of radius 2 from angle 0: 0°–60°, 90°–150°, 180°–240°, 270°–330°.
let r = 2.0;
let got = drawn(std::f64::consts::TAU * r, &dut, Layout::Closed { anchor: 0.0 });
let want: Vec<(f64, f64)> =
[(0.0, 60.0), (90.0, 150.0), (180.0, 240.0), (270.0, 330.0)].map(|(a, b): (f64, f64)| (a.to_radians() * r, b.to_radians() * r)).into();
assert!(near(&got, &want, 1e-9), "{got:?}");
// Rectangles (PLINEGEN, closed), anchored at the second vertex: 4 × 4 has 5 periods of 3.2
// from s = 0.8, 5 × 5 has 7 (round, not floor) from 2.143, 2 × 3 from 2.0, 3 × 3 from 0.
for (w, h, periods, start) in [(4.0, 4.0, 5.0, 0.8), (5.0, 5.0, 7.0, 2.0 + 1.0 / 7.0), (2.0, 3.0, 3.0, 2.0), (3.0, 3.0, 4.0, 0.0)] {
let len = 2.0 * (w + h);
let got = drawn(len, &dut, Layout::Closed { anchor: w });
let dash = 2.0 * len / (3.0 * periods);
assert!(got.iter().any(|r| (r.0 - start).abs() < 1e-9 && (r.1 - r.0 - dash).abs() < 1e-9), "{w}×{h}: {got:?}");
}
}
/// A pattern too long for the run draws it continuous.
#[test]
fn a_run_shorter_than_one_period_is_continuous() {
let lt = Linetype::simple("DASHED", "", &[2.0, -1.0]);
assert_eq!(apply(&[Vec2::ZERO, Vec2::new(2.99, 0.0)], &lt, 1.0, 0.0).len(), 1);
assert_eq!(ranges(2.99, &lt, 1.0, 0.0, Layout::Open), None);
}
/// A long pattern repeated many times is drawn continuous rather than laid out element by
/// element: 100 elements over 40,000 periods is past the cap, 400 periods is not.
#[test]
fn a_long_pattern_repeated_too_often_is_continuous() {
let pattern: Vec<f64> = (0..100).map(|i| if i % 2 == 0 { 0.001 } else { -0.001 }).collect();
let lt = Linetype::simple("MANY", "", &pattern);
for how in [Layout::Open, Layout::Closed { anchor: 0.0 }] {
assert_eq!(ranges(4000.0, &lt, 1.0, 0.0, how), None, "{how:?}");
assert!(ranges(40.0, &lt, 1.0, 0.0, how).is_some_and(|r| r.len() > 10_000), "{how:?}");
}
}
/// A plot or export keeps the dashes of a run more than 50,000 periods long; a display build,
/// with a level of detail, draws it continuous (#1069).
#[test]
fn a_plot_keeps_the_dashes_of_a_run_of_many_periods() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let len = 50_001.0 * 0.75;
// Centred, the first and last dashes are halves: one more dash than periods.
for (how, dashes) in [(Layout::Open, 50_002), (Layout::Closed { anchor: 0.0 }, 50_001)] {
assert_eq!(ranges(len, &lt, 1.0, 0.0, how).map(|r| r.len()), Some(dashes), "{how:?}");
assert_eq!(ranges(len, &lt, 1.0, 1e-9, how), None, "{how:?}");
// Where linetype texts are placed from.
assert!(phase(len, &lt, 1.0, 0.0, how).is_some(), "{how:?}");
assert_eq!(phase(len, &lt, 1.0, 1e-9, how), None, "{how:?}");
}
let pts = [Vec2::ZERO, Vec2::new(len, 0.0)];
assert_eq!(apply(&pts, &lt, 1.0, 0.0).len(), 50_002);
assert_eq!(apply(&pts, &lt, 1.0, 1e-9).len(), 1);
}
}
+32 -22
View File
@@ -4,7 +4,8 @@
//! A dash element may carry a text (DXF `74` bit 2, `9` string) or a shape (`74` bit 4, `75`
//! shape number). As in a `.lin` definition, where the bracketed text or shape follows the dash
//! or gap that carries it, it is placed where that element ends, at every repeat of the pattern
//! (laid out from the start of the run like [`crate::linetype::apply`]):
//! (laid out on the run as [`crate::linetype::apply_as`] lays out its dashes, so none on a run
//! drawn continuous):
//! - height: the element's scale (`46`), times the text style's fixed height when it has one,
//! times the linetype scale;
//! - origin: the anchor shifted by the X/Y offsets (`44`/`45`, times the linetype scale) along
@@ -22,6 +23,8 @@ use cadcraft_doc::{Drawing, Linetype};
use cadcraft_fonts::{Shaped, TextParams};
use cadcraft_geom::Vec2;
use crate::linetype::Layout;
/// Upper bound on the texts and shapes drawn along one run (hostile scales; `apply` caps the
/// dashes).
const MAX_TEXTS: usize = 10_000;
@@ -47,8 +50,8 @@ struct Element {
/// The texts and shapes of `lt` along the polyline `pts`, in the coordinates of `pts`. Empty
/// when the linetype has none or its scaled pattern is drawn continuous (shorter than
/// `min_pattern`, or repeating too often).
pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Shaped> {
/// `min_pattern`, or, in a display build, repeating too often: see [`crate::linetype::phase`]).
pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Vec<Shaped> {
let mut out = Vec::new();
if pts.len() < 2 || !lt.pattern.iter().any(|e| e.text.as_deref().is_some_and(|t| !t.trim().is_empty()) || e.shape.is_some()) {
return out;
@@ -56,20 +59,25 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern:
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let total = lt.pattern_length() * scale;
let len: f64 = pts.windows(2).map(|w| w.first().zip(w.get(1)).map(|(a, b)| a.dist(*b)).unwrap_or(0.0)).sum();
if !(total.is_finite() && total > 1e-12 && len.is_finite()) || total < min_pattern || len / total > 50_000.0 {
if !(total.is_finite() && total > 1e-12 && len.is_finite()) || total < min_pattern {
return out;
}
let elements = elements(d, lt, scale);
let Some((start, stretch)) = crate::linetype::phase(len, lt, scale, min_pattern, how) else { return out };
if elements.is_empty() {
return out;
}
let mut walk = Walk { pts, i: 0, start: 0.0 };
let mut points_left = MAX_TEXT_POINTS;
let mut base = 0.0;
// From the period before the run's start (a centred or anchored pattern starts before it).
let mut base = start - total * stretch;
let mut points = 0usize;
'repeats: while base <= len {
for el in &elements {
let s = base + el.at;
let s = base + el.at * stretch;
if s < 0.0 {
continue;
}
points = points.saturating_add(point_count(&el.local));
if s > len + 1e-9 || out.len() >= MAX_TEXTS || points > MAX_POINTS {
break 'repeats;
@@ -83,7 +91,7 @@ pub fn texts(d: &Drawing, pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern:
sh.map(|q| origin + q.rotate(rot));
out.push(sh);
}
base += total;
base += total * stretch;
}
out
}
@@ -219,20 +227,20 @@ mod tests {
#[test]
fn one_text_per_repeat_at_the_end_of_its_element() {
let d = Drawing::new_imperial();
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 0.0);
// Pattern 0.95 long: anchors at 0.7 and 1.65.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 0.0, Layout::Open);
// Pattern 0.95 long, centred on the 2.0 run (p0 = 0.2): anchors at 0.7 − 0.2 and 1.65 − 0.2.
assert_eq!(t.len(), 2);
let x = starts(&t);
assert!(x[0] >= 0.69 && x[0] < 0.75, "{x:?}");
assert!(x[1] >= 1.64 && x[1] < 1.70, "{x:?}");
assert!(x[0] >= 0.49 && x[0] < 0.55, "{x:?}");
assert!(x[1] >= 1.44 && x[1] < 1.50, "{x:?}");
}
#[test]
fn no_text_when_drawn_continuous() {
let d = Drawing::new_imperial();
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 5.0).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &gas(), 1.0, 5.0, Layout::Open).is_empty());
let plain = Linetype::simple("DASHED", "", &[0.5, -0.25]);
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &plain, 1.0, 0.0).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &plain, 1.0, 0.0, Layout::Open).is_empty());
}
/// A long label repeated along a long run stops at the point allowance, well before MAX_TEXTS.
@@ -242,7 +250,7 @@ mod tests {
let mut lt = gas();
lt.pattern[1].text = Some("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM".into());
// 0.95 per repeat over 9,000: about 9,500 repeats, under the 50,000 the run is drawn for.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(9_000.0, 0.0)], &lt, 1.0, 0.0);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(9_000.0, 0.0)], &lt, 1.0, 0.0, Layout::Open);
let points: usize =
t.iter().map(|s| s.strokes.iter().map(Vec::len).sum::<usize>() + s.glyphs.iter().flatten().map(Vec::len).sum::<usize>()).sum();
assert!(!t.is_empty() && t.len() < MAX_TEXTS, "{}", t.len());
@@ -272,26 +280,28 @@ mod tests {
register_shapes();
let d = Drawing::new_imperial();
// An unnamed shape-file style reads as its file name (DXF); scale 0.1 per vector unit.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-render-lt.shx"), 1.0, 0.0);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-render-lt.shx"), 1.0, 0.0, Layout::Open);
// Laid out as the text above: the 0.95 pattern centred on the 2.0 run, anchors at 0.7 − 0.2
// and 1.65 − 0.2.
assert_eq!(t.len(), 2);
let x = starts(&t);
assert!((x[0] - 0.7).abs() < 1e-9 && (x[1] - 1.65).abs() < 1e-9, "{x:?}");
assert!((x[0] - 0.5).abs() < 1e-9 && (x[1] - 1.45).abs() < 1e-9, "{x:?}");
let ys = t[0].strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.y), b.max(p.y)));
assert!((ys.0).abs() < 1e-9 && (ys.1 - 0.2).abs() < 1e-9, "{ys:?}");
// Along a vertical line the shape turns with it; absolute rotation keeps it level.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(0.0, 2.0)], &fence("cadcraft-render-lt.shx"), 2.0, 0.0);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(0.0, 2.0)], &fence("cadcraft-render-lt.shx"), 2.0, 0.0, Layout::Open);
assert_eq!(t.len(), 1);
let xs = t[0].strokes.iter().flatten().fold((f64::MAX, f64::MIN), |(a, b), p| (a.min(p.x), b.max(p.x)));
assert!((xs.0 + 0.4).abs() < 1e-9 && xs.1.abs() < 1e-9, "{xs:?}");
// A named style whose font is the shape file.
let mut d = Drawing::new_imperial();
d.text_styles.push(cadcraft_doc::TextStyle { name: "SHAPES".into(), font: "cadcraft-render-lt.shx".into(), ..Default::default() });
assert_eq!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("SHAPES"), 1.0, 0.0).len(), 2);
assert_eq!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("SHAPES"), 1.0, 0.0, Layout::Open).len(), 2);
// A shape file that isn't found, or a shape it lacks, draws nothing.
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-no-such-file.shx"), 1.0, 0.0).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &fence("cadcraft-no-such-file.shx"), 1.0, 0.0, Layout::Open).is_empty());
let mut lt = fence("cadcraft-render-lt.shx");
lt.pattern[1].shape = Some(131);
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &lt, 1.0, 0.0).is_empty());
assert!(texts(&d, &[Vec2::ZERO, Vec2::new(2.0, 0.0)], &lt, 1.0, 0.0, Layout::Open).is_empty());
}
#[test]
@@ -304,7 +314,7 @@ mod tests {
let mut lt = fence("cadcraft-render-big.shx");
lt.pattern[1].shape = Some(131);
// 3,000 repeats would hold about 3 million points.
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2850.0, 0.0)], &lt, 1.0, 0.0);
let t = texts(&d, &[Vec2::ZERO, Vec2::new(2850.0, 0.0)], &lt, 1.0, 0.0, Layout::Open);
let points: usize = t.iter().map(point_count).sum();
assert!(!t.is_empty() && t.len() < 3000 && points <= MAX_POINTS, "{} shapes, {points} points", t.len());
}
@@ -345,7 +355,7 @@ mod tests {
}
let pts = [Vec2::ZERO, Vec2::ZERO, Vec2::new(1e6, 0.0), Vec2::new(1e6, 0.0)];
for scale in [f64::NAN, 0.0, -1.0, 1e-9, 1e300] {
let t = texts(&d, &pts, &lt, scale, 0.0);
let t = texts(&d, &pts, &lt, scale, 0.0, Layout::Open);
assert!(t.len() <= MAX_TEXTS);
}
}
+16 -4
View File
@@ -3,7 +3,7 @@
use cadcraft_doc::{Linetype, LwPolyline};
use cadcraft_geom::{MAX_TESSELLATED_POINTS, Polyline, Vec2};
use crate::linetype;
use crate::linetype::{self, Layout};
/// A point on the centre line: position, unit direction, half width and distance along the run.
#[derive(Clone, Copy, Debug)]
@@ -67,14 +67,26 @@ fn edges(x: &Sample) -> (Vec2, Vec2) {
(x.p + nrm, x.p - nrm)
}
/// How far along a closed PLINEGEN polyline, drawn from its first vertex, its second vertex lies
/// (an arc by its chords at `tol`): where the pattern stretched around it is anchored, as AutoCAD
/// lays it. 0 when the first two vertices coincide (`Polyline::segments` leaves that segment out).
pub(crate) fn second_vertex_at(p: &LwPolyline, tol: f64) -> f64 {
let first = Polyline { vertices: p.vertices.iter().take(2).copied().collect(), closed: false };
first.tessellate(tol).windows(2).map(|w| if let [a, b] = w { a.dist(*b) } else { 0.0 }).sum()
}
/// Triangles for the dashes of a wide polyline drawn with `lt` at `scale`, a line across the band
/// for each dot, and the centre line of each dash. With PLINEGEN the pattern runs along the whole
/// polyline; otherwise it restarts at every vertex. A pattern shorter than `min_pattern` fills
/// the whole band.
/// polyline (stretched around a closed one from its second vertex, as a thin one is); otherwise
/// it restarts at every vertex. A pattern shorter than `min_pattern` fills the whole band.
pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern: f64) -> (Vec<Vec2>, Vec<Vec<Vec2>>, Vec<Vec<Vec2>>) {
let mut budget = MAX_TESSELLATED_POINTS;
let mut runs = segments(p, tol, &mut budget);
let mut how = Layout::Open;
if p.plinegen && runs.len() > 1 {
if p.closed {
how = Layout::Closed { anchor: second_vertex_at(p, tol) };
}
let mut whole: Vec<Sample> = Vec::new();
for run in runs {
let base = whole.last().map(|x| x.s).unwrap_or(0.0);
@@ -87,7 +99,7 @@ pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern:
let mut centres = Vec::new();
for run in &runs {
let len = run.last().map(|x| x.s).unwrap_or(0.0);
let dashes = linetype::ranges(len, lt, scale, min_pattern).unwrap_or_else(|| vec![(0.0, len)]);
let dashes = linetype::ranges(len, lt, scale, min_pattern, how).unwrap_or_else(|| vec![(0.0, len)]);
for (a, b) in dashes {
if b - a <= 1e-12 {
if let Some(x) = at(run, a) {
+5 -1
View File
@@ -35,12 +35,16 @@ fn drawing(ltscale: f64, own: &str) -> Drawing {
d
}
/// The lengths of the dashes drawn for the reference, all but the last one (which may be cut).
/// The lengths of the dashes drawn for the reference, all but the first and the last (the
/// pattern is centred on the line, so those two may be cut).
fn dashes(d: &Drawing) -> Vec<f64> {
let l = build(d, &Space::Model, &Options::default());
let mut out: Vec<f64> =
l.prims.iter().filter(|p| p.kind == Kind::Polyline).map(|p| l.points(p).windows(2).map(|w| w[0].dist(w[1])).sum()).collect();
out.pop();
if !out.is_empty() {
out.remove(0);
}
out
}
+7 -5
View File
@@ -33,10 +33,11 @@ fn fenceline_draws_a_circle_in_every_gap() {
let (a, b) = (Vec2::ZERO, Vec2::new(9.5, 0.0));
let d = drawing(fence, a, b);
let marks = off_line(&d, &Options::default(), a, b);
// Pattern 0.25 on, 0.1 off, "o", 0.1 off, 0.5 on = 0.95: ten repeats along 9.5.
// Pattern 0.25 on, 0.1 off, "o", 0.1 off, 0.5 on = 0.95: ten repeats along 9.5, the pattern
// centred on it (p0 = (9.5 + 0.25 − 9.5) / 2 = 0.125, so it starts 0.125 before the line).
assert_eq!(marks.len(), 10, "{marks:?}");
for (i, m) in marks.iter().enumerate() {
let gap = i as f64 * 0.95 + 0.25;
let gap = i as f64 * 0.95 + 0.25 - 0.125;
assert!(m.min.x > gap && m.max.x < gap + 0.2, "mark {i} at {m:?} outside its gap");
// Centred on the line.
assert!((m.min.y + m.max.y).abs() < 0.01 && m.max.y > 0.02, "{m:?}");
@@ -72,9 +73,10 @@ fn text_follows_the_line_or_keeps_an_absolute_rotation() {
let marks = off_line(&drawing(gas(absolute), a, b), &Options::default(), a, b);
assert!(!marks.is_empty(), "absolute {absolute}: no text");
let all = Bounds2::from_points(marks.iter().flat_map(|m| [m.min, m.max]));
// Anchor 0.7 up the line, shifted 0.1 back along it and 0.05 to its right: the text
// starts at (0.05, 0.6).
assert!((all.min.y - 0.6).abs() < 0.01, "absolute {absolute}: {all:?}");
// The pattern centred on the line (p0 = (0.95 + 0.5 − 1) / 2 = 0.225): anchor 0.7 − 0.225
// up the line, shifted 0.1 back along it and 0.05 to its right: the text starts at
// (0.05, 0.375).
assert!((all.min.y - 0.375).abs() < 0.01, "absolute {absolute}: {all:?}");
if absolute {
assert!(all.width() > all.height(), "{all:?}");
assert!((all.min.x - 0.05).abs() < 0.01, "{all:?}");
+7 -5
View File
@@ -44,9 +44,10 @@ fn dash_lengths(d: &Drawing) -> Vec<f64> {
#[test]
fn psltscale_on_keeps_paper_dash_length() {
let dashes = dash_lengths(&drawing(1));
// 1000 model units = 10 paper units; 0.75-unit pattern on paper → about 13 dashes of 0.5.
// 1000 model units = 10 paper units; 0.75-unit pattern on paper → about 13 dashes of 0.5
// (centred on the line: the first and last may be shorter).
assert!((12..=15).contains(&dashes.len()), "{} dashes", dashes.len());
assert!(dashes.iter().take(dashes.len() - 1).all(|l| (l - 0.5).abs() < 1e-6), "{dashes:?}");
assert!(dashes.iter().skip(1).take(dashes.len() - 2).all(|l| (l - 0.5).abs() < 1e-6), "{dashes:?}");
}
#[test]
@@ -54,13 +55,14 @@ fn psltscale_off_scales_dashes_with_the_viewport() {
let dashes = dash_lengths(&drawing(0));
// Model-space dash length 0.5, shrunk 100x by the viewport.
assert!(dashes.len() > 1000, "{} dashes", dashes.len());
assert!(dashes.iter().take(dashes.len() - 1).all(|l| (l - 0.005).abs() < 1e-6));
assert!(dashes.iter().skip(1).take(dashes.len() - 2).all(|l| (l - 0.005).abs() < 1e-6));
}
#[test]
fn model_space_ignores_psltscale() {
let d = drawing(1);
let l = build(&d, &Space::Model, &Options::default());
let first = l.prims.iter().find(|p| p.kind == Kind::Polyline).map(|p| l.points(p).to_vec()).unwrap();
assert!((first[0].dist(first[1]) - 0.5).abs() < 1e-9);
// The second dash (the first is cut where the centred pattern meets the line's start).
let second = l.prims.iter().filter(|p| p.kind == Kind::Polyline).nth(1).map(|p| l.points(p).to_vec()).unwrap();
assert!((second[0].dist(second[1]) - 0.5).abs() < 1e-9);
}
+87 -3
View File
@@ -40,12 +40,96 @@ fn wide_polyline_dashes_are_filled_bands() {
assert!(dashed.iter().all(|q| (q.y.abs() - 0.1).abs() < 1e-9), "dashes keep the full width");
}
#[test]
fn a_band_more_than_50000_periods_long_keeps_its_dashes_without_a_level_of_detail() {
// 50,001 DASHED periods: two thirds of the band is dashes (0.5 of each 0.75, the end ones
// halves), as a plot or export draws it; a display build, with a level of detail, draws it
// whole (#1069).
let len = 50_001.0 * 0.75;
let d = drawing(&[0.0, len], "DASHED", false);
let dashed = area(&tris(&d));
assert!((dashed - 0.2 * len * 2.0 / 3.0).abs() < 1e-4, "{dashed}");
let l = build(&d, &Space::Model, &Options { min_dash: 1e-6, ..Default::default() });
let whole = area(&l.prims.iter().filter(|p| p.kind == Kind::Tris).flat_map(|p| l.points(p).to_vec()).collect::<Vec<_>>());
assert!((whole - 0.2 * len).abs() < 1e-4, "{whole}");
}
#[test]
fn a_closed_plinegen_band_is_stretched_around_as_a_thin_one_is() {
// A closed 10.5 square is 42 around: 56 DASHED periods laid from its second vertex, 10.5 along
// (a whole number of periods), so the first side has dashes at 0-0.5, 0.75-1.25…; laid as an
// open run they would be centred, at 0-0.25, 0.5-1.0….
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
let p = LwPolyline {
vertices: [(0.0, 0.0), (10.5, 0.0), (10.5, 10.5), (0.0, 10.5)].map(|(x, y)| PolyVertex::new(Vec2::new(x, y))).to_vec(),
closed: true,
const_width: 0.2,
elevation: 0.0,
plinegen: true,
};
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let t = tris(&d);
let on_first_side = |x: f64| t.iter().any(|q| (q.x - x).abs() < 1e-9 && q.y.abs() <= 0.1 + 1e-9);
assert!(on_first_side(0.75) && on_first_side(1.25) && !on_first_side(1.0), "{t:?}");
// With fill off only the centre line is drawn, laid out the same way.
d.header.set_i64("FILLMODE", 0);
let l = build(&d, &Space::Model, &Options::default());
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
let starts_at = |x: f64| starts.iter().any(|q| (q.x - x).abs() < 1e-9 && q.y.abs() < 1e-9);
assert!(starts_at(0.75) && !starts_at(0.5), "{starts:?}");
}
#[test]
fn a_closed_plinegen_run_is_anchored_at_its_second_vertex_after_an_arc() {
// The first segment is an arc (bulge 0.5): the pattern is measured along the run as drawn, so
// a dash starts right at the second vertex, without width and with fill off alike.
for width in [0.0, 0.2] {
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
d.header.set_i64("FILLMODE", 0);
let mut vertices: Vec<PolyVertex> =
[(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();
if let Some(v) = vertices.first_mut() {
v.bulge = 0.5;
}
let p = LwPolyline { vertices, closed: true, const_width: width, elevation: 0.0, plinegen: true };
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let l = build(&d, &Space::Model, &Options::default());
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
assert!(starts.iter().any(|q| q.dist(Vec2::new(10.0, 0.0)) < 1e-9), "{width}: {starts:?}");
}
}
#[test]
fn a_closed_plinegen_run_whose_first_two_vertices_coincide_is_anchored_at_them() {
// The zero-length first segment is left out of the drawn run, but the second vertex is still
// where the run starts: the 40-unit square is stretched to 53 DASHED periods from there, so
// dashes start at 0 and 40/53 (not 10 + k * 40/53, from the next vertex). Without width, with
// fill off, and with fill on (the band's centre line) alike.
for (width, fill) in [(0.0, 0), (0.2, 0), (0.2, 1)] {
let mut d = Drawing::new_imperial();
d.linetypes.extend(library::standard_linetypes().into_iter().filter(|l| l.name == "DASHED"));
d.header.set_i64("FILLMODE", fill);
let vertices: Vec<PolyVertex> =
[(0.0, 0.0), (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 = LwPolyline { vertices, closed: true, const_width: width, elevation: 0.0, plinegen: true };
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(p)).unwrap();
let l = build(&d, &Space::Model, &Options { min_dash: 1e-6, ..Default::default() });
let starts: Vec<Vec2> = l.prims.iter().filter(|p| p.kind == Kind::Polyline).filter_map(|p| l.points(p).first().copied()).collect();
for x in [0.0, 40.0 / 53.0] {
assert!(starts.iter().any(|q| q.dist(Vec2::new(x, 0.0)) < 1e-9), "{width} {fill} {x}: {starts:?}");
}
}
}
#[test]
fn plinegen_runs_the_pattern_along_the_whole_polyline() {
// Two 0.6 segments: per segment each gets one 0.5 dash; along the whole 1.2 the pattern
// gives 0.5 + 0.45.
// Two 0.6 segments: per segment each is shorter than the 0.75 pattern, so drawn continuous;
// along the whole 1.2 the centred pattern gives 0.475 + 0.475.
let per_segment = area(&tris(&drawing(&[0.0, 0.6, 1.2], "DASHED", false)));
let whole = area(&tris(&drawing(&[0.0, 0.6, 1.2], "DASHED", true)));
assert!((per_segment - 0.2).abs() < 1e-9, "{per_segment}");
assert!((per_segment - 0.24).abs() < 1e-9, "{per_segment}");
assert!((whole - 0.19).abs() < 1e-9, "{whole}");
}