mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:42:44 +00:00
Merge pull request #7501 from dotCooCoo/fix/export-bakes-symbol-art-effects
Export: live effects in symbol art apply in PDF, EPS, print and DXF
This commit is contained in:
@@ -428,7 +428,9 @@ pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
|
||||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||||
return Err("the export region is not finite".into());
|
||||
}
|
||||
let baked = vectorcraft_effects::bake_document(doc);
|
||||
// Symbols' art is placed without clipping, as the scene places it.
|
||||
let baked =
|
||||
vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true });
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
Ok(scene::Scene::new(doc, opts).run())
|
||||
}
|
||||
|
||||
@@ -1410,6 +1410,29 @@ fn a_stained_instance_is_written_in_its_stained_color() {
|
||||
assert!(!colors.is_empty() && colors.iter().all(|c| c.as_deref() == Some("255")), "{colors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_art_effects_are_written_where_they_draw() {
|
||||
// A line and the symbol's line below it, each moved 100 pt right by a Transform effect, start
|
||||
// at the same x.
|
||||
let moved = |mut n: Node| {
|
||||
n.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "distort.transform".into(),
|
||||
params: serde_json::json!({"moveH": 100.0}),
|
||||
visible: true,
|
||||
});
|
||||
n
|
||||
};
|
||||
let mut d = doc_with(|d| {
|
||||
let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
vec![moved(line), Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY })]
|
||||
});
|
||||
let art = path(&mut d, shapes::line((10.0, 40.0).into(), (20.0, 40.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved(art)) });
|
||||
let starts: Vec<f64> = entities(&export(&d, &opts(&d)).unwrap()).iter().map(|e| all(e, 10).into_iter().fold(f64::INFINITY, f64::min)).collect();
|
||||
assert_eq!(starts.len(), 2, "{starts:?}");
|
||||
assert!((starts[0] - starts[1]).abs() < 1e-6, "{starts:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbols_fanning_out_into_empty_symbols_stop_at_the_symbol_budget() {
|
||||
// Five levels of 100 instances of the level below, ending in an empty symbol: 10^10 empty
|
||||
|
||||
@@ -251,6 +251,45 @@ fn undrawable(heights: &Heights, used: Def, depth: usize) -> bool {
|
||||
heights.get(&used).is_some_and(|h| h.is_none_or(|h| depth + h > MAX_DRAWN_DEPTH))
|
||||
}
|
||||
|
||||
/// How deep the art of a document's symbols and patterns draws, to measure objects that use them
|
||||
/// outside the document's layers ([`Self::deepest`]).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DrawnHeights {
|
||||
symbols: HashMap<String, usize>,
|
||||
patterns: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl DrawnHeights {
|
||||
/// The heights of `doc`'s symbols and patterns, as [`Document::too_deep`] counts them: the art
|
||||
/// is 1 deep, and what it uses is counted under it. A symbol or pattern that uses itself, or
|
||||
/// draws deeper than [`MAX_DRAWN_DEPTH`], has none.
|
||||
pub fn of(doc: &Document) -> Self {
|
||||
let mut out = Self::default();
|
||||
for ((pattern, name), h) in heights(doc) {
|
||||
if let Some(h) = h {
|
||||
let map = if pattern { &mut out.patterns } else { &mut out.symbols };
|
||||
map.insert(name.to_string(), h);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The deepest `n`, placed `depth` deep, draws: its own objects and the art of their opacity
|
||||
/// masks, and under the objects the art of the symbols and patterns they use. A use of a
|
||||
/// symbol or pattern without a height ([`Self::of`]) counts as the object alone. `n`'s own
|
||||
/// nesting may pass [`MAX_DEPTH`]. Without recursion.
|
||||
pub fn deepest(&self, n: &Node, depth: usize) -> usize {
|
||||
let mut out = depth;
|
||||
let mut stack = vec![(n, depth)];
|
||||
while let Some((n, d)) = stack.pop() {
|
||||
let used = uses(n).filter_map(|(pattern, name)| if pattern { self.patterns.get(name) } else { self.symbols.get(name) }).max();
|
||||
out = out.max(d + used.copied().unwrap_or(0));
|
||||
stack.extend(n.children().into_iter().flatten().chain(n.extras().mask.as_ref().map(|m| &m.art)).map(|c| (&**c, d + 1)));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Take out of `nodes` (each `depth` deep) the uses `bad` picks (given the depth of the object):
|
||||
/// an instance goes, a pattern paint becomes no paint. Returns whether anything changed. For trees
|
||||
/// within [`MAX_DEPTH`].
|
||||
@@ -623,4 +662,23 @@ mod tests {
|
||||
d.patterns.push(crate::PatternDef::new("q", vec![painted(3, "none")]));
|
||||
assert!(!d.too_deep(None) && !d.limit_depth());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawn_heights_measure_objects_outside_the_layers() {
|
||||
// s0 holds s1 two groups deep, which holds s2, which holds an instance of nothing known:
|
||||
// s2 draws 3 deep, s1 6 and s0 9.
|
||||
let d = symbols(3, 2, "none");
|
||||
let heights = DrawnHeights::of(&d);
|
||||
let on_layer = instance(1, "s0");
|
||||
assert_eq!(heights.deepest(&on_layer, 2), 2 + 9);
|
||||
// An object's own nesting and its mask's art count past MAX_DEPTH.
|
||||
let mut deep = Node::group(NodeId(5), vec![nested(MAX_DEPTH + 10)]);
|
||||
deep.extras_mut().mask = Some(Box::new(OpacityMask::new((*instance(6, "s2")).clone(), true)));
|
||||
assert_eq!(heights.deepest(&deep, 1), 1 + 1 + MAX_DEPTH + 10);
|
||||
let shallow = Node::group(NodeId(5), vec![instance(7, "s1")]);
|
||||
assert_eq!(heights.deepest(&shallow, 100), 101 + 6);
|
||||
// A symbol that holds itself has no height, so its instance counts alone.
|
||||
let looped = DrawnHeights::of(&symbols(2, 1, "s0"));
|
||||
assert_eq!(looped.deepest(&instance(1, "s0"), 2), 2);
|
||||
}
|
||||
}
|
||||
|
||||
+248
-7
@@ -17,7 +17,8 @@
|
||||
//! object of its own, a stroke a path stroked by it alone (brushed strokes their brush art, made by
|
||||
//! the caller).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::color::Paint;
|
||||
@@ -26,7 +27,7 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
|
||||
|
||||
use crate::distort::{transform_move, transform_offsets};
|
||||
use crate::group::{has_own_paint, paints};
|
||||
use crate::reshape::{as_art, clipping_text_outline, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
|
||||
use crate::reshape::{as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
|
||||
use crate::{
|
||||
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
|
||||
has_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, reshape,
|
||||
@@ -114,13 +115,181 @@ thread_local! {
|
||||
/// The objects of symbol art that [`bake_document`] has baked for instances inside the art of
|
||||
/// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`].
|
||||
static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// While [`bake_document_placing_symbols`] bakes: the symbols whose instances become their
|
||||
/// placed art ([`placed_symbol_art`]).
|
||||
static PLACING: std::cell::RefCell<Option<Rc<Placing>>> = const { std::cell::RefCell::new(None) };
|
||||
/// The objects in the baked art of the instances that [`bake_node`] has replaced by their
|
||||
/// placed art for one export ([`placed_symbol_art`]), counted against [`Placing::most_nodes`].
|
||||
static PLACED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// The objects in the baked art of the instances that [`bake_node`] baked for one export and
|
||||
/// then left as they are ([`placed_fits`] refused the art), counted with [`PLACED_NODES`]
|
||||
/// against [`Placing::most_nodes`] before more art is baked. Never given back.
|
||||
static DROPPED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
/// How deep the object [`bake_node`] is baking sits in the tree it returns: a top-level layer
|
||||
/// is 1 deep.
|
||||
static LEVEL: std::cell::Cell<usize> = const { std::cell::Cell::new(1) };
|
||||
/// Whether [`bake_node`] is baking inside an object the export does not write ([`unwritten`]),
|
||||
/// where no instance is placed.
|
||||
static UNWRITTEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// `f` run for an object one level deeper ([`LEVEL`]) than the one being baked.
|
||||
fn one_deeper<T>(f: impl FnOnce() -> T) -> T {
|
||||
LEVEL.with(|c| c.set(c.get() + 1));
|
||||
let out = f();
|
||||
LEVEL.with(|c| c.set(c.get().saturating_sub(1)));
|
||||
out
|
||||
}
|
||||
|
||||
/// The symbols whose instances [`bake_document_placing_symbols`] replaces by their placed art, and
|
||||
/// how that art is placed through 9-slice guides.
|
||||
struct Placing {
|
||||
/// The names of the symbols whose art draws something that baking changes, directly or through
|
||||
/// the instances of other such symbols in it ([`drawn_symbols`]).
|
||||
symbols: HashSet<String>,
|
||||
/// Whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not
|
||||
/// ([`Document::place_symbol_art_unclipped`]).
|
||||
clip_slices: bool,
|
||||
/// Most objects the baked art of all placed instances may hold together:
|
||||
/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] for an export.
|
||||
most_nodes: u64,
|
||||
/// How deep the document's symbols and patterns draw, for the instances and pattern paints
|
||||
/// left in placed art.
|
||||
heights: vectorcraft_doc::depth::DrawnHeights,
|
||||
/// The hidden layers and layers that do not print that the export writes.
|
||||
layers: WrittenLayers,
|
||||
}
|
||||
|
||||
/// The layers an exporter writes besides the shown, printing ones
|
||||
/// ([`bake_document_placing_symbols`]). Template layers are never written.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct WrittenLayers {
|
||||
/// Hidden layers (written turned off, as PDF layers and DXF write them).
|
||||
pub hidden: bool,
|
||||
/// Layers that do not print.
|
||||
pub non_printing: bool,
|
||||
}
|
||||
|
||||
/// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`]
|
||||
/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer
|
||||
/// that does not print when the export leaves those out ([`WrittenLayers`]).
|
||||
fn unwritten(n: &Node) -> bool {
|
||||
PLACING.with(|p| {
|
||||
p.borrow().as_ref().is_some_and(|p| match n.kind {
|
||||
NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden),
|
||||
_ => !n.visible,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Can `baked`, the baked art of a placed instance, take the instance's place [`LEVEL`] deep,
|
||||
/// when the art placed for the export so far holds `spent` objects and the art baked for
|
||||
/// instances left as they are holds `dropped` ([`DROPPED_NODES`])? `Some` with the
|
||||
/// objects placed then, when its objects (opacity masks' art included) fit with those within
|
||||
/// [`Placing::most_nodes`] and nothing in it, the symbols and patterns it uses included, draws
|
||||
/// deeper than [`vectorcraft_doc::depth::MAX_DRAWN_DEPTH`].
|
||||
fn placed_fits(baked: &Node, spent: u64, dropped: u64) -> Option<u64> {
|
||||
PLACING.with(|p| {
|
||||
let p = p.borrow();
|
||||
let p = p.as_ref()?;
|
||||
let spent = spent.saturating_add(baked.count_with_masks() as u64);
|
||||
let deepest = p.heights.deepest(baked, LEVEL.with(|c| c.get()));
|
||||
(spent.saturating_add(dropped) <= p.most_nodes && deepest <= vectorcraft_doc::depth::MAX_DRAWN_DEPTH).then_some(spent)
|
||||
})
|
||||
}
|
||||
|
||||
/// The names of the symbols of `d` whose art needs baking ([`needs_bake`]), and of those whose art
|
||||
/// holds an instance of one of them at any depth.
|
||||
fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
let mut out: HashSet<String> = d.symbols.iter().filter(|s| needs_bake(&s.art)).map(|s| s.name.clone()).collect();
|
||||
if out.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let uses: Vec<(&str, Vec<String>)> = d
|
||||
.symbols
|
||||
.iter()
|
||||
.filter(|s| !out.contains(&s.name))
|
||||
.map(|s| {
|
||||
let mut names = vec![];
|
||||
s.art.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
(s.name.as_str(), names)
|
||||
})
|
||||
.collect();
|
||||
loop {
|
||||
let before = out.len();
|
||||
for (name, names) in &uses {
|
||||
if !out.contains(*name) && names.iter().any(|x| out.contains(x)) {
|
||||
out.insert((*name).to_string());
|
||||
}
|
||||
}
|
||||
if out.len() == before {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n`'s subtree hold an instance of a symbol that [`bake_document_placing_symbols`] replaces
|
||||
/// by its placed art? False outside it, and for objects the export does not write ([`unwritten`]).
|
||||
fn holds_placed_symbol(n: &Node) -> bool {
|
||||
fn walk(n: &Node, symbols: &HashSet<String>) -> bool {
|
||||
!unwritten(n)
|
||||
&& (matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.contains(symbol))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols))))
|
||||
}
|
||||
!UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols)))
|
||||
}
|
||||
|
||||
/// Symbol instance `n`, while [`bake_document_placing_symbols`] bakes and its symbol is one it
|
||||
/// places, as the art it draws: the symbol's art with the instance's own appearance changes and
|
||||
/// its stain ([`vectorcraft_doc::symbol_overrides::instance_art`]), placed by the instance as the exporters
|
||||
/// place it, in a group with the instance's id, name, visibility, transparency, opacity mask,
|
||||
/// raster effects and attributes (its URL among them). The art is placed before its effects are baked, as the canvas draws it, so an
|
||||
/// instance that scales its art does not scale what its effects do. `None` for other objects,
|
||||
/// for instances the export does not write ([`unwritten`], hidden or inside such an object), for
|
||||
/// instances nested [`vectorcraft_doc::depth::MAX_DEPTH`] deep in such art, and when the art
|
||||
/// as placed, before its effects are baked, would already take the art placed for the export,
|
||||
/// with the art baked for instances left as they are ([`DROPPED_NODES`]), past
|
||||
/// [`Placing::most_nodes`]; those instances stay as they are. `Some` with the objects in the art
|
||||
/// as placed, before its effects are baked. [`bake_node`] checks the baked art with
|
||||
/// [`placed_fits`].
|
||||
fn placed_symbol_art(d: &Document, n: &Node) -> Option<(Node, u64)> {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None };
|
||||
let (clip, most_nodes) = PLACING.with(|p| p.borrow().as_ref().filter(|p| p.symbols.contains(symbol)).map(|p| (p.clip_slices, p.most_nodes)))?;
|
||||
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || UNWRITTEN.with(|c| c.get()) || unwritten(n) {
|
||||
return None;
|
||||
}
|
||||
let sym = d.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
|
||||
let most = match d.symbol_slice_map(symbol, *xf) {
|
||||
Some(m) if clip => m.most_placed(&art, d),
|
||||
Some(m) => m.most_placed_unclipped(&art, d),
|
||||
None => art.count_with_masks() as u64,
|
||||
};
|
||||
if PLACED_NODES.with(|c| c.get()).saturating_add(DROPPED_NODES.with(|c| c.get())).saturating_add(most) > most_nodes {
|
||||
return None;
|
||||
}
|
||||
let placed = if clip { d.place_symbol_art(symbol, &art, *xf) } else { d.place_symbol_art_unclipped(symbol, &art, *xf) }?;
|
||||
let mut g = dressed(Node::group(n.id, vec![Arc::new(placed)]), n);
|
||||
g.extras_mut().attrs = n.extras().attrs.clone();
|
||||
Some((g, most))
|
||||
}
|
||||
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged).
|
||||
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// Inside an object the export leaves out, effects are baked but no instance is placed.
|
||||
if !UNWRITTEN.with(|c| c.get()) && unwritten(n) {
|
||||
UNWRITTEN.with(|c| c.set(true));
|
||||
let out = bake_node(d, n);
|
||||
UNWRITTEN.with(|c| c.set(false));
|
||||
return out;
|
||||
}
|
||||
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
|
||||
// A ruler guide draws nothing and stays as it is, last in its layer.
|
||||
if n.is_ruler_guide() || !needs_bake(n) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
if n.is_ruler_guide() || !(needs_bake(n) || holds_placed_symbol(n)) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
|
||||
@@ -181,6 +350,26 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
return Some(baked.unwrap_or(m));
|
||||
}
|
||||
// Symbol instances whose art draws live effects, when the caller asks for them: the art
|
||||
// placed, then baked. When the baked art passes the export's budget, or would draw too deep
|
||||
// where the instance is, it is dropped with the art placed for the instances inside it, and
|
||||
// the instance stays as it is. While the art bakes, its objects before baking are held in
|
||||
// the budget, so the instances inside it are placed only within what is left; art baked and
|
||||
// then dropped still counts against the budget for the instances after it.
|
||||
if let Some((m, most)) = placed_symbol_art(d, n) {
|
||||
let spent = PLACED_NODES.with(|c| c.get());
|
||||
PLACED_NODES.with(|c| c.set(spent.saturating_add(most)));
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() + 1));
|
||||
let baked = bake_node(d, &m);
|
||||
INSTANCE_DEPTH.with(|c| c.set(c.get() - 1));
|
||||
let baked = baked.unwrap_or(m);
|
||||
if let Some(now) = placed_fits(&baked, spent, DROPPED_NODES.with(|c| c.get())) {
|
||||
PLACED_NODES.with(|c| c.set(now));
|
||||
return Some(baked);
|
||||
}
|
||||
PLACED_NODES.with(|c| c.set(spent));
|
||||
DROPPED_NODES.with(|c| c.set(c.get().saturating_add(baked.count_with_masks() as u64)));
|
||||
}
|
||||
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
|
||||
// patterns: each copy an object of its own, so its gradient fits it rather than spanning
|
||||
// every copy and its strokes and patterns can differ from the others'.
|
||||
@@ -214,11 +403,11 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
.enumerate()
|
||||
.map(|(i, c)| match (i < clip).then(|| crate::clip::with_clip_effects_applied(c)).flatten() {
|
||||
Some(a) => {
|
||||
let mut a = bake_node(d, &a).unwrap_or(a);
|
||||
let mut a = one_deeper(|| bake_node(d, &a)).unwrap_or(a);
|
||||
fresh_ids(d, &mut a, &mut std::collections::HashSet::new());
|
||||
Arc::new(a)
|
||||
}
|
||||
None => bake_node(d, c).map(Arc::new).unwrap_or_else(|| c.clone()),
|
||||
None => one_deeper(|| bake_node(d, c)).map(Arc::new).unwrap_or_else(|| c.clone()),
|
||||
})
|
||||
.collect();
|
||||
if let Some(ch) = m.children_mut() {
|
||||
@@ -295,7 +484,7 @@ fn bake_pieces(d: &mut Document, mut m: Node) -> Node {
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let c = Arc::unwrap_or_clone(c);
|
||||
let mut c = bake_node(d, &c).unwrap_or(c);
|
||||
let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c);
|
||||
fresh_ids(d, &mut c, &mut seen);
|
||||
Arc::new(c)
|
||||
})
|
||||
@@ -772,8 +961,60 @@ fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node, outline_strokes:
|
||||
/// resources of its placed documents' art added ([`Document::with_placed_art`]); `None` when
|
||||
/// there is nothing to do (export it as is).
|
||||
pub fn bake_document(doc: &Document) -> Option<Document> {
|
||||
bake(doc, None)
|
||||
}
|
||||
|
||||
/// [`bake_document`], and every symbol instance whose symbol's art draws something baking changes
|
||||
/// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or
|
||||
/// in the art of the symbols it places) replaced by that art as the instance places it, baked
|
||||
/// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For
|
||||
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than
|
||||
/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped
|
||||
/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the
|
||||
/// exporter places other instances. `layers`: the hidden layers and layers that do not print
|
||||
/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden
|
||||
/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The
|
||||
/// symbols' own art is left as it is.
|
||||
pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option<Document> {
|
||||
bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers)))
|
||||
}
|
||||
|
||||
/// Restores what [`bake`] changes in the thread's baking state when it ends.
|
||||
struct Restore(Option<Rc<Placing>>, u64, u64, usize, bool);
|
||||
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
PLACING.with(|p| *p.borrow_mut() = self.0.take());
|
||||
PLACED_NODES.with(|c| c.set(self.1));
|
||||
DROPPED_NODES.with(|c| c.set(self.2));
|
||||
LEVEL.with(|c| c.set(self.3));
|
||||
UNWRITTEN.with(|c| c.set(self.4));
|
||||
}
|
||||
}
|
||||
|
||||
/// [`bake_document`], or with `placing` [`bake_document_placing_symbols`] with that `clip_slices`,
|
||||
/// [`Placing::most_nodes`] and [`Placing::layers`].
|
||||
fn bake(doc: &Document, placing: Option<(bool, u64, WrittenLayers)>) -> Option<Document> {
|
||||
let placed = doc.with_placed_art();
|
||||
if !placed.layers.iter().any(|l| needs_bake(l)) {
|
||||
let placing = placing
|
||||
.map(|(clip_slices, most_nodes, layers)| (drawn_symbols(&placed), clip_slices, most_nodes, layers))
|
||||
.filter(|p| !p.0.is_empty())
|
||||
.map(|(symbols, clip_slices, most_nodes, layers)| Placing {
|
||||
symbols,
|
||||
clip_slices,
|
||||
most_nodes,
|
||||
heights: vectorcraft_doc::depth::DrawnHeights::of(&placed),
|
||||
layers,
|
||||
});
|
||||
// A bake inside another one (of art an effect makes) places symbols only when it asks to.
|
||||
let _restore = Restore(
|
||||
PLACING.with(|p| p.replace(placing.map(Rc::new))),
|
||||
PLACED_NODES.with(|c| c.replace(0)),
|
||||
DROPPED_NODES.with(|c| c.replace(0)),
|
||||
LEVEL.with(|c| c.replace(1)),
|
||||
UNWRITTEN.with(|c| c.replace(false)),
|
||||
);
|
||||
if !placed.layers.iter().any(|l| needs_bake(l) || holds_placed_symbol(l)) {
|
||||
return match placed {
|
||||
std::borrow::Cow::Owned(d) => Some(d),
|
||||
std::borrow::Cow::Borrowed(_) => None,
|
||||
|
||||
@@ -1115,3 +1115,345 @@ fn exporting_a_path_with_a_transform_gives_each_copy_its_own_gradient() {
|
||||
// Three squares of their own, not one path spanning all three.
|
||||
assert_eq!(gradient_pieces(d.node(NodeId(50)).unwrap()), vec![10.0; 3]);
|
||||
}
|
||||
|
||||
/// A 10 × 10 square at (10, 40), with id `id`, that a Transform effect moves 100 pt right.
|
||||
fn moved_square(id: u64) -> Node {
|
||||
let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::default_art());
|
||||
n.appearance.effects.push(fx("distort.transform", json!({"moveH": 100.0})));
|
||||
n
|
||||
}
|
||||
|
||||
fn instance(id: u64, symbol: &str, xf: vectorcraft_geom::Affine) -> Node {
|
||||
Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: symbol.into(), xf })
|
||||
}
|
||||
|
||||
fn add_symbol(d: &mut Document, name: &str, art: Node) {
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
|
||||
}
|
||||
|
||||
fn bounds(d: &Document, id: u64) -> Rect {
|
||||
d.node(NodeId(id)).and_then(|n| n.geometric_bounds()).unwrap_or_else(|| panic!("node {id} has bounds"))
|
||||
}
|
||||
|
||||
fn near_rect(a: Rect, b: Rect) -> bool {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(x, y)| (x - y).abs() < 1e-6)
|
||||
}
|
||||
|
||||
/// Each instance draws its symbol's art with the art's effects applied where the instance places
|
||||
/// it: an instance that doubles the art's size moves it the effect's 100 pt, as the canvas draws
|
||||
/// it, not 200 pt. Plain baking leaves the instances and the symbols' art as they are.
|
||||
#[test]
|
||||
fn placing_symbols_bakes_their_art_where_each_instance_places_it() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "S", Affine::IDENTITY));
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, instance(901, "S", Affine::translate((0.0, 100.0)) * Affine::scale(2.0))).unwrap();
|
||||
add_symbol(&mut d, "S", moved_square(800));
|
||||
assert!(bake_document(&d).is_none(), "nothing in the layers needs baking");
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
assert!(matches!(out.node(NodeId(900)).unwrap().kind, NodeKind::Group { .. }));
|
||||
assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 40.0, 120.0, 50.0)), "{:?}", bounds(&out, 900));
|
||||
assert!(near_rect(bounds(&out, 901), Rect::new(120.0, 180.0, 140.0, 200.0)), "{:?}", bounds(&out, 901));
|
||||
assert_eq!(out.symbols[0].art.appearance.effects.len(), 1, "the symbol's art keeps its effect");
|
||||
}
|
||||
|
||||
/// An instance of a symbol whose art holds an instance of another symbol with effects draws that
|
||||
/// art with its effects too.
|
||||
#[test]
|
||||
fn placing_symbols_reaches_the_art_of_nested_instances() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
|
||||
add_symbol(&mut d, "Inner", moved_square(800));
|
||||
add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(instance(802, "Inner", Affine::translate((0.0, 100.0))))]));
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 140.0, 120.0, 150.0)), "{:?}", bounds(&out, 900));
|
||||
}
|
||||
|
||||
/// A symbol whose art holds an instance of itself is placed until the depth limit, and the export
|
||||
/// ends.
|
||||
#[test]
|
||||
fn placing_a_symbol_that_holds_itself_stops() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "Loop", Affine::IDENTITY));
|
||||
add_symbol(
|
||||
&mut d,
|
||||
"Loop",
|
||||
Node::group(NodeId(801), vec![Arc::new(moved_square(800)), Arc::new(instance(802, "Loop", Affine::translate((0.0, 1.0))))]),
|
||||
);
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
let mut lefts = vec![];
|
||||
out.node(NodeId(900)).unwrap().walk(&mut |n| lefts.extend(n.path_data().and_then(|p| p.bounds()).map(|b| b.x0)));
|
||||
assert!(lefts.len() > 1 && lefts.iter().all(|x| (x - 110.0).abs() < 1e-6), "{lefts:?}");
|
||||
let mut depth = 0;
|
||||
let mut n = out.node(NodeId(900)).unwrap();
|
||||
while let Some(next) = n.children().and_then(|ch| ch.last()) {
|
||||
n = next;
|
||||
depth += 1;
|
||||
}
|
||||
assert!(depth <= 3 * (vectorcraft_doc::depth::MAX_DEPTH + 1), "{depth}");
|
||||
}
|
||||
|
||||
/// A dynamic symbol instance's own paint for an object of the art applies before the object's
|
||||
/// effects are baked: a fill whose own Transform effect makes the square a group of pieces still
|
||||
/// paints in the instance's red, and its sibling keeps the symbol's paint.
|
||||
#[test]
|
||||
fn placing_symbols_keeps_dynamic_instances_changes() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
let mut square = Node::path(NodeId(800), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::default_art());
|
||||
if let Some(AppearanceItem::Fill(f)) = square.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
|
||||
f.effects.push(fx("distort.transform", json!({"moveH": 100.0})));
|
||||
}
|
||||
let sibling = Node::path(NodeId(801), shapes::rectangle(Rect::new(10.0, 60.0, 20.0, 70.0)), Appearance::default_art());
|
||||
let mut inst = instance(900, "D", Affine::IDENTITY);
|
||||
inst.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(red.clone()), ..Default::default() }];
|
||||
let mut d = doc_with(inst);
|
||||
add_symbol(&mut d, "D", Node::group(NodeId(802), vec![Arc::new(square), Arc::new(sibling)]));
|
||||
d.symbols[0].dynamic = true;
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
let mut fills = vec![];
|
||||
out.node(NodeId(900)).unwrap().walk(&mut |n| {
|
||||
if n.path_data().is_some()
|
||||
&& let Some(b) = n.geometric_bounds()
|
||||
{
|
||||
fills.push((b.x0.round(), b.y0.round(), n.appearance.fill_paint()));
|
||||
}
|
||||
});
|
||||
assert!(fills.contains(&(110.0, 40.0, red)), "{fills:?}");
|
||||
assert!(fills.contains(&(10.0, 60.0, Paint::solid(Color::WHITE))), "{fills:?}");
|
||||
}
|
||||
|
||||
/// An instance whose fill stains its symbol's art places the art in its stained colors, with the
|
||||
/// art's effects applied after the stain: a Transform moves the stained square and an Invert
|
||||
/// inverts the stained color.
|
||||
#[test]
|
||||
fn placing_symbols_keeps_the_instances_stain() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let blue = Color::rgb8(30, 90, 220);
|
||||
let mut inst = instance(900, "Mark", Affine::IDENTITY);
|
||||
inst.appearance = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
|
||||
inst.appearance.items.retain(|i| i.is_fill());
|
||||
if let AppearanceItem::Fill(f) = &mut inst.appearance.items[0] {
|
||||
f.opacity = 0.5;
|
||||
}
|
||||
let square =
|
||||
Node::path(NodeId(800), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::basic(Paint::solid(blue), Paint::None, 0.0));
|
||||
let stained = vectorcraft_doc::symbol_overrides::instance_art(&square, &inst).appearance.fill_paint().color().unwrap();
|
||||
assert_ne!(stained.to_hex(), blue.to_hex());
|
||||
let [r, g, b] = stained.to_rgb();
|
||||
let inverted = Color::rgb(1.0 - r, 1.0 - g, 1.0 - b);
|
||||
for (id, params, want) in [("distort.transform", json!({"moveH": 100.0}), stained), (crate::addons::color::INVERT, json!({}), inverted)] {
|
||||
let mut art = square.clone();
|
||||
art.appearance.effects.push(fx(id, params));
|
||||
let mut d = doc_with(inst.clone());
|
||||
add_symbol(&mut d, "Mark", art);
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
assert!(!is_instance(&out, 900), "{id}: the instance is placed");
|
||||
let mut fills = vec![];
|
||||
out.node(NodeId(900)).unwrap().walk(&mut |n| {
|
||||
if n.path_data().is_some() {
|
||||
fills.extend(n.appearance.fill_paint().color().map(|c| c.to_hex()));
|
||||
}
|
||||
});
|
||||
assert_eq!(fills, [want.to_hex()], "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Every layer written, as DXF writes them (template layers are never written).
|
||||
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true };
|
||||
|
||||
fn is_instance(d: &Document, id: u64) -> bool {
|
||||
d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))
|
||||
}
|
||||
|
||||
/// The art placed for an export is counted as baked: the copies an effect makes count, so an
|
||||
/// instance whose baked art passes what is left of the budget stays an instance, and the budget
|
||||
/// holds the baked art of the instances placed, exactly.
|
||||
#[test]
|
||||
fn placing_symbols_counts_the_baked_art() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "S", Affine::IDENTITY));
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, instance(901, "S", Affine::translate((0.0, 100.0)))).unwrap();
|
||||
add_symbol(&mut d, "S", gradient_copies(800));
|
||||
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
|
||||
let each = all.node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64);
|
||||
assert!(each > 2, "the instance's group, and the copies as objects of their own: {each}");
|
||||
assert_eq!(all.node(NodeId(901)).map(|n| n.count_with_masks() as u64), Some(each));
|
||||
let fits = bake(&d, Some((true, 2 * each, ALL))).unwrap();
|
||||
assert!(!is_instance(&fits, 900) && !is_instance(&fits, 901));
|
||||
let short = bake(&d, Some((true, 2 * each - 1, ALL))).unwrap();
|
||||
assert_eq!(usize::from(is_instance(&short, 900)) + usize::from(is_instance(&short, 901)), 1, "one instance stays as it is");
|
||||
}
|
||||
|
||||
/// The baked art of an instance placed inside another's art is counted once: a budget of exactly
|
||||
/// the outer instance's baked art places both.
|
||||
#[test]
|
||||
fn placing_symbols_counts_nested_art_once() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
|
||||
add_symbol(&mut d, "Inner", gradient_copies(800));
|
||||
add_symbol(&mut d, "Outer", Node::group(NodeId(801), vec![Arc::new(instance(802, "Inner", Affine::IDENTITY))]));
|
||||
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
|
||||
let total = all.node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64);
|
||||
let exact = bake(&d, Some((true, total, ALL))).unwrap();
|
||||
assert!(!is_instance(&exact, 900) && !is_instance(&exact, 802), "both are placed within {total}");
|
||||
let short = bake(&d, Some((true, total - 1, ALL))).unwrap();
|
||||
assert!(is_instance(&short, 900), "the outer instance stays as it is");
|
||||
}
|
||||
|
||||
/// While an instance's art bakes, the art's own objects are held in the budget: an instance
|
||||
/// nested in it whose art does not fit in what is left stays as it is, and the outer instance is
|
||||
/// placed around it.
|
||||
#[test]
|
||||
fn placing_symbols_holds_the_outer_art_while_it_bakes() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
|
||||
add_symbol(&mut d, "Inner", Node::group(NodeId(803), vec![Arc::new(gradient_copies(800))]));
|
||||
let mut art: Vec<Arc<Node>> = (0..5)
|
||||
.map(|i| Arc::new(Node::path(NodeId(810 + i), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art())))
|
||||
.collect();
|
||||
art.push(Arc::new(instance(802, "Inner", Affine::IDENTITY)));
|
||||
let outer = Node::group(NodeId(801), art);
|
||||
// The outer instance's group around its art, with the inner instance left as it is.
|
||||
let around = 1 + outer.count_with_masks() as u64;
|
||||
add_symbol(&mut d, "Outer", outer);
|
||||
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
|
||||
let inner = all.node(NodeId(802)).map_or(0, |n| n.count_with_masks() as u64);
|
||||
assert!(inner > 2 && inner <= around, "the inner art alone fits: {inner} <= {around}");
|
||||
let out = bake(&d, Some((true, around, ALL))).unwrap();
|
||||
assert!(!is_instance(&out, 900) && is_instance(&out, 802), "the outer instance is placed around the inner one");
|
||||
}
|
||||
|
||||
/// Art baked for an instance and then left out, because it passes the budget, still counts: an
|
||||
/// instance after it whose art would fit in the budget alone stays as it is, and a budget with
|
||||
/// room for both places both.
|
||||
#[test]
|
||||
fn placing_symbols_counts_the_art_it_drops() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(901, "Small", Affine::IDENTITY));
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, instance(900, "Big", Affine::IDENTITY)).unwrap();
|
||||
add_symbol(&mut d, "Big", gradient_copies(800));
|
||||
add_symbol(&mut d, "Small", moved_square(810));
|
||||
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
|
||||
let count = |id: u64| all.node(NodeId(id)).map_or(0, |n| n.count_with_masks() as u64);
|
||||
let (big, small) = (count(900), count(901));
|
||||
assert!(small < big, "{small} < {big}");
|
||||
let short = bake(&d, Some((true, big - 1, ALL))).unwrap();
|
||||
assert!(is_instance(&short, 900), "the big art passes {}", big - 1);
|
||||
assert!(is_instance(&short, 901), "the big art's {big} objects count, so the small art does not fit");
|
||||
let both = bake(&d, Some((true, big + small, ALL))).unwrap();
|
||||
assert!(!is_instance(&both, 900) && !is_instance(&both, 901));
|
||||
}
|
||||
|
||||
/// Instances the export does not write are not placed and do not count against the budget: with
|
||||
/// room for one instance's baked art, hidden instances, an instance in a hidden group, one on a
|
||||
/// template layer, one on a layer that does not print and one on a hidden layer (when the export
|
||||
/// leaves those layers out) come first and stay as they are, and the visible instance after them
|
||||
/// is placed. An export that writes those layers places their instances first.
|
||||
#[test]
|
||||
fn placing_symbols_skips_instances_the_export_leaves_out() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "S", Affine::IDENTITY));
|
||||
add_symbol(&mut d, "S", gradient_copies(800));
|
||||
let each = bake(&d, Some((true, u64::MAX, ALL))).unwrap().node(NodeId(900)).map_or(0, |n| n.count_with_masks() as u64);
|
||||
let layer = d.layers[0].id;
|
||||
let mut hidden = instance(901, "S", Affine::IDENTITY);
|
||||
hidden.visible = false;
|
||||
let mut group = Node::group(NodeId(902), vec![Arc::new(instance(903, "S", Affine::IDENTITY))]);
|
||||
group.visible = false;
|
||||
for (i, n) in [hidden, group].into_iter().enumerate() {
|
||||
d.insert(Some(layer), i, n).unwrap();
|
||||
}
|
||||
let mut left_out = vec![];
|
||||
for (id, template, printable, visible) in [(910, true, true, true), (920, false, false, true), (930, false, true, false)] {
|
||||
let mut l = Node::layer(NodeId(id), &format!("L{id}"), vectorcraft_doc::LayerColor::Preset(0));
|
||||
if let NodeKind::Layer { template: t, printable: p, .. } = &mut l.kind {
|
||||
*t = template;
|
||||
*p = printable;
|
||||
}
|
||||
l.visible = visible;
|
||||
if let Some(ch) = l.children_mut() {
|
||||
ch.push(Arc::new(instance(id + 1, "S", Affine::IDENTITY)));
|
||||
}
|
||||
left_out.push(Arc::new(l));
|
||||
}
|
||||
d.layers.splice(0..0, left_out);
|
||||
let out = bake(&d, Some((true, each, WrittenLayers::default()))).unwrap();
|
||||
assert!(!is_instance(&out, 900), "the visible instance is placed within {each}");
|
||||
for id in [901, 903, 911, 921, 931] {
|
||||
assert!(is_instance(&out, id), "{id} stays as it is");
|
||||
}
|
||||
// An export that writes the layers that do not print, or the hidden layers, places that
|
||||
// layer's instance first; the template layer's instance is never placed.
|
||||
for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] {
|
||||
let out = bake(&d, Some((true, each, layers))).unwrap();
|
||||
assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `leaf` in `levels` groups, with ids from `id` up.
|
||||
fn in_groups(id: u64, levels: u64, leaf: Node) -> Node {
|
||||
(0..levels).fold(leaf, |n, i| Node::group(NodeId(id + i), vec![Arc::new(n)]))
|
||||
}
|
||||
|
||||
/// Placed art is drawn no deeper than the document may draw: an instance whose art's effects add
|
||||
/// a level past it stays an instance, and the instances around it are placed.
|
||||
#[test]
|
||||
fn placing_symbols_keeps_the_baked_art_within_the_drawn_depth() {
|
||||
use vectorcraft_doc::depth::{DrawnHeights, MAX_DRAWN_DEPTH};
|
||||
use vectorcraft_geom::Affine;
|
||||
// The instance on the layer is 2 deep; A to D each hold the next 31 objects down, and E's
|
||||
// square is 2 deep in its art: 2 + 4 × 31 + 2 = MAX_DRAWN_DEPTH.
|
||||
let mut d = doc_with(instance(900, "A", Affine::IDENTITY));
|
||||
for (i, (name, next)) in [("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")].into_iter().enumerate() {
|
||||
let base = 1000 * (i as u64 + 1);
|
||||
add_symbol(&mut d, name, in_groups(base, 30, instance(base + 100, next, Affine::IDENTITY)));
|
||||
}
|
||||
add_symbol(&mut d, "E", in_groups(5000, 1, gradient_copies(5100)));
|
||||
assert!(!d.too_deep(None));
|
||||
assert_eq!(DrawnHeights::of(&d).deepest(&d.layers[0], 1), MAX_DRAWN_DEPTH);
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
// E's square becomes a group of copies, a level past the cap: E's instance stays.
|
||||
assert!(is_instance(&out, 4100), "E's instance stays as it is");
|
||||
assert!(!is_instance(&out, 900) && !is_instance(&out, 3100), "A to D are placed");
|
||||
assert!(DrawnHeights::of(&out).deepest(&out.layers[0], 1) <= MAX_DRAWN_DEPTH);
|
||||
// Without the chain above it, E's art is placed.
|
||||
let mut shallow = doc_with(instance(900, "E", Affine::IDENTITY));
|
||||
add_symbol(&mut shallow, "E", in_groups(5000, 1, gradient_copies(5100)));
|
||||
assert!(!is_instance(&bake_document_placing_symbols(&shallow, true, ALL).unwrap(), 900));
|
||||
}
|
||||
|
||||
/// Art baked for an instance and then left out because it draws too deep still counts when the
|
||||
/// baked art of a later instance is checked: that art fits before its effects add copies, but
|
||||
/// not once they do.
|
||||
#[test]
|
||||
fn placing_symbols_counts_art_dropped_for_depth_against_later_baked_art() {
|
||||
use vectorcraft_geom::Affine;
|
||||
// The chain of placing_symbols_keeps_the_baked_art_within_the_drawn_depth, then F, whose
|
||||
// square becomes a group of copies once baked.
|
||||
let mut d = doc_with(instance(900, "A", Affine::IDENTITY));
|
||||
for (i, (name, next)) in [("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")].into_iter().enumerate() {
|
||||
let base = 1000 * (i as u64 + 1);
|
||||
add_symbol(&mut d, name, in_groups(base, 30, instance(base + 100, next, Affine::IDENTITY)));
|
||||
}
|
||||
add_symbol(&mut d, "E", in_groups(5000, 1, gradient_copies(5100)));
|
||||
add_symbol(&mut d, "F", gradient_copies(6000));
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 1, instance(901, "F", Affine::IDENTITY)).unwrap();
|
||||
let all = bake(&d, Some((true, u64::MAX, ALL))).unwrap();
|
||||
assert!(is_instance(&all, 4100) && !is_instance(&all, 900) && !is_instance(&all, 901));
|
||||
let count = |d: &Document, id: u64| d.node(NodeId(id)).map_or(0, |n| n.count_with_masks() as u64);
|
||||
let (a, f) = (count(&all, 900), count(&all, 901));
|
||||
// E's baked art, as placed where nothing above it draws deep.
|
||||
let mut shallow = doc_with(instance(4100, "E", Affine::IDENTITY));
|
||||
add_symbol(&mut shallow, "E", in_groups(5000, 1, gradient_copies(5100)));
|
||||
let e = count(&bake(&shallow, Some((true, u64::MAX, ALL))).unwrap(), 4100);
|
||||
assert!(f > 2, "F's copies are objects of their own: {f}");
|
||||
let short = bake(&d, Some((true, a + e + f - 1, ALL))).unwrap();
|
||||
assert!(!is_instance(&short, 900) && is_instance(&short, 4100), "A to D are placed, E is not");
|
||||
assert!(is_instance(&short, 901), "E's dropped {e} objects count, so F's baked {f} do not fit");
|
||||
let room = bake(&d, Some((true, a + e + f, ALL))).unwrap();
|
||||
assert!(!is_instance(&room, 900) && !is_instance(&room, 901));
|
||||
}
|
||||
|
||||
@@ -68,7 +68,10 @@ pub use adjust::{
|
||||
ADJUSTMENTS, CHANNELS, ColorMap, ImageHook, adjust, adjust_in_document, color_map, curve_at, curve_points, has_adjustment, is_adjustment,
|
||||
is_channel,
|
||||
};
|
||||
pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake};
|
||||
pub use bake::{
|
||||
StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf,
|
||||
fresh_ids, needs_bake,
|
||||
};
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent};
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
|
||||
@@ -868,7 +868,7 @@ fn as_art_opts(
|
||||
|
||||
/// `art`, the art made of `n`, with `n`'s name, visibility, transparency, opacity mask and
|
||||
/// remaining (raster) effects.
|
||||
fn dressed(mut art: Node, n: &Node) -> Node {
|
||||
pub(crate) fn dressed(mut art: Node, n: &Node) -> Node {
|
||||
art.name = n.name.clone();
|
||||
art.visible = n.visible;
|
||||
art.opacity = n.opacity;
|
||||
|
||||
@@ -230,7 +230,8 @@ pub fn export(doc: &Document, opts: &EpsOptions, preview: Option<&Raster>, thumb
|
||||
}
|
||||
// Type in the document's composite fonts is drawn in them, whether or not an app has the document open.
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
let baked = vectorcraft_effects::bake_document(doc);
|
||||
let baked =
|
||||
vectorcraft_effects::bake_document_placing_symbols(doc, true, vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true });
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
let page = scene::Scene::new(doc, opts).run();
|
||||
let mut setting_notes = vec![];
|
||||
|
||||
@@ -1654,6 +1654,23 @@ fn an_instance_whose_brush_art_reaches_the_region_is_written() {
|
||||
assert!(page.contains("1 0 0 rg"), "{page}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_art_effects_are_written_where_they_draw() {
|
||||
// The symbol's square at (10, 40), which a Transform effect moves 100 pt right, is drawn from
|
||||
// x = 110 and not from x = 10.
|
||||
let mut d = doc_with(|d| vec![Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY })]);
|
||||
let mut art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
|
||||
art.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "distort.transform".into(),
|
||||
params: serde_json::json!({"moveH": 100.0}),
|
||||
visible: true,
|
||||
});
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) });
|
||||
let page = page_of(&d, &opts(&d));
|
||||
let starts: Vec<f64> = page.lines().filter(|l| l.ends_with(" m")).filter_map(|l| l.split_whitespace().next()?.parse().ok()).collect();
|
||||
assert!(!starts.is_empty() && starts.iter().all(|x| (110.0..=120.0).contains(x)), "{starts:?}\n{page}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn level_preview_and_overprint_ids_read_back() {
|
||||
for l in Level::ALL {
|
||||
|
||||
@@ -45,8 +45,15 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha
|
||||
let set = &opts.settings;
|
||||
set.check()?;
|
||||
vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?;
|
||||
// Live geometry effects export as their result; raster effects are reported below.
|
||||
let baked = vectorcraft_effects::bake_document(doc);
|
||||
// Live geometry effects export as their result, in symbols' art too; raster effects are
|
||||
// reported below.
|
||||
// Only the layers this export writes place their instances' art (see `ex.non_printing` and
|
||||
// `ex.layers` below).
|
||||
let layers = vectorcraft_effects::WrittenLayers {
|
||||
hidden: set.writes_layers() && !doc.page_knockout,
|
||||
non_printing: set.include_non_printing || set.create_layers,
|
||||
};
|
||||
let baked = vectorcraft_effects::bake_document_placing_symbols(doc, true, layers);
|
||||
// Baking stops early when cancelled, leaving a half-baked copy that must not be written.
|
||||
vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?;
|
||||
let doc = baked.as_ref().unwrap_or(doc);
|
||||
|
||||
@@ -183,11 +183,14 @@ pub fn keep_layers(nodes: &mut Vec<Arc<Node>>, which: PrintLayers) {
|
||||
/// only the layers that print, overprints in composite output as [`PrintAdvanced::overprints`]
|
||||
/// says.
|
||||
pub fn printed_document<'a>(doc: &'a Document, set: &PrintSettings) -> Cow<'a, Document> {
|
||||
let mut doc = vectorcraft_effects::bake_document(doc).map_or(Cow::Borrowed(doc), Cow::Owned);
|
||||
let d = doc.to_mut();
|
||||
keep_layers(&mut d.layers, set.print_layers);
|
||||
composite_overprints(d, set);
|
||||
doc
|
||||
// The layers that do not print are left out first, so the art placed for symbols is only
|
||||
// the art that prints; the layers kept are shown.
|
||||
let mut kept = doc.clone();
|
||||
keep_layers(&mut kept.layers, set.print_layers);
|
||||
let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true };
|
||||
let mut d = vectorcraft_effects::bake_document_placing_symbols(&kept, true, layers).unwrap_or(kept);
|
||||
composite_overprints(&mut d, set);
|
||||
Cow::Owned(d)
|
||||
}
|
||||
|
||||
/// Overprinting fills and strokes in composite output: discarded (they knock out) or simulated
|
||||
|
||||
@@ -246,6 +246,26 @@ fn an_instance_whose_brush_art_reaches_the_page_is_written() {
|
||||
assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(-15.0, 30.0, 5.0, 70.0), 0.01), "{:?}", l[0].geometric_bounds());
|
||||
}
|
||||
|
||||
/// The live effects in a symbol's art apply where the instance places the art, as on the canvas:
|
||||
/// the symbol's square at (10, 40), which a Transform effect moves 100 pt right, is written at
|
||||
/// (110, 40).
|
||||
#[test]
|
||||
fn symbol_art_effects_are_written_where_they_draw() {
|
||||
let mut d = doc(200.0, 100.0);
|
||||
let mut square = rect_node(Rect::new(10.0, 40.0, 20.0, 50.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
square.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "distort.transform".into(),
|
||||
params: serde_json::json!({"moveH": 100.0}),
|
||||
visible: true,
|
||||
});
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(square) });
|
||||
add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY }));
|
||||
let out = roundtrip(&d);
|
||||
let l = leaves(&out);
|
||||
assert_eq!(l.len(), 1);
|
||||
assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(110.0, 40.0, 120.0, 50.0), 0.01), "{:?}", l[0].geometric_bounds());
|
||||
}
|
||||
|
||||
/// An instance of a symbol with 9-slice guides, scaled to 200 × 150, is written as the canvas
|
||||
/// draws it: its 10 × 10 corner square stays 10 × 10 and its 10 × 10 center square becomes 30 × 20.
|
||||
#[test]
|
||||
@@ -336,6 +356,31 @@ fn a_stained_instance_keeps_its_stain() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A stained instance of a symbol whose art has a live effect is written in its stained colors,
|
||||
/// where the effect draws the art.
|
||||
#[test]
|
||||
fn a_stained_instance_keeps_its_stain_when_its_art_has_effects() {
|
||||
let blue = Color::rgb8(30, 90, 220);
|
||||
let square = rect_node(Rect::new(10.0, 40.0, 20.0, 50.0), blue);
|
||||
let half = stained_instance("Moved", Affine::IDENTITY, 0.5, true);
|
||||
let want = vectorcraft_brush::instance_art(&square, &half).appearance.fill_paint().color().unwrap().to_hex();
|
||||
assert_ne!(want, blue.to_hex(), "the stain changes the color");
|
||||
let mut art = square;
|
||||
art.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "distort.transform".into(),
|
||||
params: serde_json::json!({"moveH": 100.0}),
|
||||
visible: true,
|
||||
});
|
||||
let mut d = doc(200.0, 100.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) });
|
||||
add(&mut d, half);
|
||||
let out = roundtrip(&d);
|
||||
let l = leaves(&out);
|
||||
assert_eq!(l.len(), 1);
|
||||
assert!(close(l[0].geometric_bounds().unwrap(), Rect::new(110.0, 40.0, 120.0, 50.0), 0.01), "{:?}", l[0].geometric_bounds());
|
||||
assert_eq!(leaf_fills(&out), [want]);
|
||||
}
|
||||
|
||||
/// The placed art of all the 9-slice instances in one export holds at most `MAX_SYMBOL_NODES`
|
||||
/// objects, opacity-mask art included, as on the canvas: of two instances whose art placed through
|
||||
/// the guides holds about 9,009,000 objects each (a gradient square in all nine cells, each copy
|
||||
|
||||
@@ -6,8 +6,8 @@ use std::sync::Arc;
|
||||
use craft_pdf::syntax::Pdf;
|
||||
use craft_pdf::syntax::object::{Array, Dict, Name};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::{Document, Node, NodeId};
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use super::{add, doc, rect_node};
|
||||
use crate::*;
|
||||
@@ -89,6 +89,27 @@ fn hidden_and_unprinted_objects_have_no_links_and_clipping_trims_them() {
|
||||
assert_eq!(links(&export(&d, &PdfOptions::default()).unwrap()), vec![Vec::<(String, [f32; 4])>::new()]);
|
||||
}
|
||||
|
||||
/// A linked symbol instance whose art has a live effect links over the art where the effect draws it.
|
||||
#[test]
|
||||
fn a_linked_instance_keeps_its_link_when_its_art_has_effects() {
|
||||
let mut art = rect_node(Rect::new(10.0, 40.0, 20.0, 50.0), Color::rgb(0.0, 0.0, 1.0));
|
||||
art.appearance.effects.push(vectorcraft_doc::Effect {
|
||||
id: "distort.transform".into(),
|
||||
params: serde_json::json!({"moveH": 100.0}),
|
||||
visible: true,
|
||||
});
|
||||
let mut d = doc(200.0, 100.0);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(art) });
|
||||
let mut instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY });
|
||||
instance.edit_attrs(|a| a.url = "https://example.com/symbol".into());
|
||||
add(&mut d, instance);
|
||||
let pages = links(&export(&d, &PdfOptions::default()).unwrap());
|
||||
let [(uri, rect)] = pages[0].as_slice() else { panic!("one link: {pages:?}") };
|
||||
assert_eq!(uri, "https://example.com/symbol");
|
||||
// x 110…120 after the 100 pt move; y up: 100 − 50 to 100 − 40.
|
||||
assert!(near(*rect, [110.0, 50.0, 120.0, 60.0]), "{rect:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_page_links_its_own_artboard_objects() {
|
||||
let mut d = doc(200.0, 100.0);
|
||||
|
||||
@@ -451,6 +451,29 @@ fn a_symbol_instances_brush_art_keeps_its_artboard_printed() {
|
||||
assert!(p[0].1.iter().any(|(_, paint)| rgb8(paint) == [255, 0, 0]), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_art_effects_print_where_they_draw() {
|
||||
// A red square and the symbol's blue square, each moved 100 pt right by a Transform effect,
|
||||
// print at the same distance from the page's left edge.
|
||||
let moved = |mut n: Node| {
|
||||
n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: json!({"moveH": 100.0}), visible: true });
|
||||
n
|
||||
};
|
||||
let mut d = doc(200.0, 100.0, &[]);
|
||||
let (layer, id) = (d.default_layer().unwrap(), d.alloc_id());
|
||||
let red = Node::path(id, shapes::rectangle(Rect::new(10.0, 10.0, 20.0, 20.0)), Appearance::basic(rgb(1.0, 0.0, 0.0), Paint::None, 0.0));
|
||||
d.insert(Some(layer), 0, moved(red)).unwrap();
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(10.0, 40.0, 20.0, 50.0)), Appearance::basic(rgb(0.0, 0.0, 1.0), Paint::None, 0.0));
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved(art)) });
|
||||
let id = d.alloc_id();
|
||||
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Moved".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
let p = pages(&job(&d, json!({})).bytes);
|
||||
assert_eq!(p.len(), 1);
|
||||
let left = |c: [u8; 3]| p[0].1.iter().find(|(_, paint)| rgb8(paint) == c).map(|(r, _)| r.x0);
|
||||
let (red, blue) = (left([255, 0, 0]), left([0, 0, 255]));
|
||||
assert!(red.zip(blue).is_some_and(|(r, b)| (r - b).abs() < 0.05), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_collate_and_reverse() {
|
||||
let mut d =
|
||||
|
||||
Reference in New Issue
Block a user