mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge pull request #10917 from dotCooCoo/fix/dxf-hatch-pattern-gradient
DXF/DWG import: pattern hatches keep their pattern and gradient hatches their gradient
This commit is contained in:
7 files changed
+1798
-33
No files matched your search
@@ -5,8 +5,9 @@
|
||||
//! drawing units; by default the drawing's own unit at 1:1) or fitted to an artboard, centred
|
||||
//! or with the drawing's origin on the artboard's bottom-left corner. Each DXF layer holding art
|
||||
//! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on
|
||||
//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid
|
||||
//! hatches, solids and regions become paths; text and multiline text point type; named blocks symbols
|
||||
//! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid and
|
||||
//! gradient hatches, pattern hatches' lines, solids and regions become paths; text and multiline
|
||||
//! text point type; named blocks symbols
|
||||
//! (anonymous ones, such as dimensions, groups of their art); raster images linked images of the
|
||||
//! files they name, clipped by their clip boundaries. Colours (indexed and true colour),
|
||||
//! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve
|
||||
@@ -16,6 +17,7 @@
|
||||
//! blocks and layouts.
|
||||
//! - `entity`: entities to items (geometry and properties).
|
||||
//! - `curve`: bulges, arcs, ellipses and NURBS as Bézier paths.
|
||||
//! - `hatch`: pattern hatches' lines and gradient hatches' fills.
|
||||
//! - `text`: text values to plain text.
|
||||
//! - `acis`: a region's solid-modeler data as its outline.
|
||||
//! - `build`: items to the document.
|
||||
@@ -24,6 +26,7 @@ mod acis;
|
||||
mod build;
|
||||
mod curve;
|
||||
mod entity;
|
||||
mod hatch;
|
||||
mod reader;
|
||||
mod text;
|
||||
|
||||
|
||||
+178
-10
@@ -7,8 +7,8 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::BezPath;
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_doc::{
|
||||
Appearance, AppearanceItem, CharStyle, Dash, Document, ImageBlob, ImageObject, LAYER_COLORS, LayerColor, LineCap, LinkInfo, Node, NodeKind,
|
||||
Symbol, TextObject,
|
||||
@@ -16,7 +16,8 @@ use vectorcraft_doc::{
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect};
|
||||
|
||||
use super::ImportOptions;
|
||||
use super::entity::{Alpha, Col, Converter, Geom, ImageItem, InsertItem, Item, Lw, Props, Span, TextItem};
|
||||
use super::entity::{Alpha, Col, Converter, Geom, ImageItem, InsertItem, Item, Lw, Props, Shade, Span, TextItem};
|
||||
use super::hatch::{Grad, Second};
|
||||
use super::reader::{Drawing, LayoutDef};
|
||||
use crate::{CAP_HEIGHT, MAX_NEST};
|
||||
|
||||
@@ -61,6 +62,19 @@ const MAX_IMAGE_SIDE: f64 = 1_048_576.0;
|
||||
/// the file is read.
|
||||
const IMAGE_KEY: &str = "dxf-image-";
|
||||
|
||||
/// How a path paints.
|
||||
#[derive(Clone, Copy)]
|
||||
enum Look<'g> {
|
||||
/// Stroked at its width or lineweight, in its linetype.
|
||||
Line,
|
||||
/// Filled with its color.
|
||||
Fill,
|
||||
/// Filled with a gradient hatch's gradient.
|
||||
Gradient(&'g Grad),
|
||||
/// Pattern hatch lines: stroked without the linetype; `dots` take round caps.
|
||||
Pattern { dots: bool },
|
||||
}
|
||||
|
||||
/// What a block's art takes from the insert that places it: its colour, lineweight, linetype
|
||||
/// and opacity where the art says "by block", and its layer for art on layer 0.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
@@ -424,7 +438,7 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
/// An item's bounds in world coordinates (type: an estimate from its height and length).
|
||||
fn item_bounds(&mut self, it: &Item, depth: u32) -> Option<Rect> {
|
||||
match &it.geom {
|
||||
Geom::Path { bp, .. } => super::curve::bounds(bp),
|
||||
Geom::Path { bp, .. } | Geom::Shaded { bp, .. } => super::curve::bounds(bp),
|
||||
Geom::Text(t) => {
|
||||
let lines = t.text.lines().count().max(1) as f64;
|
||||
let longest = t.text.lines().map(|l| l.chars().count()).max().unwrap_or(0) as f64;
|
||||
@@ -472,8 +486,17 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
for it in items.iter() {
|
||||
let p = &it.props;
|
||||
let on_zero = p.layer == "0";
|
||||
s |= p.color == Col::ByBlock || p.lineweight == Lw::ByBlock || p.linetype == "BYBLOCK" || p.alpha == Alpha::ByBlock;
|
||||
s |= on_zero && (p.color == Col::ByLayer || p.lineweight == Lw::ByLayer || p.linetype == "BYLAYER");
|
||||
// Fills draw no stroke, and pattern lines carry their own dashes.
|
||||
let filled = matches!(&it.geom, Geom::Path { fill: true, .. } | Geom::Shaded { shade: Shade::Gradient(_), .. });
|
||||
let stroked = !filled;
|
||||
let in_linetype = !filled && !matches!(&it.geom, Geom::Shaded { shade: Shade::Pattern { .. }, .. });
|
||||
s |= p.color == Col::ByBlock || p.alpha == Alpha::ByBlock;
|
||||
s |= (stroked && p.lineweight == Lw::ByBlock) || (in_linetype && p.linetype == "BYBLOCK");
|
||||
s |= on_zero && (p.color == Col::ByLayer || (stroked && p.lineweight == Lw::ByLayer) || (in_linetype && p.linetype == "BYLAYER"));
|
||||
if let Geom::Shaded { shade: Shade::Gradient(g), .. } = &it.geom {
|
||||
let inherited = |c| c == Col::ByBlock || (on_zero && c == Col::ByLayer);
|
||||
s |= inherited(g.first) || matches!(g.second, Second::Col(c) if inherited(c));
|
||||
}
|
||||
if let Geom::Insert(ins) = &it.geom {
|
||||
s |= !ins.attribs.is_empty() || self.is_sensitive(&ins.block, depth + 1);
|
||||
}
|
||||
@@ -532,6 +555,23 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gradient `g` as paint, placed by `map`; its colors resolved as the hatch's own would be.
|
||||
fn gradient(&self, g: &Grad, p: &Props, map: Affine, inh: &Inherit) -> Paint {
|
||||
let rgb = |c: Col| self.rgb(&Props { color: c, ..p.clone() }, inh);
|
||||
let first = rgb(g.first);
|
||||
let second = match g.second {
|
||||
Second::Col(c) => rgb(c),
|
||||
Second::Tint(t) => Grad::tinted(first, t),
|
||||
};
|
||||
let stops = g.stops.iter().map(|(at, two)| GradientStop::new(*at, rgb_color(if *two { second } else { first }))).collect();
|
||||
let mut geom = g.geom;
|
||||
geom.transform(map, g.kind);
|
||||
let mut paint = GradientPaint::new(Gradient::new(g.kind, stops));
|
||||
paint.angle = geom.angle_deg();
|
||||
paint.geom = Some(geom);
|
||||
Paint::Gradient(Box::new(paint))
|
||||
}
|
||||
|
||||
/// What a block placed by an insert with `p` inherits.
|
||||
fn inherit(&self, p: &Props, inh: &Inherit) -> Inherit {
|
||||
Inherit {
|
||||
@@ -620,7 +660,9 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
return None;
|
||||
}
|
||||
let mut node = match &it.geom {
|
||||
Geom::Path { bp, fill, width } => self.path(bp, *fill, *width, &it.props, map, inh)?,
|
||||
Geom::Path { bp, fill, width } => self.path(bp, if *fill { Look::Fill } else { Look::Line }, *width, &it.props, map, inh)?,
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(g) } => self.path(bp, Look::Gradient(g), 0.0, &it.props, map, inh)?,
|
||||
Geom::Shaded { bp, shade: Shade::Pattern { dots } } => self.pattern(bp, *dots, &it.props, map, inh)?,
|
||||
Geom::Text(t) => self.text(t, &it.props, map, inh)?,
|
||||
Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth),
|
||||
Geom::Image(im) => self.image(im, map)?,
|
||||
@@ -630,7 +672,63 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
Some(node)
|
||||
}
|
||||
|
||||
fn path(&mut self, bp: &BezPath, fill: bool, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
/// Pattern hatch lines (`bp`, a move and a line per piece). With `dots`, the pieces of no
|
||||
/// length go on a path of their own with round caps, grouped with the dashes, which keep
|
||||
/// butt caps and their lengths.
|
||||
fn pattern(&mut self, bp: &BezPath, dots: bool, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
if !dots {
|
||||
return self.path(bp, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
}
|
||||
let (mut dashes, mut points) = (BezPath::new(), BezPath::new());
|
||||
let (mut dash_count, mut dot_count) = (0usize, 0usize);
|
||||
let mut from = None;
|
||||
for el in bp.elements() {
|
||||
match *el {
|
||||
PathEl::MoveTo(a) => from = Some(a),
|
||||
PathEl::LineTo(b) => {
|
||||
if let Some(a) = from {
|
||||
let (out, count) = if a == b { (&mut points, &mut dot_count) } else { (&mut dashes, &mut dash_count) };
|
||||
out.move_to(a);
|
||||
out.line_to(b);
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if dashes.elements().is_empty() {
|
||||
return self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh);
|
||||
}
|
||||
if points.elements().is_empty() {
|
||||
return self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
}
|
||||
// Every object the split makes: the group (`item` counts it), the two paths, and each
|
||||
// piece of a path with more than one (`path` counts those).
|
||||
let loops = |count: usize| if count > 1 { count } else { 0 };
|
||||
if loops(dash_count).saturating_add(loops(dot_count)).saturating_add(3) > MAX_NODES.saturating_sub(self.nodes) {
|
||||
self.warn(TOO_MANY);
|
||||
return None;
|
||||
}
|
||||
if dashes.elements().len().saturating_add(points.elements().len()) > MAX_ELEMENTS.saturating_sub(self.elements) {
|
||||
self.warn(TOO_MANY_POINTS);
|
||||
return None;
|
||||
}
|
||||
// A split that loses either path is left out whole, and charges nothing.
|
||||
let (nodes, elements) = (self.nodes, self.elements);
|
||||
let lines = self.path(&dashes, Look::Pattern { dots: false }, 0.0, p, map, inh);
|
||||
let dots = lines.as_ref().and_then(|_| self.path(&points, Look::Pattern { dots: true }, 0.0, p, map, inh));
|
||||
let (Some(lines), Some(dots)) = (lines, dots) else {
|
||||
(self.nodes, self.elements) = (nodes, elements);
|
||||
return None;
|
||||
};
|
||||
self.nodes += 2;
|
||||
Some(Node::group(self.doc.alloc_id(), vec![Arc::new(lines), Arc::new(dots)]))
|
||||
}
|
||||
|
||||
/// A path painted as `look` says; `width`: a line's width in drawing units (0: the
|
||||
/// lineweight).
|
||||
fn path(&mut self, bp: &BezPath, look: Look<'_>, width: f64, p: &Props, map: Affine, inh: &Inherit) -> Option<Node> {
|
||||
let fill = matches!(look, Look::Fill | Look::Gradient(_));
|
||||
let n = bp.elements().len();
|
||||
if self.elements.saturating_add(n) > MAX_ELEMENTS {
|
||||
self.warn(TOO_MANY_POINTS);
|
||||
@@ -640,7 +738,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
let mut bp = bp.clone();
|
||||
bp.apply_affine(map);
|
||||
super::curve::bounds(&bp)?;
|
||||
let paint = Paint::solid(rgb_color(self.rgb(p, inh)));
|
||||
let paint = match look {
|
||||
Look::Gradient(g) => self.gradient(g, p, map, inh),
|
||||
_ => Paint::solid(rgb_color(self.rgb(p, inh))),
|
||||
};
|
||||
let pattern = match look {
|
||||
Look::Pattern { dots } => Some(dots),
|
||||
_ => None,
|
||||
};
|
||||
let scale = map.determinant().abs().sqrt();
|
||||
let path = PathData::from_bezpath(&bp);
|
||||
// A compound path's loops each keep a copy of its appearance, beside its own.
|
||||
@@ -657,7 +762,14 @@ impl<'d, 'a> Build<'d, 'a> {
|
||||
f64::from(lw) / 100.0 * PT_PER_MM * self.lw_scale
|
||||
};
|
||||
let mut ap = Appearance::basic(Paint::None, paint, w);
|
||||
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
// Pattern lines carry their own dashes; dots of no length show with round caps.
|
||||
if let Some(dots) = pattern {
|
||||
if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
&& dots
|
||||
{
|
||||
s.cap = LineCap::Round;
|
||||
}
|
||||
} else if let Some(AppearanceItem::Stroke(s)) = ap.items.last_mut()
|
||||
&& let Some((dash, dots)) = self.dash(&self.linetype(p, inh), p, scale)
|
||||
{
|
||||
match dash.pattern.len().checked_mul(copies).and_then(|v| self.dash_values.checked_add(v)).filter(|n| *n <= MAX_DASH_VALUES) {
|
||||
@@ -1118,3 +1230,59 @@ fn unique(base: &str, next: &mut HashMap<String, usize>, taken: &HashSet<String>
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const EMPTY: &[u8] = b" 0\nSECTION\n 2\nENTITIES\n 0\nENDSEC\n 0\nEOF\n";
|
||||
|
||||
fn props() -> Props {
|
||||
Props {
|
||||
layer: "0".into(),
|
||||
color: Col::Rgb([0, 0, 0]),
|
||||
lineweight: Lw::Default,
|
||||
linetype: "CONTINUOUS".into(),
|
||||
ltscale: 1.0,
|
||||
alpha: Alpha::Opacity(1.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two dashes and two dots: the group, its two paths and four pieces, in 8 path elements.
|
||||
fn mixed() -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
for (a, b) in [((0.0, 0.0), (1.0, 0.0)), ((0.0, 1.0), (1.0, 1.0)), ((2.0, 0.0), (2.0, 0.0)), ((2.0, 1.0), (2.0, 1.0))] {
|
||||
bp.move_to(a);
|
||||
bp.line_to(b);
|
||||
}
|
||||
bp
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_patterns_fit_every_object_and_point_or_charge_nothing() {
|
||||
let (tags, _) = super::super::tags(EMPTY).unwrap();
|
||||
let d = Drawing::read(craft_dxf::model::Document::read(&tags));
|
||||
let o = ImportOptions::default();
|
||||
let (p, inh) = (props(), Inherit::default());
|
||||
// Seven objects with six slots free: refused; with seven: drawn, the group left to `item`.
|
||||
let mut b = Build::new(&d, &o);
|
||||
b.nodes = MAX_NODES - 6;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none());
|
||||
assert_eq!(b.nodes, MAX_NODES - 6);
|
||||
b.nodes = MAX_NODES - 7;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_some());
|
||||
assert_eq!(b.nodes, MAX_NODES - 1);
|
||||
// Eight points with seven left: refused without charging them, so a 4-point path that
|
||||
// follows still fits.
|
||||
let mut b = Build::new(&d, &o);
|
||||
b.elements = MAX_ELEMENTS - 7;
|
||||
assert!(b.pattern(&mixed(), true, &p, Affine::IDENTITY, &inh).is_none());
|
||||
assert_eq!(b.elements, MAX_ELEMENTS - 7);
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.line_to((1.0, 0.0));
|
||||
line.line_to((1.0, 1.0));
|
||||
line.line_to((0.0, 1.0));
|
||||
assert!(b.path(&line, Look::Line, 0.0, &p, Affine::IDENTITY, &inh).is_some());
|
||||
}
|
||||
}
|
||||
+169
-16
@@ -4,7 +4,7 @@
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::rc::Rc;
|
||||
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use kurbo::{BezPath, ParamCurve, ParamCurveDeriv, PathEl, PathSeg, Shape};
|
||||
use vectorcraft_doc::Justify;
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
@@ -12,6 +12,7 @@ use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath};
|
||||
|
||||
use super::acis;
|
||||
use super::curve::{self, Vertex};
|
||||
use super::hatch::{self, Grad, NoPattern};
|
||||
use super::reader::{aci_paper, point};
|
||||
|
||||
/// How far below the baseline the lowest descender reaches, as a fraction of the cap height.
|
||||
@@ -22,6 +23,10 @@ const LINE_SPACING: f64 = 5.0 / 3.0;
|
||||
const MAX_CELLS: i64 = 10_000;
|
||||
/// The most copies all the array inserts of a file make together.
|
||||
const MAX_TOTAL_CELLS: i64 = 2_000_000;
|
||||
/// The most winding steps for island nesting: loops times boundary elements times samples.
|
||||
const MAX_ISLAND_WORK: usize = if cfg!(test) { 1_000 } else { 10_000_000 };
|
||||
/// The most segment midpoints sampled just inside each loop for island nesting.
|
||||
const MAX_ISLAND_SAMPLES: usize = 16;
|
||||
/// Art farther than this from the origin (drawing units) is damaged data, left out.
|
||||
const MAX_COORD: f64 = 1e12;
|
||||
/// How far fit and aligned text may be squeezed or stretched to span their two points: at width
|
||||
@@ -182,11 +187,26 @@ pub(crate) enum Geom {
|
||||
fill: bool,
|
||||
width: f64,
|
||||
},
|
||||
/// A hatch filled with a gradient, or a pattern hatch's lines (`bp`, world coordinates).
|
||||
Shaded {
|
||||
bp: BezPath,
|
||||
shade: Shade,
|
||||
},
|
||||
Text(TextItem),
|
||||
Insert(InsertItem),
|
||||
Image(ImageItem),
|
||||
}
|
||||
|
||||
/// How a [`Geom::Shaded`] path paints.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum Shade {
|
||||
/// The area filled with a gradient.
|
||||
Gradient(Box<Grad>),
|
||||
/// Pattern lines, stroked at the lineweight without a linetype; `dots`: some pieces have no
|
||||
/// length and need round caps to show.
|
||||
Pattern { dots: bool },
|
||||
}
|
||||
|
||||
/// An entity as art: its geometry and its properties.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Item {
|
||||
@@ -202,12 +222,18 @@ pub(crate) struct Converter {
|
||||
pub warnings: Vec<String>,
|
||||
/// Array insert copies made so far, against [`MAX_TOTAL_CELLS`].
|
||||
cells: i64,
|
||||
/// The pattern budget shared by entity sections and blocks.
|
||||
patterns: hatch::Budget,
|
||||
/// The binary solid-modeler data of regions, by handle (DXF 2013 and later).
|
||||
regions: Rc<HashMap<u64, Vec<u8>>>,
|
||||
}
|
||||
|
||||
const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries";
|
||||
const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour";
|
||||
const PATTERN_HATCH: &str = "pattern hatches without usable pattern lines come in as their boundaries";
|
||||
const DENSE_PATTERN: &str =
|
||||
"pattern hatches of more than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping steps come in as their boundaries";
|
||||
const MANY_PATTERNS: &str = "the drawing's pattern hatches have more than 2,000,000 dashes in all: the rest come in as their boundaries";
|
||||
const MUCH_PATTERN_WORK: &str = "the drawing's pattern hatches take too much work to clip: the rest come in as their boundaries";
|
||||
const MUCH_ISLAND_WORK: &str = "hatches with too many boundary points to sort into islands are filled as if every loop were a boundary";
|
||||
const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out";
|
||||
const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each";
|
||||
const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all";
|
||||
@@ -245,7 +271,7 @@ impl Converter {
|
||||
if !m.common.visible {
|
||||
continue;
|
||||
}
|
||||
match self.geom(e, &m) {
|
||||
match self.geom(e, &m).map(usable_paint) {
|
||||
Some(geom) if !in_range(&geom) => self.warn(FAR_AWAY),
|
||||
Some(geom) => out.push(Item { props: Props::read(&m.common), geom }),
|
||||
None if is_known(e.kind) => {}
|
||||
@@ -289,7 +315,7 @@ impl Converter {
|
||||
face(&mut bp, &corners);
|
||||
(!bp.elements().is_empty()).then_some(bp).and_then(path)
|
||||
}
|
||||
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
|
||||
model::EntityKind::Hatch(h) => self.hatch(h, ocs, Props::read(&m.common).color),
|
||||
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
|
||||
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
|
||||
model::EntityKind::Insert(ins) => self.insert(ins, &e.followers, ocs),
|
||||
@@ -484,27 +510,153 @@ impl Converter {
|
||||
Some(Geom::Path { bp: outline.path, fill: true, width: 0.0 })
|
||||
}
|
||||
|
||||
fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option<Geom> {
|
||||
let mut bp = BezPath::new();
|
||||
/// A hatch's art; `own`: its color, which a gradient without color records takes.
|
||||
fn hatch(&mut self, h: &model::Hatch, ocs: Affine, own: Col) -> Option<Geom> {
|
||||
let mut loops = Vec::new();
|
||||
for l in &h.loops {
|
||||
let Some(path) = boundary(&l.path) else { break };
|
||||
bp.extend(path);
|
||||
loops.push(path);
|
||||
}
|
||||
let mut max_depth = match h.style {
|
||||
1 => Some(1),
|
||||
2 => Some(0),
|
||||
_ => None,
|
||||
};
|
||||
if max_depth.is_some() {
|
||||
let elements = loops.iter().fold(0usize, |total, path| total.saturating_add(path.elements().len()));
|
||||
// Count each loop's samples against every loop, including its own containment checks.
|
||||
if loops.len().saturating_mul(elements).saturating_mul(MAX_ISLAND_SAMPLES) > MAX_ISLAND_WORK {
|
||||
self.warn(MUCH_ISLAND_WORK);
|
||||
max_depth = None;
|
||||
}
|
||||
}
|
||||
let nesting: Vec<_> = if max_depth.is_some() {
|
||||
loops
|
||||
.iter()
|
||||
.map(|path| {
|
||||
let bounds = path.bounding_box();
|
||||
// Center each loop independently so distant loops do not erase small geometry.
|
||||
let center = bounds.center();
|
||||
let local = transformed(path.clone(), Affine::translate(-center.to_vec2()));
|
||||
let area = local.area();
|
||||
// Area divided by perimeter measures thickness independently of the loop's rotation.
|
||||
let perimeter = local.perimeter(bounds.width().max(bounds.height()) * 1e-3);
|
||||
let inset = if perimeter > 0.0 { area.abs() / perimeter * 1e-3 * area.signum() } else { 0.0 };
|
||||
let step = local.segments().count().div_ceil(MAX_ISLAND_SAMPLES).max(1);
|
||||
let mut samples: Vec<_> = local
|
||||
.segments()
|
||||
.step_by(step)
|
||||
.filter_map(|segment| {
|
||||
let tangent = match segment {
|
||||
PathSeg::Line(line) => line.deriv().eval(0.5),
|
||||
PathSeg::Quad(quad) => quad.deriv().eval(0.5),
|
||||
PathSeg::Cubic(cubic) => cubic.deriv().eval(0.5),
|
||||
}
|
||||
.to_vec2();
|
||||
let tangent = if tangent.hypot() > 0.0 { tangent } else { segment.end() - segment.start() };
|
||||
let length = tangent.hypot();
|
||||
if length == 0.0 {
|
||||
return None;
|
||||
}
|
||||
// Positive area puts the interior to the left of the tangent in y-up coordinates.
|
||||
Some(segment.eval(0.5) + Vec2::new(-tangent.y, tangent.x) * (inset / length))
|
||||
})
|
||||
.take(MAX_ISLAND_SAMPLES)
|
||||
.filter(|sample| local.winding(*sample) != 0)
|
||||
.collect();
|
||||
if samples.is_empty()
|
||||
&& let Some(PathEl::MoveTo(first)) = local.elements().first()
|
||||
{
|
||||
samples.push(*first);
|
||||
}
|
||||
(bounds, center, local, area.abs(), samples)
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut bp = BezPath::new();
|
||||
for (i, path) in loops.iter().enumerate() {
|
||||
if let Some(limit) = max_depth {
|
||||
let (bounds, center, _, area, samples) = &nesting[i];
|
||||
// Require geometric containment and a majority of samples so a shared
|
||||
// edge or a single vertex on the boundary does not decide nesting.
|
||||
let depth = nesting
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(j, _)| {
|
||||
let (other_bounds, other_center, other, other_area, _) = &nesting[*j];
|
||||
let offset = *center - *other_center;
|
||||
*j != i
|
||||
&& area < other_area
|
||||
&& bounds.x0 >= other_bounds.x0
|
||||
&& bounds.y0 >= other_bounds.y0
|
||||
&& bounds.x1 <= other_bounds.x1
|
||||
&& bounds.y1 <= other_bounds.y1
|
||||
&& samples.iter().filter(|p| other.winding(**p + offset) != 0).count() > samples.len() / 2
|
||||
})
|
||||
.count();
|
||||
if depth > limit {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
bp.extend(path.iter());
|
||||
}
|
||||
if bp.elements().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let bp = transformed(bp, ocs);
|
||||
if h.gradient.is_some() {
|
||||
self.warn(GRADIENT_HATCH);
|
||||
} else if !h.solid {
|
||||
self.warn(PATTERN_HATCH);
|
||||
return Some(Geom::Path { bp, fill: false, width: 0.0 });
|
||||
if let Some(g) = &h.gradient {
|
||||
let shade = hatch::gradient(g, &bp, ocs, own).map(|g| Shade::Gradient(Box::new(g)));
|
||||
let bp = transformed(bp, ocs);
|
||||
return Some(match shade {
|
||||
Some(shade) => Geom::Shaded { bp, shade },
|
||||
None => Geom::Path { bp, fill: true, width: 0.0 },
|
||||
});
|
||||
}
|
||||
if h.solid {
|
||||
return Some(Geom::Path { bp: transformed(bp, ocs), fill: true, width: 0.0 });
|
||||
}
|
||||
// The pattern lines are in the hatch's plane, as its boundary is.
|
||||
let doubled;
|
||||
let lines = if h.pattern_type == 0 && h.double && h.pattern_lines.len() == 1 {
|
||||
doubled = hatch::doubled(&h.pattern_lines);
|
||||
&doubled
|
||||
} else {
|
||||
&h.pattern_lines
|
||||
};
|
||||
match hatch::pattern(lines, &bp, &mut self.patterns) {
|
||||
Ok((lines, _)) if lines.elements().is_empty() => None,
|
||||
Ok((lines, dots)) => Some(Geom::Shaded { bp: transformed(lines, ocs), shade: Shade::Pattern { dots } }),
|
||||
Err(why) => {
|
||||
self.warn(match why {
|
||||
NoPattern::Undefined => PATTERN_HATCH,
|
||||
NoPattern::TooDense => DENSE_PATTERN,
|
||||
NoPattern::DrawingPieces => MANY_PATTERNS,
|
||||
NoPattern::DrawingWork => MUCH_PATTERN_WORK,
|
||||
});
|
||||
Some(Geom::Path { bp: transformed(bp, ocs), fill: false, width: 0.0 })
|
||||
}
|
||||
}
|
||||
Some(Geom::Path { bp, fill: true, width: 0.0 })
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the geometry within [`MAX_COORD`] of the origin?
|
||||
/// A gradient hatch whose gradient cannot be placed (numbers out of range) as a solid fill.
|
||||
fn usable_paint(g: Geom) -> Geom {
|
||||
match g {
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(grad) } => {
|
||||
let geom = &grad.geom;
|
||||
let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
|
||||
if finite(geom.start) && finite(geom.end) && geom.aspect.is_finite() && geom.focal.is_none_or(finite) {
|
||||
Geom::Shaded { bp, shade: Shade::Gradient(grad) }
|
||||
} else {
|
||||
Geom::Path { bp, fill: true, width: 0.0 }
|
||||
}
|
||||
}
|
||||
g => g,
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the geometry within [`MAX_COORD`] of the origin? A gradient's handles may lie beyond it.
|
||||
fn in_range(g: &Geom) -> bool {
|
||||
let near = |p: Point| p.x.abs() <= MAX_COORD && p.y.abs() <= MAX_COORD;
|
||||
let origin = |m: &Affine| near(m.translation().to_point());
|
||||
@@ -512,6 +664,7 @@ fn in_range(g: &Geom) -> bool {
|
||||
Geom::Path { bp, width, .. } => {
|
||||
curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))) && *width <= MAX_COORD
|
||||
}
|
||||
Geom::Shaded { bp, .. } => curve::bounds(bp).is_some_and(|b| near(Point::new(b.x0, b.y0)) && near(Point::new(b.x1, b.y1))),
|
||||
Geom::Text(t) => origin(&t.xf) && t.height <= MAX_COORD,
|
||||
Geom::Insert(i) => i.cells.iter().all(|m| origin(m) && m.as_coeffs().iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)),
|
||||
Geom::Image(i) => {
|
||||
|
||||
@@ -0,0 +1,847 @@
|
||||
//! Hatch fills other than solid: a pattern hatch's line families clipped to its boundary and cut
|
||||
//! into their dashes, and a gradient hatch's colors and placement. Both work in the hatch's own
|
||||
//! plane (its object coordinate system), where the boundary and the pattern lines are given.
|
||||
|
||||
use kurbo::{BezPath, PathEl};
|
||||
use vectorcraft_color::{GradientGeom, GradientKind};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use craft_dxf::model::{self, PatternLine};
|
||||
|
||||
use super::entity::Col;
|
||||
use super::reader::aci_paper;
|
||||
|
||||
/// The most dashes and dots one pattern hatch draws.
|
||||
pub(crate) const MAX_PIECES: usize = 20_000;
|
||||
/// The most boundary edges a pattern hatch is clipped against, once its curves are flattened.
|
||||
const MAX_EDGES: usize = 200_000;
|
||||
/// The most work one pattern hatch does: each pattern line drawn costs one step per boundary
|
||||
/// edge, and each dash, gap or dot looked at one more.
|
||||
const MAX_WORK: usize = 20_000_000;
|
||||
/// The most dashes and dots all pattern hatches draw together.
|
||||
pub(crate) const MAX_TOTAL_PIECES: usize = if cfg!(test) { 1_000 } else { 2_000_000 };
|
||||
/// The most clipping and dash steps all pattern hatches take together.
|
||||
pub(crate) const MAX_TOTAL_WORK: usize = if cfg!(test) { 200_000 } else { 200_000_000 };
|
||||
/// How far flattened boundary curves may stray, as a fraction of their loop's larger side.
|
||||
const FLATNESS: f64 = 1e-4;
|
||||
/// Spans, line spacings and dash periods shorter than this many units of the last place of their
|
||||
/// coordinates count as none.
|
||||
const LOCAL_TINY: f64 = 64.0 * f64::EPSILON;
|
||||
|
||||
/// Why a pattern hatch is not drawn as its pattern.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum NoPattern {
|
||||
/// The hatch holds no pattern lines.
|
||||
Undefined,
|
||||
/// Drawing it would take more than [`MAX_PIECES`] pieces, [`MAX_EDGES`] boundary edges or
|
||||
/// [`MAX_WORK`] steps.
|
||||
TooDense,
|
||||
/// The drawing reaches its total piece limit.
|
||||
DrawingPieces,
|
||||
/// The drawing reaches its total work limit.
|
||||
DrawingWork,
|
||||
}
|
||||
|
||||
/// The remaining pattern budget; discarded patterns also use it.
|
||||
pub(crate) struct Budget {
|
||||
pieces: usize,
|
||||
work: usize,
|
||||
stopped: Option<NoPattern>,
|
||||
}
|
||||
|
||||
impl Default for Budget {
|
||||
fn default() -> Self {
|
||||
Self { pieces: MAX_TOTAL_PIECES, work: MAX_TOTAL_WORK, stopped: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
fn piece(&mut self, pieces: &mut usize) -> Result<(), NoPattern> {
|
||||
if *pieces >= MAX_PIECES {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
if self.pieces == 0 {
|
||||
self.stopped = Some(NoPattern::DrawingPieces);
|
||||
return Err(NoPattern::DrawingPieces);
|
||||
}
|
||||
*pieces += 1;
|
||||
self.pieces -= 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn work(&mut self, work: &mut usize, steps: usize) -> Result<(), NoPattern> {
|
||||
if steps > MAX_WORK - *work {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
if steps > self.work {
|
||||
self.stopped = Some(NoPattern::DrawingWork);
|
||||
return Err(NoPattern::DrawingWork);
|
||||
}
|
||||
*work += steps;
|
||||
self.work -= steps;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a perpendicular family when the pattern holds only one family.
|
||||
pub(crate) fn doubled(lines: &[PatternLine]) -> Vec<PatternLine> {
|
||||
let mut out = lines.to_vec();
|
||||
if let [line] = lines {
|
||||
out.push(PatternLine { angle: line.angle + 90.0, base: line.base, offset: [-line.offset[1], line.offset[0]], dashes: line.dashes.clone() });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A pattern hatch's lines inside `boundary` (closed loops; even-odd, as solid hatches fill):
|
||||
/// each family's lines, cut into dashes and dots that start from the line's own base point.
|
||||
/// `Ok` holds the pieces (empty when no line crosses the area) and whether any of them is a dot.
|
||||
pub(crate) fn pattern(lines: &[PatternLine], boundary: &BezPath, budget: &mut Budget) -> Result<(BezPath, bool), NoPattern> {
|
||||
if lines.is_empty() {
|
||||
return Err(NoPattern::Undefined);
|
||||
}
|
||||
let exhausted = if budget.pieces == 0 {
|
||||
Some(NoPattern::DrawingPieces)
|
||||
} else if budget.work == 0 {
|
||||
Some(NoPattern::DrawingWork)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(why) = budget.stopped.or(exhausted) {
|
||||
budget.stopped = Some(why);
|
||||
return Err(why);
|
||||
}
|
||||
let mut out = BezPath::new();
|
||||
let Some(b) = super::curve::bounds(boundary) else { return Ok((out, false)) };
|
||||
let size = b.width().max(b.height());
|
||||
if !(size > 0.0 && size.is_finite()) {
|
||||
return Ok((out, false));
|
||||
}
|
||||
let edges = edges(boundary)?;
|
||||
if edges.is_empty() {
|
||||
return Ok((out, false));
|
||||
}
|
||||
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)];
|
||||
let center = b.center();
|
||||
// The precision of the boundary's coordinates: spacings and periods below it draw nothing apart.
|
||||
let tiny = LOCAL_TINY * center.to_vec2().hypot().max(size);
|
||||
let (mut work, mut pieces, mut dots, mut usable) = (0usize, 0usize, false, false);
|
||||
for l in lines {
|
||||
let a = l.angle.to_radians();
|
||||
let d = Vec2::new(a.cos(), a.sin());
|
||||
let n = Vec2::new(-d.y, d.x);
|
||||
let base = Point::new(l.base[0], l.base[1]);
|
||||
let offset = Vec2::new(l.offset[0], l.offset[1]);
|
||||
let step = offset.dot(n);
|
||||
// A family with numbers out of range is damaged: the others still draw.
|
||||
if ![a, base.x, base.y, offset.x, offset.y].iter().all(|v| v.is_finite()) || l.dashes.iter().any(|v| !v.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
usable = true;
|
||||
// Lines no distance apart, or closer than the coordinates can tell apart, fill the area
|
||||
// past what can be drawn.
|
||||
if step.abs() <= tiny {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
let period: f64 = l.dashes.iter().map(|v| v.abs()).sum();
|
||||
if !l.dashes.is_empty() && period <= tiny {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
// The same family from the line nearest the boundary's center, a whole number of offsets
|
||||
// away. The base and the center are each measured from the line through the origin
|
||||
// first, so a base far away keeps the fraction of the center's position.
|
||||
let (bn, cn) = (base.to_vec2().dot(n), center.to_vec2().dot(n));
|
||||
let (to_origin, to_center) = (-(bn / step).round(), (cn / step).round());
|
||||
let across = (bn + to_origin * step) + (to_center * step - cn);
|
||||
let last = -(across / step).round();
|
||||
let across = across + last * step;
|
||||
// Where the dashes start on that line, from its point nearest the center. Each line is
|
||||
// measured from its own point nearest the center, so its spans stay near the boundary
|
||||
// however long the dash period is. Each term is reduced to within half a period before
|
||||
// the terms are added, so a distant base or a large offset count keeps its remainder.
|
||||
let od = offset.dot(d);
|
||||
let along = if l.dashes.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
let ([o, oe], [c, ce]) = (product_parts(to_origin, od), product_parts(to_center + last, od));
|
||||
sum_rem(&[base.to_vec2().dot(d), -center.to_vec2().dot(d), o, oe, c, ce], period)
|
||||
};
|
||||
if !(across.is_finite() && along.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
// The dash start nearest a line's point nearest the center, as a signed distance.
|
||||
let phase = |k: f64| {
|
||||
let [p, e] = product_parts(k, od);
|
||||
sum_rem(&[along, p, e], period)
|
||||
};
|
||||
let base = center + n * across;
|
||||
// The lines crossing the boundary's box: base + k * step along the normal for whole k.
|
||||
let h = corners.map(|c| (c - base).dot(n) / step);
|
||||
let lo = h.iter().copied().fold(f64::INFINITY, f64::min).ceil();
|
||||
let hi = h.iter().copied().fold(f64::NEG_INFINITY, f64::max).floor();
|
||||
if hi < lo {
|
||||
continue;
|
||||
}
|
||||
let count = hi - lo + 1.0;
|
||||
if count * (edges.len() as f64) + work as f64 > MAX_WORK as f64 {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
let mut t = Vec::new();
|
||||
for k in (lo as i64)..=(hi as i64) {
|
||||
budget.work(&mut work, edges.len())?;
|
||||
let q = base + n * (step * k as f64);
|
||||
crossings(&edges, q, d, n, &mut t);
|
||||
for &[ta, tb] in t.as_chunks::<2>().0 {
|
||||
// Spans of no length at the precision of their own coordinates are dropped.
|
||||
if tb - ta <= LOCAL_TINY * (q.to_vec2().hypot() + ta.abs().max(tb.abs())) {
|
||||
continue;
|
||||
}
|
||||
let mut emit = |s0: f64, s1: f64, budget: &mut Budget| -> Result<(), NoPattern> {
|
||||
budget.piece(&mut pieces)?;
|
||||
out.move_to(q + d * s0);
|
||||
out.line_to(q + d * s1);
|
||||
Ok(())
|
||||
};
|
||||
if l.dashes.is_empty() {
|
||||
emit(ta, tb, budget)?;
|
||||
continue;
|
||||
}
|
||||
// The dashes run from the line's dash start, element by element, from the period
|
||||
// the span starts in.
|
||||
let start = phase(k as f64);
|
||||
let mut at = start + ((ta - start) / period).floor() * period;
|
||||
// Periods too short to move along the span, or more dashes than one hatch may
|
||||
// look at, are refused before any of them is looked at.
|
||||
let steps = ((tb - at) / period + 2.0) * l.dashes.len() as f64;
|
||||
if period <= LOCAL_TINY * at.abs().max(tb.abs()) || steps + work as f64 > MAX_WORK as f64 {
|
||||
return Err(NoPattern::TooDense);
|
||||
}
|
||||
// An element from `s` to `e`: a dash when `v` is positive, a dot when it is zero.
|
||||
let mut element = |s: f64, e: f64, v: f64, budget: &mut Budget| -> Result<(), NoPattern> {
|
||||
budget.work(&mut work, 1)?;
|
||||
if v > 0.0 {
|
||||
let (s0, s1) = (s.max(ta), e.min(tb));
|
||||
if s1 > s0 {
|
||||
emit(s0, s1, budget)?;
|
||||
}
|
||||
} else if v == 0.0 && s >= ta {
|
||||
emit(s, s, budget)?;
|
||||
dots = true;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
// When that period starts on the span's start, or past it, the elements that end
|
||||
// the period before are measured back from its end, so a dot there is kept and a
|
||||
// long period does not move them. Each element's start and end are the distances
|
||||
// summed back from that end, so a long element does not move its known end.
|
||||
if at >= ta {
|
||||
let (mut back, mut first) = (vec![0.0], l.dashes.len());
|
||||
while first > 0 && at - back[back.len() - 1] >= ta {
|
||||
first -= 1;
|
||||
back.push(back[back.len() - 1] + l.dashes[first].abs());
|
||||
}
|
||||
for (i, v) in l.dashes[first..].iter().enumerate() {
|
||||
let rest = back.len() - 1 - i;
|
||||
element(at - back[rest], at - back[rest - 1], *v, budget)?;
|
||||
}
|
||||
}
|
||||
'span: loop {
|
||||
for v in &l.dashes {
|
||||
if at > tb {
|
||||
break 'span;
|
||||
}
|
||||
element(at, at + v.abs(), *v, budget)?;
|
||||
at += v.abs();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !usable {
|
||||
return Err(NoPattern::Undefined);
|
||||
}
|
||||
Ok((out, dots))
|
||||
}
|
||||
|
||||
/// `x` less the whole number of periods nearest it, within half a period of zero. Both steps
|
||||
/// are exact: the remainder of a division, then one period added or taken away.
|
||||
fn near_rem(x: f64, period: f64) -> f64 {
|
||||
let r = x % period;
|
||||
if r > period / 2.0 {
|
||||
r - period
|
||||
} else if r < -period / 2.0 {
|
||||
r + period
|
||||
} else {
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
/// `a * b` as the rounded product and its rounding error, which add up to it exactly.
|
||||
fn product_parts(a: f64, b: f64) -> [f64; 2] {
|
||||
let p = a * b;
|
||||
[p, a.mul_add(b, -p)]
|
||||
}
|
||||
|
||||
/// The sum of `terms` reduced as [`near_rem`] does. Each term is reduced first, so a large term
|
||||
/// keeps its remainder, and the reduced terms are added with their rounding errors kept apart, so
|
||||
/// a small term is kept when larger ones cancel.
|
||||
fn sum_rem(terms: &[f64], period: f64) -> f64 {
|
||||
let (mut hi, mut lo) = (0.0, 0.0);
|
||||
for &t in terms {
|
||||
let t = near_rem(t, period);
|
||||
let s = hi + t;
|
||||
let v = s - hi;
|
||||
lo += (hi - (s - v)) + (t - v);
|
||||
hi = s;
|
||||
}
|
||||
near_rem(near_rem(hi, period) + near_rem(lo, period), period)
|
||||
}
|
||||
|
||||
/// The boundary's edges as straight segments, each loop closed and its curves flattened to
|
||||
/// within [`FLATNESS`] of the loop's own size. Loops of no size are left out.
|
||||
fn edges(boundary: &BezPath) -> Result<Vec<(Point, Point)>, NoPattern> {
|
||||
let mut loops: Vec<BezPath> = Vec::new();
|
||||
for el in boundary.elements() {
|
||||
if matches!(el, PathEl::MoveTo(_)) {
|
||||
loops.push(BezPath::new());
|
||||
}
|
||||
if let Some(l) = loops.last_mut() {
|
||||
l.push(*el);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut over = false;
|
||||
let mut push = |a: Point, b: Point, out: &mut Vec<(Point, Point)>| {
|
||||
if out.len() >= MAX_EDGES {
|
||||
over = true;
|
||||
} else if a != b {
|
||||
out.push((a, b));
|
||||
}
|
||||
};
|
||||
for lp in &loops {
|
||||
let Some(b) = super::curve::bounds(lp) else { continue };
|
||||
let tolerance = b.width().max(b.height()) * FLATNESS;
|
||||
if !(tolerance > 0.0 && tolerance.is_finite()) {
|
||||
continue;
|
||||
}
|
||||
let (mut start, mut last) = (None::<Point>, None::<Point>);
|
||||
kurbo::flatten(lp.iter(), tolerance, |el| match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
start = Some(p);
|
||||
last = Some(p);
|
||||
}
|
||||
PathEl::LineTo(p) => {
|
||||
if let Some(l) = last {
|
||||
push(l, p, &mut out);
|
||||
}
|
||||
last = Some(p);
|
||||
}
|
||||
PathEl::ClosePath => {
|
||||
if let (Some(s), Some(l)) = (start, last) {
|
||||
push(l, s, &mut out);
|
||||
}
|
||||
last = start;
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
if let (Some(s), Some(l)) = (start, last) {
|
||||
push(l, s, &mut out);
|
||||
}
|
||||
}
|
||||
if over { Err(NoPattern::TooDense) } else { Ok(out) }
|
||||
}
|
||||
|
||||
/// Where the line through `q` along `d` (unit; `n` its normal) crosses the edges, as distances
|
||||
/// from `q` along `d`, sorted into `t`. A vertex on the line counts once, for the edge that leaves
|
||||
/// the side the previous one came from.
|
||||
fn crossings(edges: &[(Point, Point)], q: Point, d: Vec2, n: Vec2, t: &mut Vec<f64>) {
|
||||
t.clear();
|
||||
for (p0, p1) in edges {
|
||||
let (h0, h1) = ((*p0 - q).dot(n), (*p1 - q).dot(n));
|
||||
if (h0 > 0.0) != (h1 > 0.0) {
|
||||
let p = p0.lerp(*p1, h0 / (h0 - h1));
|
||||
t.push((p - q).dot(d));
|
||||
}
|
||||
}
|
||||
t.sort_by(f64::total_cmp);
|
||||
}
|
||||
|
||||
/// The second color of a gradient: a color of its own, or for a one-color gradient the first
|
||||
/// one shaded toward black (tint 0) or tinted toward white (tint 1); 0.5 keeps it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum Second {
|
||||
Col(Col),
|
||||
Tint(f64),
|
||||
}
|
||||
|
||||
/// A gradient hatch's fill, placed in world coordinates (drawing units, y up).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct Grad {
|
||||
pub kind: GradientKind,
|
||||
/// Linear: where the first stop sits and the last; radial: the center, a point on the outer
|
||||
/// ellipse and its aspect (a circle in the hatch's plane, an ellipse when the plane is seen
|
||||
/// at a slant).
|
||||
pub geom: GradientGeom,
|
||||
pub first: Col,
|
||||
pub second: Second,
|
||||
/// Each stop's position and whether it takes the second color (else the first).
|
||||
pub stops: Vec<(f32, bool)>,
|
||||
}
|
||||
|
||||
impl Grad {
|
||||
/// `first` shaded or tinted by `tint` (see [`Second::Tint`]).
|
||||
pub fn tinted([r, g, b]: [u8; 3], tint: f64) -> [u8; 3] {
|
||||
let t = if tint.is_finite() { tint.clamp(0.0, 1.0) } else { 0.5 };
|
||||
let mix = |c: u8| {
|
||||
let c = f64::from(c);
|
||||
let v = if t < 0.5 { c * t * 2.0 } else { c + (255.0 - c) * (t - 0.5) * 2.0 };
|
||||
v.round().clamp(0.0, 255.0) as u8
|
||||
};
|
||||
[mix(r), mix(g), mix(b)]
|
||||
}
|
||||
}
|
||||
|
||||
fn col(c: model::Color) -> Col {
|
||||
match c {
|
||||
model::Color::Rgb(rgb) => Col::Rgb(rgb),
|
||||
model::Color::Index(i) => Col::Rgb(aci_paper(i)),
|
||||
model::Color::ByBlock => Col::ByBlock,
|
||||
model::Color::ByLayer => Col::ByLayer,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill of gradient `g` over `boundary` (in the hatch's plane; `ocs` takes it to world
|
||||
/// coordinates), `own` standing in for colors the gradient lacks. The gradient runs at its angle
|
||||
/// across the boundary's extent in that direction. VectorCraft draws the named gradients this way:
|
||||
/// `LINEAR` the first color to the second; `CYLINDER` the second color in the middle of the first;
|
||||
/// `SPHERICAL` a circle from the second color at the center to the first; `HEMISPHERICAL` the same
|
||||
/// circle centered on the bottom edge; `CURVED` the second color at the bottom to the first at the
|
||||
/// top; each `INV` name the two colors the other way round; any other name as `LINEAR`. The shift
|
||||
/// moves the center up and left by up to a quarter of the extent.
|
||||
pub(crate) fn gradient(g: &model::Gradient, boundary: &BezPath, ocs: Affine, own: Col) -> Option<Grad> {
|
||||
let angle = if g.angle.is_finite() { g.angle } else { 0.0 };
|
||||
let mut frame = boundary.clone();
|
||||
frame.apply_affine(Affine::rotate(-angle));
|
||||
let r = super::curve::bounds(&frame)?;
|
||||
let (w, h) = (r.width(), r.height());
|
||||
let shift = if g.shift.is_finite() { g.shift.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let c = r.center() + Vec2::new(-w, h) * (shift / 4.0);
|
||||
// How far the shift moves the center left and up.
|
||||
let (dx, dy) = (c.x - r.center().x, c.y - r.center().y);
|
||||
let name = g.name.trim().to_uppercase();
|
||||
let (inverse, name) = match name.strip_prefix("INV") {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, name.as_str()),
|
||||
};
|
||||
let swap = |stops: &[(f32, bool)]| stops.iter().map(|(o, s)| (*o, *s != inverse)).collect::<Vec<_>>();
|
||||
let (kind, start, end, stops) = match name {
|
||||
"CYLINDER" => {
|
||||
(GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (0.5, true), (1.0, false)]))
|
||||
}
|
||||
"SPHERICAL" => (GradientKind::Radial, c, c + Vec2::new(w.max(h) / 2.0, 0.0), swap(&[(0.0, true), (1.0, false)])),
|
||||
"HEMISPHERICAL" => {
|
||||
let center = Point::new(c.x, r.y0 + dy);
|
||||
(GradientKind::Radial, center, center + Vec2::new((w / 2.0).max(h), 0.0), swap(&[(0.0, true), (1.0, false)]))
|
||||
}
|
||||
"CURVED" => (GradientKind::Linear, Point::new(c.x, r.y0 + dy), Point::new(c.x, r.y1 + dy), swap(&[(0.0, true), (1.0, false)])),
|
||||
_ => (GradientKind::Linear, Point::new(r.x0 + dx, c.y), Point::new(r.x1 + dx, c.y), swap(&[(0.0, false), (1.0, true)])),
|
||||
};
|
||||
let mut geom = GradientGeom { start, end, aspect: 1.0, focal: None };
|
||||
geom.transform(ocs * Affine::rotate(angle), kind);
|
||||
let first = g.colors.first().map_or(own, |c| col(*c));
|
||||
let second = if g.single { Second::Tint(g.tint) } else { Second::Col(g.colors.get(1).map_or(first, |c| col(*c))) };
|
||||
Some(Grad { kind, geom, first, second, stops })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn pattern(lines: &[PatternLine], boundary: &BezPath) -> Result<(BezPath, bool), NoPattern> {
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
super::pattern(lines, boundary, &mut budget)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_budgets_charge_discarded_patterns_and_stop_later_hatches() {
|
||||
let lines = [line(0.0, [0.0, 1.0], &[])];
|
||||
let boundary = square(10.0);
|
||||
let mut budget = Budget { pieces: 3, work: 100, stopped: None };
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces));
|
||||
assert_eq!(budget.pieces, 0);
|
||||
assert!(budget.work < 100);
|
||||
let work = budget.work;
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingPieces));
|
||||
assert_eq!(budget.work, work, "later hatches do no clipping");
|
||||
|
||||
let mut budget = Budget { pieces: 100, work: 9, stopped: None };
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!(budget.work, 1, "two lines cost four edges each");
|
||||
let pieces = budget.pieces;
|
||||
assert_eq!(super::pattern(&lines, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!((budget.work, budget.pieces), (1, pieces));
|
||||
|
||||
let gaps = [line(0.0, [0.0, 1.0], &[-0.01])];
|
||||
let mut budget = Budget { pieces: 100, work: 20, stopped: None };
|
||||
assert_eq!(super::pattern(&gaps, &boundary, &mut budget), Err(NoPattern::DrawingWork));
|
||||
assert_eq!((budget.work, budget.pieces), (0, 100), "gaps cost work without drawing pieces");
|
||||
}
|
||||
|
||||
fn square(side: f64) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((side, 0.0));
|
||||
bp.line_to((side, side));
|
||||
bp.line_to((0.0, side));
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
|
||||
fn line(angle: f64, offset: [f64; 2], dashes: &[f64]) -> PatternLine {
|
||||
PatternLine { angle, base: [0.0, 0.0], offset, dashes: dashes.to_vec() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn doubling_adds_a_perpendicular_family_only_when_one_is_present() {
|
||||
let mut level = line(0.0, [3.0, 10.0], &[4.0, -2.0]);
|
||||
level.base = [2.0, 5.0];
|
||||
let lines = doubled(&[level.clone()]);
|
||||
let [first, second] = &lines[..] else { panic!("two families") };
|
||||
assert_eq!((first.angle, first.base, first.offset, &first.dashes), (level.angle, level.base, level.offset, &level.dashes));
|
||||
assert_eq!(second.angle, level.angle + 90.0);
|
||||
assert_eq!(second.offset, [-level.offset[1], level.offset[0]]);
|
||||
assert_eq!((second.base, &second.dashes), (level.base, &level.dashes));
|
||||
let kept = doubled(&lines);
|
||||
assert_eq!(kept.len(), lines.len());
|
||||
for (a, b) in kept.iter().zip(&lines) {
|
||||
assert_eq!((a.angle, a.base, a.offset, &a.dashes), (b.angle, b.base, b.offset, &b.dashes));
|
||||
}
|
||||
}
|
||||
|
||||
/// The pieces as (start, end) pairs.
|
||||
fn pieces(bp: &BezPath) -> Vec<(Point, Point)> {
|
||||
let mut out = vec![];
|
||||
let mut from = Point::ZERO;
|
||||
for el in bp.elements() {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => from = *p,
|
||||
PathEl::LineTo(p) => out.push((from, *p)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_lines_stop_at_the_boundary_and_skip_holes() {
|
||||
// Horizontal lines 10 apart, through y 5, 15 … 95, across a 100 square with a 20 square
|
||||
// hole in the middle.
|
||||
let mut boundary = square(100.0);
|
||||
let mut hole = square(20.0);
|
||||
hole.apply_affine(Affine::translate((40.0, 40.0)));
|
||||
boundary.extend(hole);
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 5.0], offset: [0.0, 10.0], dashes: vec![] };
|
||||
let (bp, dots) = pattern(&[l], &boundary).unwrap();
|
||||
assert!(!dots);
|
||||
let p = pieces(&bp);
|
||||
// Ten lines, the two through the hole (y 45 and 55) each cut in two.
|
||||
assert_eq!(p.len(), 12, "{p:?}");
|
||||
for (a, b) in &p {
|
||||
assert!((a.y - b.y).abs() < 1e-9 && a.x >= -1e-9 && b.x <= 100.0 + 1e-9);
|
||||
}
|
||||
let middle: Vec<_> = p.iter().filter(|(a, _)| (a.y - 45.0).abs() < 1e-9).collect();
|
||||
assert_eq!(middle.len(), 2);
|
||||
assert!(middle.iter().all(|(a, b)| b.x <= 40.0 + 1e-9 || a.x >= 60.0 - 1e-9), "{middle:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dashes_start_at_each_lines_base_point() {
|
||||
// Dash 3, gap 2, a dot, gap 5: period 10 from x = 0, lines staggered by 5 along them.
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 0.0], offset: [5.0, 50.0], dashes: vec![3.0, -2.0, 0.0, -5.0] };
|
||||
let (bp, dots) = pattern(&[l], &square(100.0)).unwrap();
|
||||
assert!(dots);
|
||||
let p = pieces(&bp);
|
||||
let row = |y: f64| p.iter().filter(|(a, _)| (a.y - y).abs() < 1e-9).map(|(a, b)| (a.x, b.x)).collect::<Vec<_>>();
|
||||
let first = row(50.0);
|
||||
assert!(first.len() > 4, "{first:?}");
|
||||
// The pattern at y 50 starts at x 5, so the period before it puts a dot on the boundary.
|
||||
assert_eq!(&first[..4], &[(0.0, 0.0), (5.0, 8.0), (10.0, 10.0), (15.0, 18.0)]);
|
||||
assert!(first.iter().all(|(a, b)| *a >= 0.0 && *b <= 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dash_across_the_boundary_is_cut_there() {
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 7.0], &[30.0, -10.0])], &square(50.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!(p.iter().any(|(a, b)| (a.x - 0.0).abs() < 1e-9 && (b.x - 30.0).abs() < 1e-9));
|
||||
// The second dash, 40 to 70, crosses the boundary at 50 and stops there.
|
||||
assert!(p.iter().any(|(a, b)| (a.x - 40.0).abs() < 1e-9 && (b.x - 50.0).abs() < 1e-9), "{p:?}");
|
||||
assert!(p.iter().all(|(_, b)| b.x <= 50.0 + 1e-9), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_spans_far_apart_keep_their_pieces_and_curves() {
|
||||
// Two strips 1 wide and 100 tall, 10 billion units apart: each level line keeps its
|
||||
// one-unit spans.
|
||||
let strip = |x: f64| {
|
||||
let mut s = square(1.0);
|
||||
s.apply_affine(Affine::translate((x, 0.0)) * Affine::scale_non_uniform(1.0, 100.0));
|
||||
s
|
||||
};
|
||||
let mut boundary = strip(0.0);
|
||||
boundary.extend(strip(1e10));
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 25.0], offset: [0.0, 50.0], dashes: vec![] };
|
||||
let (bp, _) = pattern(std::slice::from_ref(&l), &boundary).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 4, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| ((b.x - a.x) - 1.0).abs() < 1e-3), "{p:?}");
|
||||
// Unit circles as far apart keep their round outlines: the line through y 0.5 spans
|
||||
// 2 * sqrt(0.75) of each.
|
||||
let circle = |x: f64| kurbo::Shape::to_path(&kurbo::Circle::new((x, 0.0), 1.0), 0.1);
|
||||
let mut boundary = circle(0.0);
|
||||
boundary.extend(circle(1e10));
|
||||
let l = PatternLine { angle: 0.0, base: [0.0, 0.5], offset: [0.0, 100.0], dashes: vec![] };
|
||||
let (bp, _) = pattern(&[l], &boundary).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 2, "{p:?}");
|
||||
let chord = 2.0 * 0.75f64.sqrt();
|
||||
assert!(p.iter().all(|(a, b)| ((b.x - a.x).abs() - chord).abs() < chord * 1e-2), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_lines_across_squares_far_apart_are_drawn() {
|
||||
// Two unit squares 10 billion units apart, lines 0.5 apart: two lines cross each square.
|
||||
let mut boundary = square(1.0);
|
||||
let mut far = square(1.0);
|
||||
far.apply_affine(Affine::translate((1e10, 0.0)));
|
||||
boundary.extend(far);
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[])], &boundary).unwrap();
|
||||
assert_eq!(pieces(&bp).len(), 4, "{:?}", pieces(&bp));
|
||||
// Dashes 0.25 long with 0.25 gaps: two per line in each square.
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 0.5], &[0.25, -0.25])], &boundary).unwrap();
|
||||
assert_eq!(pieces(&bp).len(), 8, "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn families_based_far_away_draw_the_same_lines() {
|
||||
// Lines one apart from a base 1e19 up are the lines one apart from the origin.
|
||||
let mut far = line(0.0, [0.0, 1.0], &[]);
|
||||
far.base = [0.0, 1e19];
|
||||
let (bp, _) = pattern(&[far], &square(100.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert_eq!(p.len(), 100, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0 && (0.0..100.0).contains(&a.y)), "{p:?}");
|
||||
// A staggered family based 100 lines away keeps each line's dash phase.
|
||||
let mut near = line(0.0, [5.0, 10.0], &[3.0, -7.0]);
|
||||
near.base = [-497.0, 0.0];
|
||||
let mut away = near.clone();
|
||||
away.base = [3.0, 1000.0];
|
||||
let sorted = |l: PatternLine| {
|
||||
let mut p = pieces(&pattern(&[l], &square(100.0)).unwrap().0);
|
||||
p.sort_by(|a, b| (a.0.y, a.0.x).partial_cmp(&(b.0.y, b.0.x)).unwrap_or(std::cmp::Ordering::Equal));
|
||||
p
|
||||
};
|
||||
let (a, b) = (sorted(near), sorted(away));
|
||||
assert_eq!(a.len(), b.len());
|
||||
assert!(!a.is_empty());
|
||||
assert!(a.iter().zip(&b).all(|(x, y)| x.0.distance(y.0) < 1e-9 && x.1.distance(y.1) < 1e-9), "{a:?} {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn families_based_far_away_keep_lines_off_a_fractional_center() {
|
||||
// A 3 square centered on y 1.5: lines one apart from a base 1e19 up run at whole y, not
|
||||
// through the center.
|
||||
let mut far = line(0.0, [0.0, 1.0], &[]);
|
||||
far.base = [0.0, 1e19];
|
||||
let (bp, _) = pattern(&[far], &square(3.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!(p.len() >= 2, "{p:?}");
|
||||
assert!(p.iter().all(|(a, b)| a.y == b.y && a.y.fract() == 0.0), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_periods_far_longer_than_the_boundary_still_draw() {
|
||||
// Dashes 1e16 long from x 0, and from x -7.5e15: each row of the 100 square lies in a
|
||||
// dash, so every row is drawn across the square.
|
||||
for x in [0.0, -7.5e15] {
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]);
|
||||
l.base = [x, 0.0];
|
||||
let (bp, _) = pattern(&[l], &square(100.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
let rows: Vec<_> = p.iter().filter(|(a, _)| a.y > 0.0 && a.y < 100.0).collect();
|
||||
assert_eq!(rows.len(), 9, "base x {x}: {p:?}");
|
||||
assert!(rows.iter().all(|(a, b)| a.x.abs() < 1e-9 && (b.x - 100.0).abs() < 1e-9), "base x {x}: {p:?}");
|
||||
}
|
||||
// From x 5e15 the square lies in a gap: nothing is drawn.
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1e16, -1e16]);
|
||||
l.base = [5e15, 0.0];
|
||||
let (bp, _) = pattern(&[l], &square(100.0)).unwrap();
|
||||
assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_offset_counts_that_cancel_keep_the_dash_start() {
|
||||
// A 100 square 2^40 up, its family based on the row through its middle with offsets
|
||||
// 2^30 along: the row's dashes start at x 0, so it draws 0 to 30.
|
||||
let b = 2f64.powi(40);
|
||||
let mut boundary = square(100.0);
|
||||
boundary.apply_affine(Affine::translate((0.0, b)));
|
||||
let mut l = line(0.0, [2f64.powi(30), 1024.0], &[30.0, -70.0]);
|
||||
l.base = [0.0, b + 50.0];
|
||||
let p = pieces(&pattern(&[l], &boundary).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == b + 50.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row.len(), 1, "{p:?}");
|
||||
assert!((row[0].0 - 0.0).abs() < 1e-9 && (row[0].1 - 30.0).abs() < 1e-9, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_phase_terms_that_cancel_keep_a_small_one() {
|
||||
// Based and offset by 2^54 along and 10 up: the line one offset back runs along the
|
||||
// bottom of the unit square with its dash 16 long from x 0, so it covers 0 to 1.
|
||||
let big = 2f64.powi(54);
|
||||
let mut l = line(0.0, [big, 10.0], &[16.0, -(2f64.powi(57) - 16.0)]);
|
||||
l.base = [big, 10.0];
|
||||
let p = pieces(&pattern(&[l], &square(1.0)).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 0.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row, [(0.0, 1.0)], "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_dash_before_the_boundary_ends_where_its_gap_starts() {
|
||||
// A gap 1e16 long from x 0, after a dash 1e16 long that ends at x 0: the unit square
|
||||
// lies in the gap, so nothing is drawn.
|
||||
let mut l = line(0.0, [0.0, 10.0], &[-1e16, 1e16]);
|
||||
l.base = [0.0, 0.5];
|
||||
let (bp, _) = pattern(&[l], &square(1.0)).unwrap();
|
||||
assert!(pieces(&bp).is_empty(), "{:?}", pieces(&bp));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distant_bases_keep_their_dash_remainder() {
|
||||
// Dash 1, gap 5 from x 1e19, which is 4 more than a whole number of periods of 6: the
|
||||
// dashes run 4 to 5, 10 to 11 … 94 to 95 in squares centered on a whole and a half x.
|
||||
for side in [96.0, 98.0] {
|
||||
let mut l = line(0.0, [0.0, 10.0], &[1.0, -5.0]);
|
||||
l.base = [1e19, 0.0];
|
||||
let p = pieces(&pattern(&[l], &square(side)).unwrap().0);
|
||||
let row: Vec<_> = p.iter().filter(|(a, _)| a.y == 50.0).map(|(a, e)| (a.x, e.x)).collect();
|
||||
assert_eq!(row.len(), 16, "side {side}: {row:?}");
|
||||
assert!(
|
||||
row.iter().enumerate().all(|(i, (a, e))| (a - (4.0 + 6.0 * i as f64)).abs() < 1e-9 && (e - a - 1.0).abs() < 1e-9),
|
||||
"side {side}: {row:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dot_on_the_start_of_a_span_is_kept() {
|
||||
// A gap of 5 then a dot, from x 0: dots at 0, 5 and 10 on the line along the bottom.
|
||||
let (bp, dots) = pattern(&[line(0.0, [0.0, 20.0], &[-5.0, 0.0])], &square(10.0)).unwrap();
|
||||
assert!(dots);
|
||||
let xs: Vec<f64> = pieces(&bp).iter().filter(|(a, _)| a.y == 0.0).map(|(a, _)| a.x).collect();
|
||||
assert_eq!(xs, [0.0, 5.0, 10.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slanted_lines_fill_a_square_evenly() {
|
||||
// 45 degree lines 1 apart across the square's diagonal of 14.1: each piece runs from one
|
||||
// side of the square to another.
|
||||
let offset = [-(0.5f64.sqrt()), 0.5f64.sqrt()];
|
||||
let (bp, _) = pattern(&[line(45.0, offset, &[])], &square(10.0)).unwrap();
|
||||
let p = pieces(&bp);
|
||||
assert!((14..=15).contains(&p.len()), "{} lines", p.len());
|
||||
let on_edge = |q: Point| [q.x, q.y].iter().any(|v| v.abs() < 1e-6 || (v - 10.0).abs() < 1e-6);
|
||||
assert!(p.iter().all(|(a, b)| on_edge(*a) && on_edge(*b)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_dense_patterns_and_missing_ones_are_reported() {
|
||||
assert_eq!(pattern(&[], &square(10.0)), Err(NoPattern::Undefined));
|
||||
// Lines 0.001 apart across a 1,000 square: a million lines.
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 0.001], &[])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// Few lines, but dashes far shorter than the square: more pieces than allowed.
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 10.0], &[0.01, -0.01])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// A tiny nonempty dash period is too dense; only an empty list draws continuous lines.
|
||||
// It is refused once the first line is clipped, before any of its dashes is looked at.
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-12])], &square(10.0), &mut budget), Err(NoPattern::TooDense));
|
||||
assert_eq!(budget.work, usize::MAX - 4, "one line clipped against four edges, no dashes looked at");
|
||||
// A period below the coordinates' precision is refused before any line is clipped.
|
||||
let mut budget = Budget { pieces: usize::MAX, work: usize::MAX, stopped: None };
|
||||
assert_eq!(super::pattern(&[line(0.0, [0.0, 1.0], &[-1e-15])], &square(10.0), &mut budget), Err(NoPattern::TooDense));
|
||||
assert_eq!(budget.work, usize::MAX, "no work done");
|
||||
let (bp, _) = pattern(&[line(0.0, [0.0, 1.0], &[])], &square(10.0)).unwrap();
|
||||
assert!(!pieces(&bp).is_empty());
|
||||
// Lines on top of each other, or as good as, are as dense as can be.
|
||||
assert_eq!(pattern(&[line(0.0, [5.0, 0.0], &[])], &square(10.0)), Err(NoPattern::TooDense));
|
||||
assert_eq!(pattern(&[line(0.0, [0.0, 1e-7], &[])], &square(1000.0)), Err(NoPattern::TooDense));
|
||||
// Only damaged families: no pattern to draw.
|
||||
assert_eq!(pattern(&[line(f64::NAN, [0.0, 1.0], &[])], &square(10.0)), Err(NoPattern::Undefined));
|
||||
}
|
||||
|
||||
fn grad(name: &str, angle: f64, shift: f64) -> model::Gradient {
|
||||
model::Gradient {
|
||||
name: name.into(),
|
||||
angle,
|
||||
shift,
|
||||
single: false,
|
||||
tint: 0.0,
|
||||
colors: vec![model::Color::Index(1), model::Color::Rgb([0, 0, 255])],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradients_run_across_the_boundary_at_their_angle() {
|
||||
let box_ = {
|
||||
let mut b = square(100.0);
|
||||
b.apply_affine(Affine::scale_non_uniform(2.0, 1.0));
|
||||
b
|
||||
};
|
||||
let g = gradient(&grad("LINEAR", 0.0, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.kind, g.geom.start, g.geom.end), (GradientKind::Linear, Point::new(0.0, 50.0), Point::new(200.0, 50.0)));
|
||||
assert_eq!((g.first, g.second), (Col::Rgb(aci_paper(1)), Second::Col(Col::Rgb([0, 0, 255]))));
|
||||
assert_eq!(g.stops, [(0.0, false), (1.0, true)]);
|
||||
// At a quarter turn it runs bottom to top.
|
||||
let g = gradient(&grad("LINEAR", std::f64::consts::FRAC_PI_2, 0.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert!(g.geom.start.distance(Point::new(100.0, 0.0)) < 1e-9 && g.geom.end.distance(Point::new(100.0, 100.0)) < 1e-9, "{g:?}");
|
||||
// Shifted, the center moves up and left: a sphere's center and a cylinder's middle.
|
||||
let g = gradient(&grad("SPHERICAL", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.kind, g.geom.start), (GradientKind::Radial, Point::new(50.0, 75.0)));
|
||||
assert_eq!(g.stops, [(0.0, true), (1.0, false)], "the second color in the center");
|
||||
let g = gradient(&grad("CYLINDER", 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!(g.geom.start.midpoint(g.geom.end), Point::new(50.0, 75.0));
|
||||
// A curved gradient runs bottom to top, so the shift moves it up.
|
||||
for name in ["CURVED", "INVCURVED"] {
|
||||
let g = gradient(&grad(name, 0.0, 1.0), &box_, Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((g.geom.start, g.geom.end), (Point::new(50.0, 25.0), Point::new(50.0, 125.0)), "{name}");
|
||||
}
|
||||
// A plane stretched twice as wide stretches the circle into an ellipse with it.
|
||||
let g = gradient(&grad("SPHERICAL", 0.0, 0.0), &square(10.0), Affine::scale_non_uniform(2.0, 1.0), Col::ByLayer).unwrap();
|
||||
assert!((g.geom.aspect - 0.5).abs() < 1e-9 && g.geom.end.distance(Point::new(20.0, 5.0)) < 1e-9, "{:?}", g.geom);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_gradients_swap_their_colors() {
|
||||
for (name, inv) in
|
||||
[("CYLINDER", "INVCYLINDER"), ("SPHERICAL", "INVSPHERICAL"), ("HEMISPHERICAL", "INVHEMISPHERICAL"), ("CURVED", "INVCURVED")]
|
||||
{
|
||||
let a = gradient(&grad(name, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
let b = gradient(&grad(inv, 0.0, 0.0), &square(10.0), Affine::IDENTITY, Col::ByLayer).unwrap();
|
||||
assert_eq!((a.kind, a.geom), (b.kind, b.geom), "{name}");
|
||||
let count = if name == "CYLINDER" { 3 } else { 2 };
|
||||
assert_eq!((a.stops.len(), b.stops.len()), (count, count), "{name}");
|
||||
assert!(a.stops.iter().zip(&b.stops).all(|(x, y)| x.0 == y.0 && x.1 != y.1), "{name}: {:?} {:?}", a.stops, b.stops);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_color_gradients_shade_or_tint_their_color() {
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.0), [0, 0, 0]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.5), [200, 100, 0]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 1.0), [255, 255, 255]);
|
||||
assert_eq!(Grad::tinted([200, 100, 0], 0.25), [100, 50, 0]);
|
||||
let mut g = grad("LINEAR", 0.0, 0.0);
|
||||
(g.single, g.tint, g.colors) = (true, 0.75, vec![]);
|
||||
let g = gradient(&g, &square(10.0), Affine::IDENTITY, Col::ByBlock).unwrap();
|
||||
assert_eq!((g.first, g.second), (Col::ByBlock, Second::Tint(0.75)), "no color record: the hatch's own color");
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use kurbo::ParamCurve;
|
||||
use kurbo::{ParamCurve, Shape};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Justify, Node, NodeKind, TextObject, Unit};
|
||||
use vectorcraft_doc::{Appearance, Document, Justify, LineCap, Node, NodeKind, TextObject, Unit};
|
||||
use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes};
|
||||
|
||||
use super::*;
|
||||
@@ -505,6 +505,593 @@ fn solid_hatches_fill_and_pattern_hatches_outline() {
|
||||
assert!(square.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
}
|
||||
|
||||
/// [`hatch`]'s square with a round hole, as a pattern hatch of level lines 10 apart through
|
||||
/// y 5, 15 … 95, in linetype `linetype`, with `dashes` (79 and 49 groups).
|
||||
fn pattern_hatch(linetype: &'static str, dashes: &[(i32, &'static str)]) -> Vec<(i32, &'static str)> {
|
||||
let mut e = hatch("0");
|
||||
e.insert(1, (6, linetype));
|
||||
let seeds = e.iter().position(|p| *p == (98, "0")).unwrap();
|
||||
let mut lines = vec![(78, "1"), (53, "0"), (43, "0"), (44, "5"), (45, "0"), (46, "10")];
|
||||
lines.extend_from_slice(if dashes.is_empty() { &[(79, "0")] } else { dashes });
|
||||
e.splice(seeds..seeds, lines);
|
||||
e
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignore_islands_hatches_fill_and_pattern_through_the_hole() {
|
||||
let mut e = hatch("1");
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "ignore islands leaves only the outer square");
|
||||
assert!(path.subpaths[0].closed);
|
||||
assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
let box_area = bounds(area).area();
|
||||
assert!((path.to_bezpath().area().abs() - box_area).abs() < box_area * 1e-9, "the whole square is filled");
|
||||
|
||||
let mut e = pattern_hatch("CONTINUOUS", &[]);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
assert_eq!(children.len(), 10, "the ten level lines are not cut by the hole");
|
||||
let width = bounds(lines).width();
|
||||
assert!(children.iter().all(|c| (bounds(c).width() - width).abs() < width * 1e-9), "each line spans the square");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_island_styles_select_nested_boundary_levels() {
|
||||
let mut e = hatch("1");
|
||||
let count = e.iter().position(|p| p.0 == 91).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
e[count] = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
// Innermost first so nesting depends on geometry, not boundary order or flags.
|
||||
for (lo, hi) in [("40", "60"), ("0", "100"), ("20", "80")] {
|
||||
loops.extend([
|
||||
(92, "2"),
|
||||
(72, "0"),
|
||||
(73, "1"),
|
||||
(93, "4"),
|
||||
(10, lo),
|
||||
(20, lo),
|
||||
(10, hi),
|
||||
(20, lo),
|
||||
(10, hi),
|
||||
(20, hi),
|
||||
(10, lo),
|
||||
(20, hi),
|
||||
(97, "0"),
|
||||
]);
|
||||
}
|
||||
e.splice(count + 1..end, loops);
|
||||
// The sides of the squares each style keeps: normal and unknown styles all three, outer the
|
||||
// outermost and middle ones, ignore the outermost alone.
|
||||
for (style, expected) in [("0", &[20.0, 60.0, 100.0][..]), ("1", &[60.0, 100.0]), ("2", &[100.0]), ("3", &[20.0, 60.0, 100.0])] {
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style);
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "style {style}: {:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let mut sides: Vec<f64> = match &area.kind {
|
||||
NodeKind::Compound { children, rule } => {
|
||||
assert_eq!(*rule, FillRule::EvenOdd);
|
||||
children.iter().map(|c| bounds(c).width().round()).collect()
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(area.path_data().unwrap().subpaths.len(), 1);
|
||||
vec![bounds(area).width().round()]
|
||||
}
|
||||
};
|
||||
sides.sort_by(f64::total_cmp);
|
||||
assert_eq!(sides, expected, "boundary loops for island style {style}");
|
||||
assert!(area.appearance.fill().is_some_and(|f| !f.paint.is_none()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_small_island_far_from_origin() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("100000000", "100000001"), ("100000000.2", "100000000.8")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Centered, so the art far from the drawing's origin lands on the canvas.
|
||||
let r = open(&entities(&e), &ImportOptions { center: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the small island far from the origin is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_small_island_with_distant_outer_loop() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
*e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("0", "1"), ("0.2", "0.8"), ("100000000", "100000001")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Fitted to the artboard: the drawing spans more than the canvas holds at 1:1.
|
||||
let r = open(&entities(&e), &ImportOptions { fit: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "the island is removed and both outer squares remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_tiny_island_with_distant_outer_loop() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
*e.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "3");
|
||||
let mut loops = Vec::new();
|
||||
for (lo, hi) in [("0", "0.000001"), ("0.0000002", "0.0000008"), ("100000000000", "100000000001")] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [(lo, lo), (hi, lo), (hi, hi), (lo, hi)] {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
// Fitted to the artboard: the drawing spans more than the canvas holds at 1:1.
|
||||
let r = open(&entities(&e), &ImportOptions { fit: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both outer boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "the tiny island is removed and both outer squares remain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_keeps_squares_sharing_an_edge() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// The first vertex lies on the second square's left edge.
|
||||
for vertices in [[("10", "0"), ("10", "10"), ("0", "10"), ("0", "0")], [("10", "0"), ("20", "0"), ("20", "10"), ("10", "10")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &area.kind else { panic!("both boundary loops must remain") };
|
||||
assert_eq!(children.len(), 2, "adjacent squares are both boundaries");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_square_touching_outer_boundary_at_a_vertex() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// The island's first vertex touches the outer square's right edge, where
|
||||
// winding is zero. Its other vertices and all segment midpoints are inside.
|
||||
for vertices in [[("100", "50"), ("75", "75"), ("50", "50"), ("75", "25")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the touching island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_square_sharing_two_outer_edges() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for vertices in [[("50", "50"), ("100", "50"), ("100", "100"), ("50", "100")], [("0", "0"), ("100", "0"), ("100", "100"), ("0", "100")]] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the island sharing two outer edges is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_thin_island() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
for vertices in [
|
||||
[("0", "0"), ("100", "0"), ("100", "0.00001"), ("0", "0.00001")],
|
||||
[("10", "0.000002"), ("90", "0.000002"), ("90", "0.000008"), ("10", "0.000008")],
|
||||
] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the thin island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_ignore_islands_drops_rotated_thin_island() {
|
||||
let mut e = hatch("1");
|
||||
let start = e.iter().position(|p| p.0 == 92).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
let mut loops = Vec::new();
|
||||
// These are the previous test's corners turned 45 degrees about the origin.
|
||||
for vertices in [
|
||||
[("0", "0"), ("70.7106781187", "70.7106781187"), ("70.7106710476", "70.7106851897"), ("-0.00000707106781187", "0.00000707106781187")],
|
||||
[
|
||||
("7.07106639765", "7.07106922608"),
|
||||
("63.6396088926", "63.6396117210"),
|
||||
("63.6396046499", "63.6396159636"),
|
||||
("7.07106215421", "7.07107346952"),
|
||||
],
|
||||
] {
|
||||
loops.extend([(92, "2"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in vertices {
|
||||
loops.extend([(10, x), (20, y)]);
|
||||
}
|
||||
loops.push((97, "0"));
|
||||
}
|
||||
e.splice(start..end, loops);
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, "2");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let path = area.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1, "the rotated thin island is removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_island_work_limit_keeps_all_loops_and_warns_only_for_island_styles() {
|
||||
let mut e = hatch("1");
|
||||
let count = e.iter().position(|p| p.0 == 91).unwrap();
|
||||
let hole = e.iter().position(|p| *p == (92, "0")).unwrap();
|
||||
let end = e.iter().position(|p| p.0 == 75).unwrap();
|
||||
e[count] = (91, "16");
|
||||
// Keep the outer square and add 15 inner squares. With at least five path elements
|
||||
// per square, 16 loops require at least 1,280 steps, over the test-time limit.
|
||||
// Without the fallback, ignore style removes the inner squares.
|
||||
let inner = [
|
||||
(92, "2"),
|
||||
(72, "0"),
|
||||
(73, "1"),
|
||||
(93, "4"),
|
||||
(10, "20"),
|
||||
(20, "20"),
|
||||
(10, "80"),
|
||||
(20, "20"),
|
||||
(10, "80"),
|
||||
(20, "80"),
|
||||
(10, "20"),
|
||||
(20, "80"),
|
||||
(97, "0"),
|
||||
];
|
||||
e.splice(hole..end, inner.repeat(15));
|
||||
for style in ["2", "0"] {
|
||||
*e.iter_mut().find(|p| p.0 == 75).unwrap() = (75, style);
|
||||
let r = open(&entities(&e), &points());
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let count = match &area.kind {
|
||||
NodeKind::Compound { children, .. } => children.len(),
|
||||
_ => area.path_data().unwrap().subpaths.len(),
|
||||
};
|
||||
assert_eq!(count, 16, "every boundary loop is kept for style {style}");
|
||||
if style == "2" {
|
||||
assert_eq!(r.warnings, ["hatches with too many boundary points to sort into islands are filled as if every loop were a boundary"]);
|
||||
} else {
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_hatches_draw_their_lines_inside_the_boundary() {
|
||||
// A dashed linetype on the hatch: its pattern lines stay solid, as the pattern defines them.
|
||||
let tables = [(0, "TABLE"), (2, "LTYPE"), (0, "LTYPE"), (2, "DASHED"), (73, "2"), (40, "15"), (49, "10"), (49, "-5"), (0, "ENDTAB")];
|
||||
let r = open(&drawing(&[], &tables, &[], &pattern_hatch("DASHED", &[])), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
// Ten lines; the four that cross the hole (y 35 to 65) are cut in two.
|
||||
assert_eq!(children.len(), 14);
|
||||
assert_eq!(stroke_rgb(lines), [255, 0, 0, 255]);
|
||||
assert!(lines.appearance.fill().is_none_or(|f| f.paint.is_none()), "the lines are not filled");
|
||||
assert!(lines.appearance.stroke().is_some_and(|s| s.dash.is_none()), "no linetype dashes on pattern lines");
|
||||
let h = height(&r.document);
|
||||
for c in children {
|
||||
let pts = path_points(c);
|
||||
let (a, b) = (pts[0], *pts.last().unwrap());
|
||||
let y = h - a.y;
|
||||
assert!((a.y - b.y).abs() < 1e-9 && (y - 5.0).rem_euclid(10.0) < 1e-9, "level lines through y 5, 15 …: {a:?} {b:?}");
|
||||
assert!(a.x.min(b.x) >= -1e-9 && a.x.max(b.x) <= 100.0 + 1e-9, "inside the square: {a:?} {b:?}");
|
||||
let mid = Point::new((a.x + b.x) / 2.0, y);
|
||||
assert!(mid.distance(Point::new(50.0, 50.0)) > 20.0, "outside the hole: {a:?} {b:?}");
|
||||
}
|
||||
assert!(lines.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round));
|
||||
// A pattern of dots (no length) shows them with round caps.
|
||||
let r = open(&entities(&pattern_hatch("CONTINUOUS", &[(79, "2"), (49, "0"), (49, "-5")])), &points());
|
||||
let [dots] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round), "{:?}", r.warnings);
|
||||
// Dashes and dots together: the dots take round caps on a path of their own, and the dashes
|
||||
// keep butt caps, so they do not grow into their gaps.
|
||||
let mixed = [(79, "4"), (49, "3"), (49, "-2"), (49, "0"), (49, "-5")];
|
||||
let r = open(&entities(&pattern_hatch("CONTINUOUS", &mixed)), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [hatch_art] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let [dashes, dots] = &hatch_art.children().unwrap()[..] else { panic!("dashes and dots: {:?}", hatch_art.kind) };
|
||||
assert!(dashes.appearance.stroke().is_some_and(|s| s.cap != LineCap::Round));
|
||||
assert!(dots.appearance.stroke().is_some_and(|s| s.cap == LineCap::Round));
|
||||
let length = |n: &Node| {
|
||||
let pts = path_points(n);
|
||||
pts[0].distance(*pts.last().unwrap())
|
||||
};
|
||||
let pieces = |n: &Node| match &n.kind {
|
||||
NodeKind::Compound { children, .. } => children.iter().map(|c| (**c).clone()).collect(),
|
||||
_ => vec![n.clone()],
|
||||
};
|
||||
assert!(pieces(dashes).iter().all(|c| length(c) > 1e-9), "no dots among the dashes");
|
||||
assert!(pieces(dots).iter().all(|c| length(c) < 1e-9), "only dots");
|
||||
// Without its pattern lines a pattern hatch still comes in as its boundary, with a note.
|
||||
let r = open(&entities(&hatch("0")), &points());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("without usable pattern lines")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_defined_double_hatches_draw_level_and_vertical_lines() {
|
||||
for double in ["1", "0"] {
|
||||
let mut e = pattern_hatch("CONTINUOUS", &[]);
|
||||
let kind = e.iter().position(|p| *p == (76, "1")).unwrap();
|
||||
e[kind] = (76, "0");
|
||||
e.insert(kind + 1, (77, double));
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [lines] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let NodeKind::Compound { children, .. } = &lines.kind else { panic!("{:?}", lines.kind) };
|
||||
let (mut level, mut vertical) = (0, 0);
|
||||
for c in children {
|
||||
let pts = path_points(c);
|
||||
let (a, b) = (pts[0], *pts.last().unwrap());
|
||||
if (a.y - b.y).abs() < 1e-9 && (a.x - b.x).abs() > 1e-9 {
|
||||
level += 1;
|
||||
} else if (a.x - b.x).abs() < 1e-9 && (a.y - b.y).abs() > 1e-9 {
|
||||
vertical += 1;
|
||||
} else {
|
||||
panic!("level or vertical piece: {a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
assert!(level > 0, "level pieces with double = {double}");
|
||||
assert_eq!(vertical > 0, double == "1", "vertical pieces with double = {double}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pattern_hatches_share_the_drawings_budget() {
|
||||
// Keep the fixture's square alone so every fallback is one closed path.
|
||||
let mut hatch = pattern_hatch("CONTINUOUS", &[]);
|
||||
let hole = hatch.iter().position(|p| *p == (92, "0")).unwrap();
|
||||
let end = hatch.iter().position(|p| p.0 == 75).unwrap();
|
||||
hatch.drain(hole..end);
|
||||
*hatch.iter_mut().find(|p| p.0 == 91).unwrap() = (91, "1");
|
||||
let limit = super::hatch::MAX_TOTAL_PIECES;
|
||||
let count = limit / 10 + 5;
|
||||
let e = hatch.repeat(count);
|
||||
let r = open(&entities(&e), &points());
|
||||
assert_eq!(r.warnings.len(), 1, "{:?}", r.warnings);
|
||||
assert!(r.warnings[0].contains("2,000,000 dashes in all"), "{:?}", r.warnings);
|
||||
let art = r.document.layers[0].children().unwrap();
|
||||
assert_eq!(art.len(), count, "each hatch keeps its place");
|
||||
let mut pieces = 0;
|
||||
let mut boundaries = 0;
|
||||
for n in art {
|
||||
if let NodeKind::Compound { children, .. } = &n.kind {
|
||||
assert_eq!(boundaries, 0, "all hatches after exhaustion keep their boundaries");
|
||||
pieces += children.len();
|
||||
assert!(children.iter().all(|c| c.path_data().is_some_and(|p| p.subpaths.iter().all(|s| !s.closed))));
|
||||
} else {
|
||||
let path = n.path_data().unwrap();
|
||||
assert_eq!(path.subpaths.len(), 1);
|
||||
assert!(path.subpaths[0].closed);
|
||||
boundaries += 1;
|
||||
}
|
||||
}
|
||||
assert!(pieces > 0 && pieces <= limit, "{pieces} pieces against {limit}");
|
||||
assert!(boundaries >= 5, "hatches past the budget keep their boundaries");
|
||||
}
|
||||
|
||||
/// [`hatch`]'s square with a round hole, filled with gradient `name` at `angle` (radians) from
|
||||
/// a true color (red) to color 5 (blue), or from red alone with `tint`.
|
||||
fn gradient_hatch(name: &'static str, angle: &'static str, tint: Option<&'static str>) -> Vec<(i32, &'static str)> {
|
||||
let mut e = hatch("1");
|
||||
e.extend([(450, "1"), (451, "0"), (452, if tint.is_some() { "1" } else { "0" }), (453, "2"), (460, angle), (461, "0")]);
|
||||
e.extend([(462, tint.unwrap_or("0")), (463, "0"), (63, "1"), (421, "16711680"), (463, "1"), (63, "5"), (470, name)]);
|
||||
e
|
||||
}
|
||||
|
||||
fn gradient_of(n: &Node) -> vectorcraft_color::GradientPaint {
|
||||
match n.appearance.fill().map(|f| &f.paint) {
|
||||
Some(Paint::Gradient(g)) => (**g).clone(),
|
||||
other => panic!("not a gradient: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_hatches_keep_their_gradient() {
|
||||
let r = open(&entities(&gradient_hatch("LINEAR", "0", None)), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
let g = gradient_of(area);
|
||||
let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect();
|
||||
assert_eq!(g.gradient.kind, vectorcraft_color::GradientKind::Linear);
|
||||
assert_eq!(colors, [[255, 0, 0, 255], [0, 0, 255, 255]], "the true color, then color 5");
|
||||
// Level, across the square from left to right through its middle.
|
||||
let (h, geom) = (height(&r.document), g.geom.unwrap());
|
||||
assert!(geom.start.distance(Point::new(0.0, h - 50.0)) < 1e-9 && geom.end.distance(Point::new(100.0, h - 50.0)) < 1e-9, "{geom:?}");
|
||||
// A quarter turn runs it up the square: from the bottom (larger y in the document) to the top.
|
||||
let r = open(&entities(&gradient_hatch("LINEAR", "1.5707963267948966", None)), &points());
|
||||
let geom = gradient_of(&r.document.layers[0].children().unwrap()[0]).geom.unwrap();
|
||||
assert!(geom.start.distance(Point::new(50.0, h)) < 1e-6 && geom.end.distance(Point::new(50.0, h - 100.0)) < 1e-6, "{geom:?}");
|
||||
// A one-color sphere tinted to white: white in the center, red at the edge.
|
||||
let r = open(&entities(&gradient_hatch("SPHERICAL", "0", Some("1"))), &points());
|
||||
let g = gradient_of(&r.document.layers[0].children().unwrap()[0]);
|
||||
let colors: Vec<[u8; 4]> = g.gradient.stops.iter().map(|s| s.color.to_rgba8(1.0)).collect();
|
||||
assert_eq!((g.gradient.kind, colors), (vectorcraft_color::GradientKind::Radial, vec![[255; 4], [255, 0, 0, 255]]));
|
||||
assert!(g.geom.unwrap().start.distance(Point::new(50.0, h - 50.0)) < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_gradient_stops_keep_the_inserts_color() {
|
||||
for (color, layer) in [("0", "Doors"), ("256", "0")] {
|
||||
for (second, tint) in [(false, None), (true, None), (false, Some("1"))] {
|
||||
let mut hatch = gradient_hatch("LINEAR", "0", tint);
|
||||
// The hatch's explicit color and other properties do not need insert inheritance.
|
||||
hatch.splice(1..1, [(8, layer), (6, "CONTINUOUS"), (370, "25")]);
|
||||
hatch.retain(|p| p.0 != 421);
|
||||
let stop = hatch.iter_mut().filter(|p| p.0 == 63).nth(usize::from(second)).unwrap();
|
||||
*stop = (63, color);
|
||||
let inserts = [(0, "INSERT"), (8, "Doors"), (2, "Door"), (62, "3"), (10, "0"), (20, "0")];
|
||||
let r = open(&with_door(&hatch, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [symbol] = &r.document.symbols[..] else { panic!("one symbol") };
|
||||
let g = gradient_of(&symbol.art);
|
||||
let stop = &g.gradient.stops[usize::from(second)];
|
||||
let expected = if color == "0" { [0, 255, 0, 255] } else { [0, 0, 255, 255] };
|
||||
assert_eq!(stop.color.to_rgba8(1.0), expected, "color {color}, second {second}, tint {tint:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_hatches_far_out_keep_their_fill() {
|
||||
// A sphere hatch on a strip 10 wide ending 1e12 out: its circle reaches past 1e12, and the
|
||||
// strip still comes in, centered on the artboard.
|
||||
let mut e = vec![(0, "HATCH"), (62, "1"), (10, "0"), (20, "0"), (30, "0"), (2, "SOLID"), (70, "1"), (71, "0"), (91, "1")];
|
||||
e.extend([(92, "3"), (72, "0"), (73, "1"), (93, "4")]);
|
||||
for (x, y) in [("999999999990", "0"), ("1000000000000", "0"), ("1000000000000", "100"), ("999999999990", "100")] {
|
||||
e.extend([(10, x), (20, y)]);
|
||||
}
|
||||
e.extend([(97, "0"), (75, "0"), (76, "1"), (98, "0")]);
|
||||
e.extend([(450, "1"), (451, "0"), (452, "0"), (453, "2"), (460, "0"), (461, "0")]);
|
||||
e.extend([(462, "0"), (463, "0"), (63, "1"), (463, "1"), (63, "5"), (470, "SPHERICAL")]);
|
||||
let r = open(&entities(&e), &ImportOptions { center: true, ..points() });
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [area] = &r.document.layers[0].children().unwrap()[..] else { panic!("one hatch") };
|
||||
assert_eq!(gradient_of(area).gradient.kind, vectorcraft_color::GradientKind::Radial);
|
||||
assert_eq!(bounds(area).width().round(), 10.0);
|
||||
}
|
||||
|
||||
/// [`with_door`] with a dashed linetype `DASHED` in the drawing.
|
||||
fn with_dashed_door(block_art: &[(i32, &'static str)], inserts: &[(i32, &'static str)]) -> Vec<u8> {
|
||||
let mut blocks = vec![(0, "BLOCK"), (8, "0"), (2, "Door"), (70, "0"), (10, "5"), (20, "5"), (3, "Door")];
|
||||
blocks.extend_from_slice(block_art);
|
||||
blocks.push((0, "ENDBLK"));
|
||||
let tables = [
|
||||
(0, "TABLE"),
|
||||
(2, "LTYPE"),
|
||||
(0, "LTYPE"),
|
||||
(2, "DASHED"),
|
||||
(73, "2"),
|
||||
(40, "15"),
|
||||
(49, "10"),
|
||||
(49, "-5"),
|
||||
(0, "ENDTAB"),
|
||||
(0, "TABLE"),
|
||||
(2, "LAYER"),
|
||||
(0, "LAYER"),
|
||||
(2, "Doors"),
|
||||
(70, "0"),
|
||||
(62, "5"),
|
||||
(6, "CONTINUOUS"),
|
||||
(0, "ENDTAB"),
|
||||
];
|
||||
drawing(&[], &tables, &blocks, inserts)
|
||||
}
|
||||
|
||||
/// Whether `n` or any object inside it has a dashed stroke.
|
||||
fn dashed(n: &Node) -> bool {
|
||||
n.appearance.stroke().is_some_and(|s| s.dash.is_some()) || n.children().is_some_and(|c| c.iter().any(|c| dashed(c)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_pattern_hatches_ignore_the_inserts_linetype() {
|
||||
let inserts = [(0, "INSERT"), (2, "Door"), (62, "1"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (62, "3"), (10, "200"), (20, "0")];
|
||||
// Pattern lines draw without a linetype: inserts of other colors share one symbol.
|
||||
let mut lines = pattern_hatch("BYBLOCK", &[]);
|
||||
lines.splice(1..1, [(8, "Doors"), (370, "25")]);
|
||||
let r = open(&with_door(&lines, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(r.document.symbols.len(), 1);
|
||||
// A pattern hatch drawn as its boundary strokes it in the insert's linetype.
|
||||
let mut boundary = hatch("0");
|
||||
boundary.splice(1..1, [(8, "Doors"), (370, "25"), (6, "BYBLOCK")]);
|
||||
let r = open(&with_door(&boundary, &inserts), &points());
|
||||
assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings);
|
||||
|
||||
// Inserts of one color, one dashed and one continuous.
|
||||
let inserts =
|
||||
[(0, "INSERT"), (2, "Door"), (6, "DASHED"), (10, "0"), (20, "0"), (0, "INSERT"), (2, "Door"), (6, "CONTINUOUS"), (10, "200"), (20, "0")];
|
||||
let r = open(&with_dashed_door(&lines, &inserts), &points());
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let [symbol] = &r.document.symbols[..] else { panic!("one symbol for both linetypes") };
|
||||
assert!(!dashed(&symbol.art), "pattern lines carry no linetype dashes");
|
||||
// The boundary drawn for each insert takes that insert's linetype.
|
||||
let r = open(&with_dashed_door(&boundary, &inserts), &points());
|
||||
assert_eq!(r.document.symbols.len(), 2, "{:?}", r.warnings);
|
||||
let looks: Vec<bool> = leaves(&r.document)
|
||||
.iter()
|
||||
.map(|n| {
|
||||
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { panic!("{:?}", n.kind) };
|
||||
dashed(&r.document.symbols.iter().find(|s| s.name == *symbol).unwrap().art)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(looks, [true, false], "the dashed insert's boundary is dashed, the continuous one's is not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hatch_declaring_many_absent_source_handles_parses_quickly() {
|
||||
let base = hatch("1");
|
||||
|
||||
@@ -371,7 +371,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's
|
||||
| PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` |
|
||||
| DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` |
|
||||
| SVG / SVGZ | open, place, save | yes | yes (SVG Options, Preserve Editing, symbols, filters, rich text) | strongest format; tests in `crates/svg/tests`; text on a path follows basic shapes as their SVG 2 equivalent paths (#1527); CSS transforms and the `font` shorthand (#1565), percentage lengths in symbols (#1596), Inkscape flowed text as area type (#1568) and Inkscape pages as artboards (#1601) import; an unsupported filter is named in its warning (#1598); an artboard exported on its own (Export As with Use Artboards, Export for Screens, Asset Export) has the artboard's name as `<title>`, Save the document's (#3544); attributes in other applications' XML namespaces (`plotter:pen="2"`) kept on their objects from import to export, as `data-*` attributes are (`crates/svg/tests/it/foreign_attributes.rs`); simple shapes export as `<rect>`, `<circle>`, `<ellipse>`, `<line>`, `<polygon>` and `<polyline>` where they draw the same as the path (#4652, `crates/svg/tests/it/basic_shapes.rs`); the regions of exported masks and filters (opacity masks, inverted masks, knockout groups) cover the art they apply to, and over type keep a region that covers any artwork (#6401, `crates/svg/tests/it/blend_export.rs`); a masked group, or a knockout group's masked group, whose content has a shadow, glow, blur or feather starts with a hidden, unpainted rectangle over the mask's region, so readers that draw a masked group only inside the box of its shapes draw those effects too (`crates/svg/tests/it/blend_export.rs`); SVG Options › Include Variable Data writes the text variables, data sets and bound type objects, and opening the SVG reads them back (`tests::variables::an_svg_with_variable_data_opens_with_its_variables_data_sets_and_bindings`); SVG Options › Units writes `width` and `height` in px (bare numbers, the default), pt, mm, cm or in, the `viewBox` staying in points, for software that reads physical size such as LaserGRBL (#4462, `crates/svg/tests/it/roundtrip.rs`) |
|
||||
| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. REGION entities open as filled paths of their faces' boundary loops (lines, circles, ellipses and spline edges), read from the text data of DXF R13 to 2010 and the binary data in the ACDSDATA section of DXF 2013 and later, DWG included; edges of other curve types come in straight, an outline that breaks off is closed with a straight line, and a spline edge whose endpoint lies on two parts of a self-crossing curve is trimmed at the nearer one, each with a warning ([REGION group codes](https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4), `crates/cad/src/import/tests_region.rs`) |
|
||||
| DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open. REGION entities open as filled paths of their faces' boundary loops (lines, circles, ellipses and spline edges), read from the text data of DXF R13 to 2010 and the binary data in the ACDSDATA section of DXF 2013 and later, DWG included; edges of other curve types come in straight, an outline that breaks off is closed with a straight line, and a spline edge whose endpoint lies on two parts of a self-crossing curve is trimmed at the nearer one, each with a warning ([REGION group codes](https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-644BF0F0-FD79-4C5E-AD5A-0053FCC5A5A4), `crates/cad/src/import/tests_region.rs`). DXF and DWG import draw a pattern hatch as its pattern lines (groups 53, 43–46 and 49) clipped to its boundary and cut into their dashes and dots, and fill a gradient hatch (groups 450–470) with a linear or radial gradient in its colors at its angle; hatches follow their island style (normal, outer, ignore); the mapping of each named gradient to a linear or radial one is VectorCraft's own (`pattern_hatches_draw_their_lines_inside_the_boundary`, `gradient_hatches_keep_their_gradient`; [HATCH group codes](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-C6C71CED-CE0F-4184-82A5-07AD6241F15B.htm)) |
|
||||
| HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines; Export As opens HP-GL Options) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` |
|
||||
| DWG | open, export | yes (open and place: craft-dwg converts the drawing to DXF, in a child process on desktop, and the DXF reader reads it with the DXF import options) | no (export DXF instead) | `crates/cad/src/import/tests_dwg.rs`, `crates/engine/src/cmd/fileio/tests_dwgimport.rs` (drawings written as DXF and converted to DWG by craft-dwg's writer); not in the web build |
|
||||
| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` |
|
||||
|
||||
+9
-2
@@ -13030,14 +13030,21 @@ artboard under `at`). `center: false` puts the drawing's origin (fitted art: its
|
||||
artboard's bottom-left corner; `mergeLayers` puts all art on one layer. Each DXF layer holding art becomes a layer
|
||||
(off and frozen layers hidden, locked ones locked, non-plotting ones non-printing). Lines, polylines (arc segments from
|
||||
bulges), circles, arcs, ellipses, splines (NURBS, within a millionth of their size), solids and hatches become paths (solid
|
||||
hatches filled, pattern hatches as their boundaries), text and multiline text point type, named blocks symbols
|
||||
hatches filled; hatches follow their island style (normal, outer, ignore), except that a hatch with too many boundary
|
||||
points to sort into islands is filled as if every loop were a boundary, with a warning, so an ignore-style hatch can
|
||||
keep its holes; gradient hatches filled with a linear or
|
||||
radial gradient at their angle, in their two colors or one color shaded or tinted; pattern hatches as their pattern's lines clipped to the boundary, each cut into its dashes
|
||||
and dots and stroked at the lineweight without the linetype; a pattern hatch with no usable pattern lines, with more
|
||||
than 20,000 dashes, 200,000 boundary edges or 20,000,000 clipping and dash steps, or past the drawing's budget of
|
||||
2,000,000 dashes or 200,000,000 clipping steps, as its boundary),
|
||||
text and multiline text point type, named blocks symbols
|
||||
(one per look when their art takes colour "by block"), anonymous blocks such as dimensions groups. 3D faces, polyface
|
||||
meshes and polygon meshes are seen from above, their height dropped: a 3D face or a polyface mesh's face becomes the
|
||||
lines of its visible edges (closed when every edge is visible), and a polygon mesh one path of its M and N lines
|
||||
(smoothed meshes draw their surface's vertices). Indexed colours
|
||||
(7 is black on paper), true colour, lineweights (`scaleLineweights` scales them with the art), linetypes and
|
||||
transparency resolve through layers and blocks. What is left out (viewports, images, meshes and mesh faces whose
|
||||
vertices are missing, unknown entities) is listed in `warnings`. ASCII and binary DXF files are read.
|
||||
vertices are missing, pattern hatches drawn as their boundaries, unknown entities) is listed in `warnings`. ASCII and binary DXF files are read.
|
||||
|
||||
DWG drawings (by content or the `.dwg` extension) open, place and answer `document.dxfInfo` the same way, with the
|
||||
same `dxf` options, in builds with a DWG decoder (not web builds or FreeBSD on 64-bit ARM): craft-dwg converts the drawing to DXF (acadrust 0.6.6, MPL-2.0) and the DXF reader reads that.
|
||||
|
||||
Reference in new issue
Block a user