render: a dash budget per build, and say when a run is drawn continuous

A dashed run is laid out over at most two million pattern elements, but
nothing bounded the total, and a pattern of mostly gaps visits many elements
for each point it draws, so the 64M-point display budget never stopped it:
1,000 lines on a 256-element pattern of gaps and one dash (a 58 KB DXF) took
11.6 s to PNG and 12.7 s to a 69 MB PDF on a dev build. A run past the
per-run limit was also drawn continuous without a word (#1069).

- MAX_DASH_ELEMENTS (64M, as many as the list's points) is charged by
  linetype::layout before a run is laid out, on a counter shared like the
  point budget's (parallel parts, XCLIP parts, viewport contents). Once a run
  does not fit, the rest of the build's dashed runs are drawn continuous.
  The per-run limit is MAX_RUN_DASH_ELEMENTS, unchanged.
- A run drawn continuous because of either limit sets DisplayList::truncated
  and counts in the new DisplayList::undashed, merged where lists are joined.
  Runs drawn continuous by rule (short, sub-pixel, the screen's 50,000-period
  level of detail) are not counted.
- cadcraft_io::write_framed_noted (and png/svg/pdf "noted" variants) return
  the note; cadcraft-cli convert and run --export print it.
- Linetype texts are placed only on a run whose dashes were laid out; phase
  checks the limits without laying the run out again.

On 11 real drawings the most a complete plot asked was 26.5M elements; a
16M total would have drawn 8,241 runs of that drawing solid. With 64M the
gap-pattern file takes 0.8 s / 0.4 s, the #1069 controls and three real
drawings export byte-identical, and the audit's dense dash/gap file stays as
on main (it fills the point budget at the same time).

Part of #1923 (F-05 f). Part of #1069: the app's EXPORT and PLOT don't show
the note yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2ez4gcxandClaude Opus 5.5 committed 2026-11-26 20:13:14 +07:00
1 parent edbdf0dd8f
commit c824e5e96a
21 files changed
+745 -83

No files matched your search

+5 -1
View File
@@ -145,10 +145,14 @@ pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result {
pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io: &mut Streams) -> Result {
let d = s.doc()?;
let bytes = cadcraft_io::write_framed(d, out, window)?;
let (bytes, notes) = cadcraft_io::write_framed_noted(d, out, window)?;
let folder = write_atomic(out, &bytes)?;
report_new_folder(folder, io);
io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len()));
// What the image draws short of the drawing (dashed runs past a dash limit drawn continuous).
for note in notes {
io.errln(format_args!("{}: {note}", out.display()));
}
if cadcraft_engine::cmd::file::drops_unknown(out) {
let lost = cadcraft_engine::cmd::file::not_saved(d);
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
@@ -0,0 +1,101 @@
//! `convert` to an image says how many dashed runs it drew continuous because of a dash limit
//! (#1069): a line whose DASHED pattern repeats past what one run may be laid out over. A line of
//! 50,001 periods, which an export keeps dashed, gets no note.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF of one line `periods` DASHED (0.5, -0.25) periods long.
fn dashed_line(periods: f64) -> String {
format!(
"0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
1
0
LTYPE
2
DASHED
70
0
3
Dashed
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
0
6
DASHED
10
0
20
0
11
{}
21
0
0
ENDSEC
0
EOF
",
periods * 0.75
)
}
#[test]
fn convert_to_an_image_notes_dashed_runs_drawn_continuous_past_the_dash_limit() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// (1,000,001 + 2) periods × 2 elements: past the two million one run may be laid out over.
let long = dir.join("long.dxf");
std::fs::write(&long, dashed_line(1_000_001.0)).unwrap();
let control = dir.join("control.dxf");
std::fs::write(&control, dashed_line(50_001.0)).unwrap();
let notes = |out: &Output| {
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("drawn continuous")).map(str::to_string).collect::<Vec<_>>()
};
for ext in ["png", "svg", "pdf"] {
let image = dir.join(format!("long.{ext}"));
let image = image.to_str().unwrap();
let got = notes(&cli(&["convert", long.to_str().unwrap(), image]));
assert!(matches!(got.as_slice(), [note] if note.starts_with(&format!("{image}: 1 dashed run "))), "{ext}: {got:?}");
let got = notes(&cli(&["convert", control.to_str().unwrap(), dir.join(format!("control.{ext}")).to_str().unwrap()]));
assert!(got.is_empty(), "{ext}: {got:?}");
}
// A DXF copy draws nothing, so there is nothing to note.
assert!(notes(&cli(&["convert", long.to_str().unwrap(), dir.join("copy.dxf").to_str().unwrap()])).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
+1
View File
@@ -1,4 +1,5 @@
mod cli;
mod dash_limit_note;
mod drafting_spacing;
mod help;
// DWG output needs craft-dwg's bridge.
+41 -10
View File
@@ -179,26 +179,50 @@ fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, craft_dwg::Unwri
/// extents. Formats that are not images (DXF, DWG) ignore the window. The window is checked with
/// [`check_window`].
pub fn write_framed(d: &Drawing, name: impl AsRef<Path>, window: Option<Bounds2>) -> Result<Vec<u8>> {
write_framed_noted(d, name, window).map(|(bytes, _)| bytes)
}
/// [`write_framed`], also returning what an image (PNG, SVG, PDF) draws short of the drawing
/// because of a render limit, one note each: the dashed runs drawn continuous
/// ([`undashed_note`]). DXF and DWG have none.
pub fn write_framed_noted(d: &Drawing, name: impl AsRef<Path>, window: Option<Bounds2>) -> Result<(Vec<u8>, Vec<String>)> {
let name = name.as_ref();
// A drawing template (.dwt) is DWG content.
let format = Format::from_path(name);
if format == Some(Format::Dwt) {
let mut dwg = name.as_os_str().to_owned();
dwg.push(".dwg");
return write_framed(d, PathBuf::from(dwg), None);
return write_framed_noted(d, PathBuf::from(dwg), None);
}
if let Some(w) = &window
&& is_image(name)
{
check_window(w)?;
}
match format {
Some(Format::Dxf | Format::Dwg) => write_with(d, name, &SaveOptions::default()),
Some(Format::Svg) => Ok(svg::export_window(d, &Space::Model, window).into_bytes()),
Some(Format::Png) => png_framed(d, &Space::Model, 2400, 1600, window),
Some(Format::Pdf) => pdf::pdf(d, &Space::Model, &PdfOptions { compress: true, window, ..PdfOptions::default() }),
_ => Err(IoError::Unsupported(ext(name))),
}
let (bytes, undashed) = match format {
Some(Format::Dxf | Format::Dwg) => (write_with(d, name, &SaveOptions::default())?, 0),
Some(Format::Svg) => {
let (svg, undashed) = svg::export_window_noted(d, &Space::Model, window);
(svg.into_bytes(), undashed)
}
Some(Format::Png) => png_framed_noted(d, &Space::Model, 2400, 1600, window)?,
Some(Format::Pdf) => pdf::pdf_noted(d, &Space::Model, &PdfOptions { compress: true, window, ..PdfOptions::default() })?,
_ => return Err(IoError::Unsupported(ext(name))),
};
Ok((bytes, undashed_note(undashed).into_iter().collect()))
}
/// The note for `n` dashed runs an output drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]), or `None` when there are none.
pub fn undashed_note(n: usize) -> Option<String> {
let runs = if n == 1 { "run" } else { "runs" };
(n > 0).then(|| {
format!(
"{n} dashed {runs} (each a line, a curve or a polyline segment) drawn continuous: past the dash limit of {} pattern elements per run or {} per drawing",
cadcraft_render::MAX_RUN_DASH_ELEMENTS,
cadcraft_render::MAX_DASH_ELEMENTS
)
})
}
/// Whether `name` is written as an image (PNG, SVG, PDF), i.e. whether framing applies to it.
@@ -238,10 +262,17 @@ pub fn png(d: &Drawing, space: &Space, width: u32, height: u32) -> Result<Vec<u8
/// extents (5% margin) when `window` is `None`. Objects are drawn with their transparency, as on
/// screen.
pub fn png_framed(d: &Drawing, space: &Space, width: u32, height: u32, window: Option<Bounds2>) -> Result<Vec<u8>> {
png_framed_noted(d, space, width, height, window).map(|(png, _)| png)
}
/// [`png_framed`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn png_framed_noted(d: &Drawing, space: &Space, width: u32, height: u32, window: Option<Bounds2>) -> Result<(Vec<u8>, usize)> {
let list = cadcraft_render::build(d, space, &cadcraft_render::Options { transparency: true, ..cadcraft_render::Options::default() });
let view = png_view(&list.bounds, width, height, window);
cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default())
.ok_or_else(|| IoError::Format("render failed".into()))
let png = cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default())
.ok_or_else(|| IoError::Format("render failed".into()))?;
Ok((png, list.undashed))
}
/// The raster view a PNG export uses.
+24 -5
View File
@@ -346,6 +346,12 @@ pub fn pdf(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<Vec<u8>> {
pdf_sheets(d, std::slice::from_ref(space), o)
}
/// [`pdf`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn pdf_noted(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<(Vec<u8>, usize)> {
pdf_items_noted(d, &sheet_items(std::slice::from_ref(space), o), o)
}
/// The name of a sheet: `Model` or the layout's.
fn sheet_name(space: &Space) -> String {
space.tab_name().to_string()
@@ -354,17 +360,27 @@ fn sheet_name(space: &Space) -> String {
/// Write a vector PDF with one page per space (at most [`MAX_PAGES`]), each labelled with its
/// layout name. The options apply to every sheet; layouts use their own page setups.
pub fn pdf_sheets(d: &Drawing, spaces: &[Space], o: &PdfOptions) -> Result<Vec<u8>> {
pdf_items(d, &sheet_items(spaces, o), o)
}
/// The items [`pdf_sheets`] plots: each space with `o`, at most one past [`MAX_PAGES`].
fn sheet_items(spaces: &[Space], o: &PdfOptions) -> Vec<(Space, PdfOptions)> {
// Links are file-wide (`pdf_items` reads them from `o`), so a sheet's own options carry none:
// a copy of the list per sheet multiplied it by the sheet count.
let sheet = PdfOptions { links: Vec::new(), ..o.clone() };
let items: Vec<(Space, PdfOptions)> = spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), sheet.clone())).collect();
pdf_items(d, &items, o)
spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), sheet.clone())).collect()
}
/// Write a vector PDF with one page per `(space, options)` item (at most [`MAX_PAGES`]): each
/// page plots with its own options (window, paper, orientation); `o` supplies the file-wide
/// ones (compression, title, layers, links).
pub fn pdf_items(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions) -> Result<Vec<u8>> {
pdf_items_noted(d, items, o).map(|(bytes, _)| bytes)
}
/// [`pdf_items`], also returning the dashed runs its pages drew continuous because of a dash
/// limit ([`cadcraft_render::DisplayList::undashed`]).
pub fn pdf_items_noted(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions) -> Result<(Vec<u8>, usize)> {
if items.iter().any(|(_, io)| io.offset.is_some_and(|offset| !valid_plot_offset(offset))) {
return Err(IoError::Format("plot offset must contain two finite values within ±100000 mm".into()));
}
@@ -420,8 +436,9 @@ impl Failure {
}
/// Write the file, one sheet at a time: each sheet's display list is built, written as its page
/// and dropped before the next.
fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as_geometry: bool) -> std::result::Result<Vec<u8>, Failure> {
/// and dropped before the next. Also the dashed runs the pages drew continuous because of a dash
/// limit ([`cadcraft_render::DisplayList::undashed`]).
fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as_geometry: bool) -> std::result::Result<(Vec<u8>, usize), Failure> {
write::guard(|| {
// Layers that are off plot on PDF layers that start hidden: draw them from a copy with
// them on.
@@ -456,6 +473,7 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as
// Link annotations of the whole file: each page keeps its own copy of the targets, so the
// pages times the links must not multiply without a bound.
let mut annotations_left = MAX_FILE_ANNOTATIONS;
let mut undashed = 0usize;
for (s, po) in items {
// Once the budget is spent no link is built (scanned and cloned) for later pages.
let mut page = sheet(drawn, s, po, if annotations_left == 0 { &links[..0] } else { &links })?;
@@ -467,11 +485,12 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as
// Groups are added to the document, so they must exist before the page starts.
groups.add(doc, d, &page.layers);
write_page(doc, &page, &groups, &mut fonts)?;
undashed = undashed.saturating_add(page.list.undashed);
}
if items.len() == 1 && !groups.ids.is_empty() {
writer.document_mut().set_optional_content_page_mode(true);
}
Ok(writer.finish()?)
Ok((writer.finish()?, undashed))
})
}
+12 -1
View File
@@ -17,10 +17,21 @@ pub fn export_window(d: &Drawing, space: &Space, window: Option<Bounds2>) -> Str
export_window_with(d, space, window, true)
}
/// [`export_window`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn export_window_noted(d: &Drawing, space: &Space, window: Option<Bounds2>) -> (String, usize) {
export_noted(d, space, window, true)
}
/// [`export_window`], drawing transparency only when `transparency` is on (plots).
pub fn export_window_with(d: &Drawing, space: &Space, window: Option<Bounds2>, transparency: bool) -> String {
export_noted(d, space, window, transparency).0
}
/// [`export_window_with`] and the list's [`cadcraft_render::DisplayList::undashed`].
fn export_noted(d: &Drawing, space: &Space, window: Option<Bounds2>, transparency: bool) -> (String, usize) {
let list = cadcraft_render::build(d, space, &cadcraft_render::Options { transparency, ..cadcraft_render::Options::default() });
export_list(&list, window)
(export_list(&list, window), list.undashed)
}
/// Opacity for a transparent primitive (none for an opaque one or a wipeout's mask).
+153
View File
@@ -0,0 +1,153 @@
//! The controls of #1069: one line of 49,999 or of 50,001 DASHED (0.5, -0.25) periods, as the
//! issue's generator writes it. A plot or export keeps the pattern on both: the PDF strokes a
//! subpath per dash and a close-up PNG of the line's start shows its gaps.
use cadcraft_doc::{Drawing, Space};
use cadcraft_geom::{Bounds2, Vec2};
use cadcraft_io::PdfOptions;
/// One line on layer L1 with linetype DASHED, `periods` periods long.
fn control(periods: f64) -> Drawing {
let len = periods * 0.75;
let dxf = format!(
"0
SECTION
2
HEADER
9
$ACADVER
1
AC1032
9
$INSUNITS
70
4
9
$LTSCALE
40
1.0
0
ENDSEC
0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
2
0
LTYPE
2
CONTINUOUS
70
0
3
Solid line
72
65
73
0
40
0.0
0
LTYPE
2
DASHED
70
0
3
Dashed 0.5/0.25
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
TABLE
2
LAYER
70
1
0
LAYER
2
L1
70
0
62
7
6
DASHED
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
L1
6
DASHED
10
0.0
20
0.0
30
0.0
11
{len}
21
0.0
31
0.0
0
ENDSEC
0
EOF
"
);
cadcraft_io::read(dxf.as_bytes(), "control.dxf").unwrap()
}
/// Runs of inked columns across the middle rows of `png` (a horizontal line through its centre):
/// one for a continuous line, one per dash for a dashed one.
fn dashes_across_the_middle(png: &[u8]) -> usize {
let r = cadcraft_io::raster::decode(png).unwrap();
let (w, h) = (r.width(), r.height());
let paper = r.pixel(0, 0);
let inked = |x: u32| (h / 2 - 3..=h / 2 + 3).any(|y| r.pixel(x, y) != paper);
(0..w).filter(|&x| inked(x) && (x == 0 || !inked(x - 1))).count()
}
#[test]
fn the_49_999_and_50_001_period_controls_keep_their_dashes_in_pdf_and_png() {
for periods in [49_999.0, 50_001.0] {
let d = control(periods);
let pdf = cadcraft_io::pdf(&d, &Space::Model, &PdfOptions { compress: false, ..PdfOptions::default() }).unwrap();
let doc = crate::pdf_read::read(&pdf);
let dashes = crate::pdf_read::drawn(doc.content()).iter().filter(|o| o.op == "m").count();
assert!(dashes > periods as usize, "{periods} periods: {dashes} dashes in the PDF");
// As `cadcraft-cli convert --window 0,-3,60,3`: 80 periods fill the image.
let png = cadcraft_io::write_framed(&d, "close.png", Some(Bounds2::new(Vec2::new(0.0, -3.0), Vec2::new(60.0, 3.0)))).unwrap();
let shown = dashes_across_the_middle(&png);
assert!(shown > 60, "{periods} periods: {shown} dashes across the close-up");
}
}
+1
View File
@@ -12,6 +12,7 @@ mod attrib_props;
mod block_expansion;
mod closed_spline;
mod codepages;
mod dash_controls;
mod dim_block_resave_roundtrip;
mod dim_block_text;
mod dim_marks_roundtrip;
+1
View File
@@ -108,6 +108,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
if let (Some(part), Some((region, inverted))) = (part, &clip) {
b.list.expanded = part.list.expanded;
b.list.truncated |= part.list.truncated;
b.list.undashed = b.list.undashed.saturating_add(part.list.undashed);
append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) });
xclip_frame(b, ctx, region, rgb);
}
+10 -3
View File
@@ -108,10 +108,16 @@ pub struct DisplayList {
/// Block contents expanded while building (see [`MAX_BLOCK_EXPANSION`]).
pub expanded: usize,
/// The block-expansion budget or the point budget ([`crate::MAX_DISPLAY_POINTS`]) was spent:
/// block contents or objects past it are not in the list. The screen,
/// plots and exports draw what is here; the CLI and the control channel report this, so an
/// output that leaves contents out is never silent (#1070).
/// block contents or objects past it are not in the list; or a dashed run was drawn
/// continuous past a dash limit ([`DisplayList::undashed`]). The screen,
/// plots and exports draw what is here; the control channel and the MCP render report this,
/// so an output that leaves contents out is never silent (#1070).
pub truncated: bool,
/// Dashed runs drawn continuous because of a dash limit: one run repeating its pattern past
/// [`crate::MAX_RUN_DASH_ELEMENTS`], or the build past [`crate::MAX_DASH_ELEMENTS`] (#1069). Runs drawn
/// continuous by rule (shorter than one period, a pattern under two pixels or, on screen, past
/// 50,000 periods) are not counted.
pub undashed: usize,
/// Plot style end, join and fill style per primitive (parallel to `prims`; missing entries
/// are "use object"), turned into geometry by [`pen::apply`].
pub pens: Vec<Pen>,
@@ -210,4 +216,5 @@ pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) {
dst.bounds = dst.bounds.union(&src.bounds);
dst.expanded = dst.expanded.saturating_add(src.expanded);
dst.truncated |= src.truncated;
dst.undashed = dst.undashed.saturating_add(src.undashed);
}
+8 -5
View File
@@ -94,7 +94,9 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
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_as(pts, lt, ltscale, min, how) {
let dashes = linetype::apply_as(pts, lt, ltscale, min, how, b);
let laid = dashes.is_some();
for dash in dashes.unwrap_or_else(|| vec![pts.to_vec()]) {
if dash.len() == 1 {
if let Some(p) = dash.first() {
b.point(ctx, rgb, *p);
@@ -103,8 +105,9 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
b.polyline(ctx, rgb, lw, &dash);
}
}
// Text and shapes embedded in the linetype (shapes when their SHX file is found).
if b.opts.text {
// Text and shapes embedded in the linetype (shapes when their SHX file is found), on
// a run whose dashes were laid out.
if b.opts.text && laid {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min, how) {
b.shaped(ctx, rgb, lw, &sh);
}
@@ -176,7 +179,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
// Dashed: each dash a filled piece of the band; dots a line across it.
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
let (tris, ticks, centres) = wide::dashed(p, tol, lt, ltscale, min);
let (tris, ticks, centres) = wide::dashed(p, tol, lt, ltscale, min, b);
b.tris(ctx, rgb, &tris);
if hairline {
for c in &centres {
@@ -421,7 +424,7 @@ pub(crate) fn stroke_with(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Opt
match lt.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(pts, lt, ltscale, min, b) {
match dash.as_slice() {
[p] => b.point(ctx, rgb, *p),
_ => b.polyline(ctx, rgb, lw, &dash),
+36
View File
@@ -130,6 +130,10 @@ struct Builder<'a> {
points: &'a std::sync::atomic::AtomicUsize,
/// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests).
max_points: usize,
/// Dash pattern elements the whole build has laid out so far, shared like `points`.
dashes: &'a std::sync::atomic::AtomicUsize,
/// The most dash pattern elements the build may lay out: [`MAX_DASH_ELEMENTS`] (less in tests).
max_dashes: usize,
}
/// Upper bound on the block contents drawn per display list (each block reference, MINSERT copy
@@ -148,6 +152,21 @@ pub const MAX_BLOCK_EXPANSION: usize = 2_000_000;
/// for a plot) is expected to hold a few tens of millions.
pub const MAX_DISPLAY_POINTS: usize = 64_000_000;
/// Upper bound on the dash pattern elements one dashed run (a line, an arc, a polyline segment or
/// a PLINEGEN polyline) is laid out over: a longer pattern repeated more often is drawn
/// continuous, and [`DisplayList::undashed`] counts it. A plot keeps the dashes of a run of any
/// number of periods up to this (#1069).
pub const MAX_RUN_DASH_ELEMENTS: usize = 2_000_000;
/// Upper bound on the dash pattern elements one display list lays out over all its dashed runs.
/// Each run may visit up to [`MAX_RUN_DASH_ELEMENTS`], and a pattern of mostly gaps visits many
/// elements for each point it draws, so a small file of many long lines walked millions of
/// elements per line with nothing to stop it, [`MAX_DISPLAY_POINTS`] included (#1923). The limit is
/// as many elements as the list may hold points: a dash and its gap make about one point per
/// element, so a drawing whose dashes fit the point budget keeps them. Past it later dashed runs
/// are drawn continuous, and [`DisplayList::undashed`] counts them.
pub const MAX_DASH_ELEMENTS: usize = 64_000_000;
impl<'a> Builder<'a> {
/// `color` and `lw` as the plot style table prints them.
fn styled(&self, color: Ink, lw: f32) -> (Ink, f32) {
@@ -370,6 +389,8 @@ impl<'a> Builder<'a> {
transparency: self.transparency,
points: self.points,
max_points: self.max_points,
dashes: self.dashes,
max_dashes: self.max_dashes,
}
}
/// Take one unit of the block-expansion budget; false once it is spent, or once the build
@@ -404,6 +425,21 @@ impl<'a> Builder<'a> {
}
}
/// The build's dash budget ([`MAX_DASH_ELEMENTS`]), charged as [`Builder::charge`] charges
/// points: once a run does not fit, the count is past the limit and every later run is drawn
/// continuous. The runs laid out never pass the limit; the count itself passes it by at most one
/// run per thread building in parallel.
impl linetype::Budget for Builder<'_> {
fn take(&mut self, visits: usize) -> bool {
use std::sync::atomic::Ordering::Relaxed;
self.dashes.load(Relaxed) < self.max_dashes && self.dashes.fetch_add(visits, Relaxed).saturating_add(visits) <= self.max_dashes
}
fn refused(&mut self) {
self.list.undashed = self.list.undashed.saturating_add(1);
self.list.truncated = true;
}
}
/// The clip boundary of image `i` as a closed outline, or `None` when the whole image shows.
/// `place` gives the position of a point of the entity's pixel grid (x right, y down from the
/// top-left corner of the image).
+128 -39
View File
@@ -35,20 +35,40 @@ pub enum Layout {
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;
/// that it is drawn continuous too, and the build says so ([`Budget::refused`]).
const MAX_ELEMENTS: f64 = crate::MAX_RUN_DASH_ELEMENTS as f64;
/// 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)>> {
/// Where a build's dash work is charged ([`crate::Builder`], against
/// [`crate::MAX_DASH_ELEMENTS`]): asked before a run's pattern elements are visited.
pub(crate) trait Budget {
/// Take `visits` pattern elements for one run; false when the build may not spend them, and
/// the run is drawn continuous.
fn take(&mut self, visits: usize) -> bool;
/// A run is drawn continuous because of a limit: its own ([`MAX_ELEMENTS`]) or the build's.
fn refused(&mut self);
}
/// The pattern elements [`layout`] visits on a run `len` long, or `None` when the run is drawn
/// continuous whatever the limits: shorter than one period, or past [`MAX_PERIODS`] in a display
/// build. `pattern` is scaled.
fn visits(len: f64, pattern: &[f64], min_pattern: f64) -> Option<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 {
Some((len / period + 2.0) * pattern.len() as f64)
}
/// 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 (see [`visits`]), also when it repeats past
/// [`MAX_ELEMENTS`] or `budget` refuses it. `pattern` is scaled; `min_pattern` is the caller's.
fn layout(len: f64, pattern: &[f64], how: Layout, min_pattern: f64, budget: &mut impl Budget) -> Option<Vec<(f64, f64)>> {
let elements = visits(len, pattern, min_pattern)?;
if elements > MAX_ELEMENTS {
budget.refused();
return None;
}
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
let mut drawn = Vec::new();
let mut at = 0.0;
for &d in pattern {
@@ -60,6 +80,11 @@ fn layout(len: f64, pattern: &[f64], how: Layout, min_pattern: f64) -> Option<Ve
if drawn.is_empty() {
return Some(Vec::new());
}
// At most MAX_ELEMENTS here, so the cast is exact enough to charge.
if !budget.take(elements.ceil() as usize) {
budget.refused();
return None;
}
let first = pattern.first().copied().unwrap_or(0.0);
let out = match how {
Layout::Closed { anchor } => {
@@ -208,34 +233,37 @@ fn cut(pts: &[Vec2], ranges: &[(f64, f64)]) -> Vec<Vec<Vec2>> {
}
/// 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)
/// one period, or with a scaled pattern shorter than `min_pattern` (sub-pixel), comes back whole,
/// as does one past a limit (see [`layout`]).
pub(crate) fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, budget: &mut impl Budget) -> Vec<Vec<Vec2>> {
apply_as(pts, lt, scale, min_pattern, Layout::Open, budget).unwrap_or_else(|| vec![pts.to_vec()])
}
/// [`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()],
/// [`apply`] with the run laid out as `how` says; `None` when the run is drawn continuous.
pub(crate) fn apply_as(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout, budget: &mut impl Budget) -> Option<Vec<Vec<Vec2>>> {
if pts.len() < 2 {
return None;
}
let pattern = scaled(lt, scale, min_pattern)?;
layout(length(pts), &pattern, how, min_pattern, budget).map(|r| cut(pts, &r))
}
/// 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 }
/// continuous: shorter than one period, a scaled pattern shorter than `min_pattern`, too many
/// repeats (see [`MAX_PERIODS`]), or past a limit (see [`layout`]).
pub(crate) fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout, budget: &mut impl Budget) -> Option<Vec<(f64, f64)>> {
if len > 0.0 { scaled(lt, scale, min_pattern).and_then(|p| layout(len, &p, how, min_pattern, budget)) } 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.
/// period `k` starts at `start + k · period · stretch`. `None` when the run is drawn continuous
/// whatever the build's budget ([`visits`], [`MAX_ELEMENTS`]); the caller places texts only on a
/// run whose dashes were laid out.
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)?;
visits(len, &pattern, min_pattern).filter(|v| *v <= MAX_ELEMENTS)?;
let first = pattern.first().copied().unwrap_or(0.0);
Some(match how {
Layout::Open => {
@@ -256,18 +284,28 @@ pub fn phase(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout)
mod tests {
use super::*;
/// No build: every run within its own limit is laid out.
struct Free;
impl Budget for Free {
fn take(&mut self, _: usize) -> bool {
true
}
fn refused(&mut self) {}
}
/// This gap-only pattern draws nothing, and `ranges` returns before cycling through its repeats.
#[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, Layout::Open), Some(Vec::new()));
assert!(apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0).is_empty());
assert_eq!(ranges(1.0, &lt, 1.0, 0.0, Layout::Open, &mut Free), Some(Vec::new()));
assert!(apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0, &mut Free).is_empty());
}
#[test]
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);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 0.0, &mut Free);
// 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);
@@ -278,7 +316,7 @@ mod tests {
#[test]
fn dots_are_single_points() {
let lt = Linetype::simple("DOT", "", &[0.0, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0);
let d = apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0, &mut Free);
assert!(d.iter().all(|r| r.len() == 1));
assert!(d.len() >= 4);
}
@@ -286,21 +324,21 @@ mod tests {
#[test]
fn tiny_pattern_is_continuous() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 10.0);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 10.0, &mut Free);
assert_eq!(d.len(), 1);
}
#[test]
fn dash_continues_across_vertices() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(0.3, 0.0), Vec2::new(0.3, 1.0)], &lt, 1.0, 0.0);
let d = apply(&[Vec2::ZERO, Vec2::new(0.3, 0.0), Vec2::new(0.3, 1.0)], &lt, 1.0, 0.0, &mut Free);
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)]) {
for (a, b) in layout(len, pattern, how, 0.0, &mut Free).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)),
@@ -380,8 +418,12 @@ mod tests {
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();
let whole: Vec<f64> = ranges(len, &lt, 1.0, 0.0, Layout::Open, &mut Free)
.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;
@@ -414,8 +456,8 @@ mod tests {
#[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);
assert_eq!(apply(&[Vec2::ZERO, Vec2::new(2.99, 0.0)], &lt, 1.0, 0.0, &mut Free).len(), 1);
assert_eq!(ranges(2.99, &lt, 1.0, 0.0, Layout::Open, &mut Free), None);
}
/// A long pattern repeated many times is drawn continuous rather than laid out element by
@@ -425,11 +467,58 @@ mod tests {
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:?}");
assert_eq!(ranges(4000.0, &lt, 1.0, 0.0, how, &mut Free), None, "{how:?}");
assert!(ranges(40.0, &lt, 1.0, 0.0, how, &mut Free).is_some_and(|r| r.len() > 10_000), "{how:?}");
// Linetype text follows: none on the continuous run.
assert_eq!(phase(4000.0, &lt, 1.0, 0.0, how), None, "{how:?}");
assert!(phase(40.0, &lt, 1.0, 0.0, how).is_some(), "{how:?}");
}
}
/// A budget of `left` elements that counts the runs it is told were refused.
struct Left {
left: usize,
refused: usize,
}
impl Budget for Left {
fn take(&mut self, visits: usize) -> bool {
self.left.checked_sub(visits).map(|left| self.left = left).is_some()
}
fn refused(&mut self) {
self.refused += 1;
}
}
/// A run is charged to the build's budget before it is laid out, and drawn whole and refused
/// when it does not fit. A run past its own limit is refused without being charged; one
/// drawn continuous by rule, or a pattern of gaps only, is neither charged nor refused.
#[test]
fn runs_are_charged_to_the_budget_and_refused_past_it() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
// 1,000 periods: 2,000 elements and more.
let pts = [Vec2::ZERO, Vec2::new(750.0, 0.0)];
let mut b = Left { left: 3000, refused: 0 };
assert!(apply(&pts, &lt, 1.0, 0.0, &mut b).len() > 1000);
assert!(b.left <= 1000 && b.refused == 0, "{}", b.left);
assert_eq!(apply(&pts, &lt, 1.0, 0.0, &mut b), vec![pts.to_vec()]);
assert_eq!(apply_as(&pts, &lt, 1.0, 0.0, Layout::Closed { anchor: 0.0 }, &mut b), None);
assert_eq!(b.refused, 2);
let mut b = Left { left: usize::MAX, refused: 0 };
assert_eq!(ranges(1_000_001.0 * 0.75, &lt, 1.0, 0.0, Layout::Open, &mut b), None);
assert_eq!((b.left, b.refused), (usize::MAX, 1));
// Shorter than a period, and past 50,000 periods with a level of detail.
assert_eq!(ranges(0.5, &lt, 1.0, 0.0, Layout::Open, &mut b), None);
assert_eq!(ranges(50_001.0 * 0.75, &lt, 1.0, 1e-9, Layout::Open, &mut b), None);
assert_eq!((b.left, b.refused), (usize::MAX, 1));
let gaps = Linetype::simple("GAPS", "", &[-0.5, -0.25]);
let mut b = Left { left: 0, refused: 0 };
assert_eq!(ranges(750.0, &gaps, 1.0, 0.0, Layout::Open, &mut b), Some(Vec::new()));
assert_eq!(b.refused, 0);
}
/// 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]
@@ -438,14 +527,14 @@ mod tests {
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:?}");
assert_eq!(ranges(len, &lt, 1.0, 0.0, how, &mut Free).map(|r| r.len()), Some(dashes), "{how:?}");
assert_eq!(ranges(len, &lt, 1.0, 1e-9, how, &mut Free), 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);
assert_eq!(apply(&pts, &lt, 1.0, 0.0, &mut Free).len(), 50_002);
assert_eq!(apply(&pts, &lt, 1.0, 1e-9, &mut Free).len(), 1);
}
}
+1 -1
View File
@@ -61,7 +61,7 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &MLine, rgb: Ink,
fn stroke(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Option<&cadcraft_doc::Linetype>, scale: f64, min: f64, pts: &[Vec2]) {
match lt.filter(|_| b.opts.linetypes) {
Some(lt) => {
for dash in linetype::apply(pts, lt, scale, min) {
for dash in linetype::apply(pts, lt, scale, min, b) {
match dash.as_slice() {
[p] => b.point(ctx, rgb, *p),
_ => b.polyline(ctx, rgb, lw, &dash),
+15 -8
View File
@@ -4,8 +4,8 @@ use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT};
use super::draw::entity;
use super::viewports::{MAX_VIEWPORTS, viewport};
use super::{
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, pen, plotstyle,
point,
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper,
pen, plotstyle, point,
};
/// Build options.
@@ -106,14 +106,15 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St
}
fn build_space(d: &Drawing, space: &Space, opts: &Options, plotting: bool) -> DisplayList {
build_space_within(d, space, opts, plotting, MAX_DISPLAY_POINTS)
build_space_within(d, space, opts, plotting, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS)
}
/// [`build_space`] holding at most `max_points` points.
pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plotting: bool, max_points: usize) -> DisplayList {
/// [`build_space`] holding at most `max_points` points and laying out at most `max_dashes` dash
/// pattern elements.
pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plotting: bool, max_points: usize, max_dashes: usize) -> DisplayList {
let opts = &with_point_view(d, space, opts);
let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t));
let points = std::sync::atomic::AtomicUsize::new(0);
let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -124,6 +125,8 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo
transparency: 0,
points: &points,
max_points,
dashes: &dashes,
max_dashes,
};
if let Space::Paper(name) = space {
b.list.sheet = paper::sheet(d, name);
@@ -171,7 +174,7 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
use rayon::prelude::*;
let ents: Vec<&std::sync::Arc<Entity>> = store.iter().collect();
let budget = std::sync::atomic::AtomicUsize::new(0);
let (opts, plotting, points, max_points) = (b.opts, b.plotting, b.points, b.max_points);
let (opts, plotting, points, max_points, dashes, max_dashes) = (b.opts, b.plotting, b.points, b.max_points, b.dashes, b.max_dashes);
let parts: Vec<DisplayList> = ents
.par_chunks(PARALLEL_CHUNK)
.map(|chunk| {
@@ -185,6 +188,8 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
transparency: 0,
points,
max_points,
dashes,
max_dashes,
};
for e in chunk {
entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
@@ -237,7 +242,7 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
} else {
opts
};
let points = std::sync::atomic::AtomicUsize::new(0);
let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -248,6 +253,8 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
transparency: 0,
points: &points,
max_points: MAX_DISPLAY_POINTS,
dashes: &dashes,
max_dashes: MAX_DASH_ELEMENTS,
};
for e in ents {
entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
+135 -2
View File
@@ -1534,7 +1534,7 @@ 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);
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, 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()));
@@ -1547,7 +1547,140 @@ fn objects_built_on_all_cores_stop_at_the_point_budget_and_say_so() {
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);
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, crate::MAX_DASH_ELEMENTS);
assert!(l.truncated);
assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l));
}
// ---------- 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_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, 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, 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, 100);
assert_eq!(l.undashed, 2);
}
/// 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, 400);
let each = prims_per_entity(&l);
assert!(matches!(each.as_slice(), [first, 1] if *first > 101), "{each:?}");
assert_eq!(l.undashed, 1);
}
+11 -4
View File
@@ -6,8 +6,8 @@ use super::draw::entity;
use super::pipeline::PARALLEL_CHUNK;
use super::pipeline::{Options, style_table, top_ctx, with_point_view};
use super::{
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, clip, paper, pen,
plotstyle,
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2,
clip, paper, pen, plotstyle,
};
/// Upper bound on viewports drawn per layout (hostile files).
@@ -70,7 +70,7 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
}
let opts = &with_point_view(d, space, opts);
let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t));
let points = std::sync::atomic::AtomicUsize::new(0);
let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -81,6 +81,8 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
transparency: 0,
points: &points,
max_points: MAX_DISPLAY_POINTS,
dashes: &dashes,
max_dashes: MAX_DASH_ELEMENTS,
};
contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle));
b.list
@@ -135,6 +137,8 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
transparency: 0,
points: b.points,
max_points: b.max_points,
dashes: b.dashes,
max_dashes: b.max_dashes,
};
#[cfg(not(target_arch = "wasm32"))]
let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK;
@@ -146,7 +150,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
// As `build_parallel`: chunks built side by side, joined in drawing order.
use rayon::prelude::*;
let ents: Vec<&std::sync::Arc<Entity>> = d.model.iter().collect();
let (opts, points, max_points) = (b.opts, b.points, b.max_points);
let (opts, points, max_points, dashes, max_dashes) = (b.opts, b.points, b.max_points, b.dashes, b.max_dashes);
let parts: Vec<DisplayList> = ents
.par_chunks(PARALLEL_CHUNK)
.map(|chunk| {
@@ -160,6 +164,8 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
transparency: 0,
points,
max_points,
dashes,
max_dashes,
};
let c = ctx();
for me in chunk.iter().filter(|me| seen(me)) {
@@ -193,6 +199,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
pen::apply(&mut sub.list, unit_mm);
b.list.expanded = b.list.expanded.saturating_add(sub.list.expanded);
b.list.truncated |= sub.list.truncated;
b.list.undashed = b.list.undashed.saturating_add(sub.list.undashed);
append_clipped(&mut b.list, &sub.list, clip);
}
+11 -3
View File
@@ -78,8 +78,16 @@ pub(crate) fn second_vertex_at(p: &LwPolyline, tol: f64) -> f64 {
/// 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 (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>>) {
/// it restarts at every vertex. A pattern shorter than `min_pattern` fills the whole band, as does
/// a run past a dash limit (`dash_budget`, see [`linetype::Budget`]).
pub(crate) fn dashed(
p: &LwPolyline,
tol: f64,
lt: &Linetype,
scale: f64,
min_pattern: f64,
dash_budget: &mut impl linetype::Budget,
) -> (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;
@@ -99,7 +107,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, how).unwrap_or_else(|| vec![(0.0, len)]);
let dashes = linetype::ranges(len, lt, scale, min_pattern, how, dash_budget).unwrap_or_else(|| vec![(0.0, len)]);
for (a, b) in dashes {
if b - a <= 1e-12 {
if let Some(x) = at(run, a) {
+48
View File
@@ -0,0 +1,48 @@
//! A small file of many long lines on a pattern of mostly gaps (#1923, F-05 f). Laying a run out
//! visits every element of every period, two million here, but draws one dash in 256 of them, so
//! the point budget (`MAX_DISPLAY_POINTS`) never stops the build: each line used to cost two
//! million steps. The build's dash budget lays a few dozen out and draws the rest continuous.
use cadcraft_doc::{Common, DashElement, Drawing, EntityKind, Handle, Line, Linetype, Space};
use cadcraft_geom::Vec3;
use cadcraft_render::{DisplayList, Options, build_plot};
const LINES: usize = 1000;
/// `LINES` lines 1,999 long on a pattern of 255 gaps and a dash, each 0.001: 7,808 periods of 256
/// elements a line, just under the two million one run may be laid out over.
fn sparse() -> Drawing {
let mut d = Drawing::new_imperial();
let pattern = (0..256).map(|i| DashElement::dash(if i == 255 { 0.001 } else { -0.001 })).collect();
d.linetypes.push(Linetype { name: "SPARSE".into(), description: String::new(), pattern });
for row in 0..LINES {
let y = row as f64;
let line = EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(1999.0, y, 0.0) });
d.add(&Space::Model, Common { linetype: "SPARSE".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()
}
#[test]
fn many_long_runs_of_a_pattern_of_gaps_stop_at_the_dash_budget() {
let l = build_plot(&sparse(), &Space::Model, &Options::default());
let each = prims_per_entity(&l);
let dashed = each.iter().filter(|n| **n > 1).count();
assert_eq!(each.len(), LINES);
// Every line used to be laid out; a few dozen fit the budget and the rest are one stroke.
assert!(dashed > 0 && dashed * 4 < LINES, "{dashed} of {LINES} lines dashed");
assert!(each.iter().skip(dashed).all(|n| *n == 1), "{each:?}");
assert!(l.truncated, "the lines drawn continuous are reported");
}
+1
View File
@@ -1,6 +1,7 @@
mod aci7_display;
mod annotative_orientation;
mod annotative_viewport;
mod dash_budget;
mod dim_angular_centre;
mod dim_post_tolerance;
mod dim_text_fill;
+2 -1
View File
@@ -587,7 +587,8 @@ fn render_view(bounds: &cadcraft_geom::Bounds2, center: Vec2, height: f64, fit:
}
/// The `ui.render` reply, matching the headless backend (`pngBase64`, `width`, `height`), plus
/// `bytes`, `path` and `truncated` (the build left block contents out, see #1070).
/// `bytes`, `path` and `truncated` (the build left contents out, see #1070, or drew dashed runs
/// continuous past a dash limit, #1069).
fn render_reply(png: &[u8], w: u32, h: u32, path: Option<&str>, truncated: bool) -> Value {
let mut v =
json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(png), "width": w, "height": h, "bytes": png.len(), "truncated": truncated});