diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 5a5582efe1..2f1fd93467 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -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 and solids 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 and solids become paths; text and multiline text +//! point type; named blocks symbols //! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour), //! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve //! them. What can't come in is listed in the warnings. @@ -15,12 +16,14 @@ //! 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. //! - `build`: items to the document. mod build; mod curve; mod entity; +mod hatch; mod reader; mod text; diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 4e1bed4ae1..9ddd1944db 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -8,12 +8,13 @@ use std::rc::Rc; use std::sync::Arc; use kurbo::BezPath; -use vectorcraft_color::{Color, Paint}; +use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect}; use super::ImportOptions; -use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Span, TextItem}; +use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Shade, Span, TextItem}; +use super::hatch::{Grad, Second}; use super::reader::{Drawing, LayoutDef}; use crate::{CAP_HEIGHT, MAX_NEST}; @@ -47,6 +48,19 @@ const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to pl const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; +/// 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)] @@ -291,7 +305,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 { 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; @@ -333,6 +347,10 @@ impl<'d, 'a> Build<'d, 'a> { 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"); + 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); } @@ -391,6 +409,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 { @@ -479,7 +514,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.path(bp, Look::Pattern { dots: *dots }, 0.0, &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), }; @@ -488,7 +525,10 @@ 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 { + /// 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 { + 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); @@ -498,7 +538,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. @@ -515,7 +562,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) { diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index 9d147b08cf..3538920f1d 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -10,6 +10,7 @@ use vectorcraft_geom::{Affine, Point, Vec2}; use craft_dxf::model::{self, EntityRecord, Groups, HatchEdge, HatchPath}; 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. @@ -155,10 +156,25 @@ 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), } +/// How a [`Geom::Shaded`] path paints. +#[derive(Clone, Debug)] +pub(crate) enum Shade { + /// The area filled with a gradient. + Gradient(Box), + /// 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 { @@ -174,10 +190,14 @@ pub(crate) struct Converter { pub warnings: Vec, /// Array insert copies made so far, against [`MAX_TOTAL_CELLS`]. cells: i64, + /// The pattern budget shared by entity sections and blocks. + patterns: hatch::Budget, } -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 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 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"; @@ -247,7 +267,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), @@ -378,7 +398,8 @@ impl Converter { out } - fn hatch(&mut self, h: &model::Hatch, ocs: Affine) -> Option { + /// 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 { let mut bp = BezPath::new(); for l in &h.loops { let Some(path) = boundary(&l.path) else { break }; @@ -387,14 +408,38 @@ impl Converter { 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 }) } } @@ -406,6 +451,10 @@ 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, shade } => { + let far = matches!(shade, Shade::Gradient(g) if !near(g.geom.start) || !near(g.geom.end) || !g.geom.aspect.is_finite()); + !far && 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)), } diff --git a/crates/cad/src/import/hatch.rs b/crates/cad/src/import/hatch.rs new file mode 100644 index 0000000000..506f595ba0 --- /dev/null +++ b/crates/cad/src/import/hatch.rs @@ -0,0 +1,563 @@ +//! 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 the boundary's larger side. +const FLATNESS: f64 = 1e-4; +/// Lengths below this fraction of the boundary's larger side count as none. +const TINY: f64 = 1e-9; + +/// 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 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, +} + +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 { + 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, size * FLATNESS)?; + 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 tiny = size * TINY; + 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 as good as none, fill the area past what can be drawn. + if step.abs() <= tiny { + return Err(NoPattern::TooDense); + } + // The lines crossing the boundary's box: base + k * offset 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 period: f64 = l.dashes.iter().map(|v| v.abs()).sum(); + if !l.dashes.is_empty() && period <= tiny { + 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 + offset * k as f64; + crossings(&edges, q, d, n, &mut t); + for &[ta, tb] in t.as_chunks::<2>().0 { + if tb - ta <= tiny { + 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 base point: the first period that reaches the + // span, element by element. + let mut at = (ta / period).floor() * period; + 'span: loop { + for v in &l.dashes { + if at > tb { + break 'span; + } + budget.work(&mut work, 1)?; + let len = v.abs(); + if *v > 0.0 { + let (s0, s1) = (at.max(ta), (at + len).min(tb)); + if s1 > s0 { + emit(s0, s1, budget)?; + } + } else if *v == 0.0 && at >= ta { + emit(at, at, budget)?; + dots = true; + } + at += len; + } + } + } + } + } + if !usable { + return Err(NoPattern::Undefined); + } + Ok((out, dots)) +} + +/// The boundary's edges as straight segments, each loop closed. +fn edges(boundary: &BezPath, tolerance: f64) -> Result, NoPattern> { + let mut out = Vec::new(); + let (mut start, mut last) = (None::, None::); + 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)); + } + }; + kurbo::flatten(boundary.iter(), tolerance, |el| match el { + PathEl::MoveTo(p) => { + if let (Some(s), Some(l)) = (start, last) { + push(l, s, &mut out); + } + 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) { + 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 { + 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 along the gradient (left). + let dx = c.x - r.center().x; + 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::>(); + 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 + (c.y - r.center().y)); + (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), Point::new(c.x, r.y1), 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::>(); + let first = row(50.0); + // 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(35.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, starts past the boundary at 35. + assert!(p.iter().all(|(_, b)| b.x <= 35.0 + 1e-9), "{p:?}"); + } + + #[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 before any line is clipped or dashed. + 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, "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 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}"); + 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"); + } +} diff --git a/crates/cad/src/import/tests.rs b/crates/cad/src/import/tests.rs index d53694343a..323923a370 100644 --- a/crates/cad/src/import/tests.rs +++ b/crates/cad/src/import/tests.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use kurbo::ParamCurve; 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,175 @@ 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 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); + // 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 hatch_declaring_many_absent_source_handles_parses_quickly() { let base = hatch("1"); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index c20f2ee24c..918f653235 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -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 ``, 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 | +| 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. 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; 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` | diff --git a/docs/mcp.md b/docs/mcp.md index 4de603f5e1..b84778151a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -12867,14 +12867,18 @@ 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; 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, 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: craft-dwg converts the drawing to DXF (acadrust 0.6.6, MPL-2.0) and the DXF reader reads that.