Merge main into feat/save-for-web-delete-color

This commit is contained in:
dotCooCoo committed 2026-11-17 16:25:37 -08:00
commit dc30166813
108 files changed
+4091 -464

No files matched your search

Generated
+2
View File
@@ -7108,6 +7108,7 @@ dependencies = [
name = "vectorcraft-text"
version = "0.24.1"
dependencies = [
"craft-proof",
"harfrust 0.13.3",
"icu_segmenter",
"kurbo 0.13.1",
@@ -7116,6 +7117,7 @@ dependencies = [
"subsetter",
"unicode-bidi",
"unicode-general-category",
"unicode-normalization",
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
+2
View File
@@ -11,6 +11,8 @@ workspace = true
[features]
# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only).
spine-count = []
# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only).
symbol-read-count = []
[dependencies]
vectorcraft-geom = { workspace = true }
+3
View File
@@ -75,6 +75,9 @@ pub mod style_libs;
pub mod swatches;
mod symbols;
pub use symbols::SymbolBoxes;
#[cfg(any(test, feature = "symbol-read-count"))]
#[doc(hidden)]
pub use symbols::symbols_read;
pub mod text;
pub mod trace;
pub mod twist;
+83 -8
View File
@@ -9,7 +9,7 @@ use std::sync::Arc;
use vectorcraft_geom::{Affine, Rect};
use crate::symbol_nine_slice::transformed;
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF, Symbol};
/// The box a symbol instance is measured by when its symbol's art has no box
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
@@ -312,7 +312,7 @@ impl Document {
/// Each symbol name of this document → the index of the first symbol of that name (the one a
/// name finds).
pub(crate) fn symbol_names(&self) -> SymbolNames {
#[cfg(test)]
#[cfg(any(test, feature = "symbol-read-count"))]
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
let mut names = HashMap::with_capacity(self.symbols.len());
for (i, s) in self.symbols.iter().enumerate() {
@@ -322,7 +322,7 @@ impl Document {
}
}
#[cfg(test)]
#[cfg(any(test, feature = "symbol-read-count"))]
thread_local! {
/// How many symbols [`Document::symbol_names`] has read on this thread.
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
@@ -330,12 +330,31 @@ thread_local! {
static ART_BOXES_MEASURED: Cell<usize> = const { Cell::new(0) };
}
/// How many symbols [`Document::symbol_names`] has read on this thread, for other crates' tests
/// that count how often the symbol list is read to find symbols by name (the `symbol-read-count`
/// feature, dev-dependencies only).
#[cfg(any(test, feature = "symbol-read-count"))]
#[doc(hidden)]
pub fn symbols_read() -> usize {
SYMBOLS_READ.with(Cell::get)
}
impl<'a> SymbolBoxes<'a> {
/// The document whose symbols these are.
pub fn document(&self) -> &'a Document {
self.doc
}
/// New boxes for the same document, none measured yet and with none of the options set, that
/// find symbols by name through the same index as these boxes ([`Self::symbol`]). Measuring
/// objects one at a time in boxes of their own made this way measures them as boxes made by
/// [`Document::symbol_boxes`] do, without reading the symbol list again.
pub fn unmeasured(&self) -> SymbolBoxes<'a> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
doc.symbol_boxes().with_names(names)
}
/// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the
/// document's symbols while they had the names and order they have now.
pub(crate) fn with_names(self, names: &Arc<SymbolNames>) -> Self {
@@ -343,19 +362,24 @@ impl<'a> SymbolBoxes<'a> {
self
}
/// The art of the first symbol of the document named `name`, found in time independent of the
/// number of symbols after the first lookup.
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
/// The first symbol of the document named `name`, found in time independent of the number of
/// symbols after the first lookup.
pub fn symbol(&self, name: &str) -> Option<&'a Symbol> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
let i = *names.get(name)?;
match doc.symbols.get(i) {
Some(s) if s.name == name => Some(&s.art),
Some(s) if s.name == name => Some(s),
// Names that no longer match the symbols: the first symbol of that name.
_ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art),
_ => doc.symbols.iter().find(|s| s.name == name),
}
}
/// The art of the first symbol of the document named `name` ([`Self::symbol`]).
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
self.symbol(name).map(|s| &s.art)
}
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
/// art box alone. An instance that scales or turns stroked art then measures a little larger
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
@@ -904,6 +928,57 @@ mod tests {
assert_eq!(s.sliced_placed.get(), 13);
}
#[test]
fn symbols_are_found_by_name_reading_the_list_once() {
// 2,000 symbols, then two named "Mark": a name finds the first.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Filler {i}"), vec![r]);
}
let (first, second) = (rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0), rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), 0.0));
symbol(&mut d, "Mark", vec![first]);
symbol(&mut d, "Mark", vec![second]);
let read = || SYMBOLS_READ.with(Cell::get);
let before = read();
let s = d.symbol_boxes();
for _ in 0..1000 {
assert!(s.symbol("Mark").is_some_and(|m| std::ptr::eq(m, &d.symbols[2000])));
assert!(s.symbol("Filler 7").is_some_and(|m| std::ptr::eq(m, &d.symbols[7])));
assert!(s.symbol("Nowhere").is_none());
}
assert_eq!(read() - before, d.symbols.len());
}
#[test]
fn unmeasured_boxes_share_the_index_and_nothing_measured() {
// 2,000 symbols, then a 9-slice frame held, scaled, by "Holder", whose instances spend
// the boxes' budget of placed objects.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Filler {i}"), vec![r]);
}
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
symbol(&mut d, "Panel", vec![frame]);
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
symbol(&mut d, "Holder", vec![wide]);
let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(1.5, 1.5));
let fresh = holder.visual_bounds_with(&d.symbol_boxes().quick());
let read = || SYMBOLS_READ.with(Cell::get);
let s = d.symbol_boxes().quick();
assert_eq!(holder.visual_bounds_with(&s), fresh);
assert!(s.sliced_placed.get() > 0);
let before = read();
let u = s.unmeasured();
assert_eq!(read(), before, "the index is shared");
assert!(u.measured.borrow().is_empty() && u.sliced.borrow().is_empty() && u.reaches.borrow().is_empty());
assert_eq!((u.sliced_placed.get(), u.holders.get(), u.quick.get()), (0, 0, false));
assert_eq!(holder.visual_bounds_with(&u.quick()), fresh);
assert_eq!(read(), before);
}
#[test]
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
+7 -7
View File
@@ -94,13 +94,13 @@ pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE,
ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options,
graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
with_graphic,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES,
ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading,
extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics,
mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art,
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at,
+2 -2
View File
@@ -801,7 +801,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let (paint, opacity, _) = paint_of(item);
let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?;
Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) })
Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity)))
};
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let before = n.appearance.effects.get(..index).unwrap_or_default();
@@ -924,7 +924,7 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::
let Some(item) = surface_item(&s.items) else { continue };
let (paint, opacity, _) = paint_of(item);
let mesh = vectorcraft_three_d::revolve_mesh(&s.path, s.rule, b, options)?;
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity * s.opacity) }, limit)?;
crate::solids::keep_mesh(&mut out, total, crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity * s.opacity)), limit)?;
}
Ok(out)
}
+78 -5
View File
@@ -25,8 +25,8 @@ pub(crate) use source::{resolve, resolve_for};
pub(crate) mod graphics;
pub use graphics::{
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, MeshGraphics, graphic_symbols, mapped_graphics, mesh_graphics_art, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols,
@@ -2322,6 +2322,71 @@ pub struct SolidMesh {
/// The paint's display color (sRGB, 0..1) and its opacity: a gradient's stops averaged, gray
/// for a pattern.
pub color: [f32; 4],
/// The graphics mapped onto the mesh when it is the part of a solid's planar face that carries
/// some ([`split_graphics`]); `None` otherwise.
pub graphics: Option<MeshGraphics>,
}
impl SolidMesh {
/// A mesh painted `color`, with no graphics.
pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self {
Self { mesh, color, graphics: None }
}
}
/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted
/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude &
/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each
/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its
/// mesh, stays plain.
fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec<SolidMesh> {
let list = graphics::mapped_graphics(p);
if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE {
return vec![SolidMesh::plain(mesh, color)];
}
let view = view_options(p);
let mut rest = mesh;
let mut out = vec![];
for face in PlanarFace::ALL {
if !list.iter().any(|g| g.face == face) {
continue;
}
let on_mesh = if id == ROTATE {
vectorcraft_three_d::plane_mesh_face(bounds, view)
} else {
vectorcraft_three_d::extrude_mesh_face(bounds, extrude_options(p), view, face)
};
let Some(on_mesh) = on_mesh else { continue };
let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]);
for t in &rest.triangles {
let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied());
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
let points: Option<Vec<Point>> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect();
let into = match points {
Some(points) => {
art.extend(points);
&mut taken
}
None => &mut left,
};
let base = into.positions.len() as u32;
for (m, n) in corners {
into.positions.push(m);
into.normals.push(n);
}
into.triangles.push([base, base + 1, base + 2]);
}
rest = left;
if !taken.is_empty() {
let graphics = list.iter().filter(|g| g.face == face).cloned().collect();
let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 };
out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) });
}
}
if !rest.is_empty() {
out.insert(0, SolidMesh::plain(rest, color));
}
out
}
/// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]).
@@ -2363,13 +2428,18 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
let p = crate::merged_params(&fx.id, &fx.params);
let view = view_options(&p);
let mut out = vec![];
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit);
// A solid's parts with and without graphics count together against the limit.
let mut keep = |out: &mut Vec<SolidMesh>, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| {
split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity))
.into_iter()
.try_for_each(|part| keep_mesh(out, total, part, limit))
};
if is_plane(&fx.id) {
for s in shapes {
for item in &s.items {
let (paint, opacity, _) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?;
keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?;
}
}
return Ok(out);
@@ -2406,7 +2476,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize)
match solid.mesh() {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *member);
keep(&mut out, mesh, mesh_color(&paint, opacity))?;
keep(&mut out, mesh, (&paint, opacity), bounds)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
@@ -2494,6 +2564,9 @@ fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usi
.filter(|m| !m.mesh.is_empty())
.map(|mut m| {
m.color[3] *= n.opacity.clamp(0.0, 1.0);
if let Some(g) = &mut m.graphics {
g.object *= n.opacity.clamp(0.0, 1.0);
}
m
})
.collect();
+65
View File
@@ -519,6 +519,71 @@ pub(super) fn face_art(
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
}
/// The graphics on one planar face of a solid's mesh ([`super::SolidMesh`]): those mapped onto
/// `face`, placed about `center` (the center of the bounds the solids were built with), and the
/// point of the art's plane that each corner of the mesh shows (document coordinates of the art
/// before its 3D effect, y down).
#[derive(Clone, Debug, PartialEq)]
pub struct MeshGraphics {
pub face: PlanarFace,
pub graphics: Vec<MappedGraphic>,
pub center: Point,
/// One for each position of the mesh.
pub art: Vec<Point>,
/// The opacity of the fill or stroke the face is painted with, which the graphics take too, as
/// the canvas draws them; neither a gradient's stops nor the object's own opacity is in it.
pub opacity: f32,
/// The opacity of the object the face belongs to, which applies to the face and its graphics
/// together.
pub object: f32,
}
impl MeshGraphics {
/// The bounds of the art points of the mesh's corners; `None` without corners.
pub fn art_bounds(&self) -> Option<Rect> {
let first = *self.art.first()?;
Some(self.art.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p)))
}
}
/// The art `graphics` draws on its face, flat in the art's plane, unshaded and unclipped: each
/// graphic's fills and stroke outlines at its place ([`MappedGraphic`]), back to front, as one
/// group of objects with id `id`. A graphic whose symbol `doc` does not have, or whose art is past
/// the limits of [`pieces_of`], is left out, as the canvas leaves it out. `Ok(None)` when nothing
/// is drawn; an error when the graphics' art draws more than [`MAX_ELEMENTS`] path elements
/// together.
pub fn mesh_graphics_art(doc: &Document, id: NodeId, graphics: &MeshGraphics) -> Result<Option<Node>, String> {
let mut children = vec![];
let mut elements = 0usize;
for g in graphics.graphics.iter().filter(|g| g.face == graphics.face) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
let place = g.placement(bounds, graphics.center);
for piece in pieces {
elements = elements.saturating_add(drawn_elements(&piece.path, 1));
if elements > MAX_ELEMENTS {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
let mut paint = piece.paint;
if let Paint::Pattern { xf, .. } = &mut paint {
*xf = place * *xf;
}
let mut fill = FillLayer::new(paint);
fill.opacity = piece.opacity;
fill.blend = piece.blend;
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
appearance.transform_gradients(place);
let mut node = Node::path(id, piece.path.transformed(place), appearance);
if let NodeKind::Path { rule, .. } = &mut node.kind {
*rule = piece.rule;
}
children.push(Arc::new(node));
}
}
Ok((!children.is_empty()).then(|| Node::group(id, children)))
}
/// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces.
struct Unrolled {
polygons: Vec<Vec<Point>>,
@@ -86,6 +86,48 @@ fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
}
#[test]
fn a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane() {
let d = document();
let graphics =
json!([{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}, {"symbol": "Mark", "face": "back", "x": 20.0, "y": -10.0, "scale": 200.0}]);
// Turned, so the caps' corners in the mesh are not the art's.
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0, "graphics": graphics}));
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
// The walls first, then the front cap and the back cap, each two triangles.
assert_eq!(
parts.iter().map(|p| p.graphics.as_ref().map(|g| g.face)).collect::<Vec<_>>(),
[None, Some(PlanarFace::Front), Some(PlanarFace::Back)]
);
let total: usize = parts.iter().map(|p| p.mesh.triangles.len()).sum();
let plain = super::super::three_d_meshes_in(Some(&d), &object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0})));
assert_eq!(total, plain.as_ref().map_or(0, |p| p.iter().map(|p| p.mesh.triangles.len()).sum()), "no triangle is lost or doubled");
assert!(plain.unwrap().iter().all(|p| p.graphics.is_none()));
// The art points of each cap's corners are the art's own square; the graphic is drawn flat at
// its place, mirrored on the back so it reads from behind.
for (part, drawn) in parts[1..].iter().zip([Rect::new(60.0, 30.0, 80.0, 50.0), Rect::new(20.0, 30.0, 40.0, 50.0)]) {
let Some(g) = &part.graphics else { panic!("no graphics") };
assert_eq!(g.art.len(), part.mesh.positions.len());
assert!(close(g.art_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)), "{:?}", g.art_bounds());
assert_eq!(g.graphics.len(), 1);
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
let paths: Vec<(PathData, Paint)> = art
.children()
.into_iter()
.flatten()
.filter_map(|c| Some((c.path_data()?.clone(), c.appearance.items.first()?.paint().clone())))
.collect();
assert!(close(bounds_of(&paths), drawn), "{:?}: {:?}", g.face, bounds_of(&paths));
assert_eq!(paths[0].1, Paint::solid(red()), "unshaded");
}
// A plane is all one face; a graphic whose symbol is gone draws nothing.
let n = object(ROTATE, json!({"rotationY": 35.0, "graphics": [{"symbol": "Gone"}]}));
let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap();
assert_eq!(parts.len(), 1);
let Some(g) = &parts[0].graphics else { panic!("no graphics") };
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
}
#[test]
fn without_the_document_or_its_symbol_nothing_is_drawn() {
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
@@ -563,6 +605,15 @@ fn art_nested_too_deep_is_refused_and_not_drawn() {
// A loaded file draws its other graphics.
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
// A mesh's graphics leave it out as well and draw the others.
let parts = super::super::three_d_meshes_in(Some(&d), &both).unwrap();
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap();
assert_eq!(art.children().map_or(0, |c| c.len()), 1);
let deep = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
let parts = super::super::three_d_meshes_in(Some(&d), &deep).unwrap();
let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") };
assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None));
}
#[test]
+1 -1
View File
@@ -238,7 +238,7 @@ fn meshes_built_apart(fx: &Effect, shapes: &[Profile], total: &mut usize, limit:
match mesh {
Ok(mesh) => {
let (paint, opacity, _) = paint_of(item, *opacity);
keep_mesh(&mut out, total, SolidMesh { mesh, color: mesh_color(&paint, opacity) }, limit)?;
keep_mesh(&mut out, total, SolidMesh::plain(mesh, mesh_color(&paint, opacity)), limit)?;
}
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
+3 -1
View File
@@ -47,6 +47,7 @@ vectorcraft-js = { workspace = true }
vectorcraft-apischema = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
tiff = { workspace = true }
jxl-oxide = { workspace = true }
jxl-color = { workspace = true }
jxl-grid = { workspace = true }
@@ -88,7 +89,6 @@ craft-jxl = { workspace = true }
# vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference
# tests/group3_reference.rs compares it with.
hayro-ccitt = { workspace = true }
tiff = { workspace = true }
craft-stream-codecs = { workspace = true }
vectorcraft-affinity = { workspace = true, features = ["synth"] }
crc32fast = { workspace = true }
@@ -98,6 +98,8 @@ proptest = { workspace = true }
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
# How many times an open reads a PDF.
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
wat = { workspace = true }
# Zstandard streams for the Illustrator editing data fuzz tests.
ruzstd = { workspace = true }
+24 -5
View File
@@ -10,8 +10,8 @@ use vectorcraft_doc::{ExportAsset, NodeId};
use super::edit::{refuse_symbol_part, roots_of, selected_roots};
use super::fileio::{
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files,
safe_file_name, store_screen_settings, with_screen_export_preset, write_file,
DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens,
image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file,
};
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param};
@@ -80,7 +80,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export 3D Assets",
[],
None,
"{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
"{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as <name>-texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets <name>-texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})",
has_doc,
export_3d
),
@@ -299,6 +299,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
}
let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty());
let zip = switch_or(p, "zip", false, C)?;
let size = texture_size_param(p, C)?;
let mut pixels = 0u64;
// Every file's name, compared without case: a later file that would take one gets -2, -3…
let mut taken: HashSet<String> = HashSet::new();
let mut files: Vec<(String, Vec<u8>)> = vec![];
@@ -311,18 +313,20 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
let what = &a.name;
let parts =
vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?;
let images = image_maps(&pictures);
let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into());
let mut stem = base.clone();
let mut k = 1;
loop {
let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?;
let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?;
if names.iter().all(|n| !taken.contains(&n.to_lowercase())) {
break;
}
k += 1;
stem = format!("{base}-{k}");
}
let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?;
let made = mesh_files(&stem, format, &parts, &pictures).map_err(|e| bad(C, e))?;
taken.extend(made.iter().map(|(n, _)| n.to_lowercase()));
files.extend(made);
}
@@ -360,6 +364,21 @@ fn export_3d(s: &mut Session, p: &Value) -> Result<Value> {
}
}
/// Param `textureSize` of command `cmd`: the pixels along the longer side of each face's texture,
/// [`TEXTURE_SIZE`] when it is not given.
fn texture_size_param(p: &Value, cmd: &str) -> Result<u32> {
let key = "textureSize";
let (lo, hi) = TEXTURE_SIZES;
match p.get(key) {
None | Some(Value::Null) => Ok(TEXTURE_SIZE),
Some(v) => v
.as_u64()
.and_then(|n| u32::try_from(n).ok())
.filter(|n| (lo..=hi).contains(n))
.ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of pixels from {lo} to {hi}"))),
}
}
/// The asset ids of param `key`.
fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result<Vec<u64>> {
let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?;
+2 -1
View File
@@ -38,6 +38,7 @@ mod shape_builder;
mod trace;
pub use live_paint::live_paint_gaps;
pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation};
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
use shape_builder::{sb_merge, sb_regions};
pub(crate) use trace::TracePresetChanges;
@@ -144,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Image Trace"],
None,
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
has_selection_or_ids,
|s, p| trace_make(s, p, false)
),
+72 -11
View File
@@ -1,8 +1,8 @@
use super::{
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
source_nodes, source_shapes, switch_or,
PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json,
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
switch_or,
};
/// `options` as stored on a Live Paint group: none for the defaults.
@@ -53,6 +53,27 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result<
Ok((gid, nf, ne))
}
/// The children of Live Paint group `g` besides its sources group ([`b::sources`]) and its faces and
/// edges (paths named [`FACE_NAME`] or [`EDGE_NAME`]), back to front: objects drawn in it in
/// isolation mode. A group or other object named like a part is one of them.
fn others_in(g: &Node) -> impl Iterator<Item = &Arc<Node>> {
let src = b::sources(g).map(|s| s.id);
g.children()
.into_iter()
.flatten()
.filter(move |c| Some(c.id) != src && !(c.path_data().is_some() && matches!(c.name.as_deref(), Some(FACE_NAME | EDGE_NAME))))
}
/// Make `parts` (a sources group, faces and edges made again) the children of Live Paint group `g`,
/// with its other children ([`others_in`]) that are not among `gone` kept in front of them, in their
/// order.
fn set_parts(g: &mut Node, mut parts: Vec<Arc<Node>>, gone: &[NodeId]) {
parts.extend(others_in(g).filter(|c| !gone.contains(&c.id)).cloned());
if let Some(ch) = g.children_mut() {
*ch = parts;
}
}
/// Select `ids` alone, without an undo step, when they are not selected that way already.
fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> {
let st = s.doc()?;
@@ -134,9 +155,15 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
let old_parts = old.clone();
let mut sources = source_nodes(&old);
// The objects drawn in the other Live Paint groups besides their parts stay in the merged group.
let mut others = vec![];
for r in roots {
if *r != target {
sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?));
let n = d.node(*r).ok_or(EngineError::NoNode(*r))?;
sources.extend(source_nodes(n));
if is_live_paint(n) {
others.extend(others_in(n).cloned());
}
}
}
// Merge applies the Gap Options' merge rules to the groups' options, bottom-most first.
@@ -146,8 +173,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
// The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic
// style link and the rest; its children are made again and its Gap Options set to the merged ones.
let mut g = old;
set_parts(&mut g, children, roots);
if let Some(ch) = g.children_mut() {
*ch = children;
ch.extend(others);
}
g.extras_mut().live_paint_gaps = stored_gap_options(options);
for (pt, carried) in keep_faces {
@@ -199,6 +227,38 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
}
/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost
/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint
/// group and then isolated itself. None when `isolated` is not in a Live Paint group.
pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option<NodeId> {
d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint))
}
/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes
/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to
/// front: the paths drawn in it in isolation mode.
fn drawn_in(g: &Node) -> Vec<NodeId> {
fn open(n: &Node) -> bool {
n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c)))
}
others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect()
}
/// Leaving isolation mode in Live Paint group `g` adds the paths drawn in it to the group as
/// `livePaint.merge` does, in one "Merge Live Paint" undo step; → whether any were added. Type,
/// images, other objects Live Paint does not take, and hidden or locked objects stay where they
/// are. With nothing to add, or when `g` is not a Live Paint group, nothing changes and no undo
/// step is recorded.
pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result<bool> {
let drawn = s.doc()?.doc.node(g).filter(|n| is_live_paint(n)).map(drawn_in).unwrap_or_default();
if drawn.is_empty() {
return Ok(false);
}
let roots: Vec<NodeId> = std::iter::once(g).chain(drawn).collect();
s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?;
Ok(true)
}
fn live_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let d = &s.doc()?.doc;
let ids = root_ids(s, p)?;
@@ -216,7 +276,8 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result<Value> {
let mut released = Beside::replacing(d, &targets);
for g in &targets {
let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?;
let srcs: Vec<Node> = source_nodes(&n).iter().map(|c| (**c).clone()).collect();
// The objects drawn in the group besides its parts are released in front of its paths.
let srcs: Vec<Node> = source_nodes(&n).iter().chain(others_in(&n)).map(|c| (**c).clone()).collect();
out.extend(srcs.iter().map(|c| c.id));
released.put(d, *g, srcs)?;
}
@@ -245,10 +306,12 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result<Value> {
e.trace = None;
e.live_paint_gaps = None;
}
// Objects drawn in the group ([`others_in`]) stay, whatever they are named.
let src = b::sources(n).map(|c| c.id);
if let Some(ch) = n.children_mut() {
ch.retain(|c| match c.name.as_deref() {
Some(SOURCES_NAME) => false,
Some(FACE_NAME | EDGE_NAME) => draws(c),
_ if Some(c.id) == src => false,
Some(FACE_NAME | EDGE_NAME) if c.path_data().is_some() => draws(c),
_ => true,
});
}
@@ -354,9 +417,7 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
// The faces change only with what paint stops at, or with new paths.
if added > 0 || options.max_gap() != old.gap_options().max_gap() {
let (children, _, _) = build_children(d, sources, options.max_gap())?;
if let Some(ch) = n.children_mut() {
*ch = children;
}
set_parts(&mut n, children, &[]);
repaint_from(&mut n, &old);
}
n.extras_mut().live_paint_gaps = stored_gap_options(options);
+1 -1
View File
@@ -209,7 +209,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Load Metafile into Clipboard",
[],
None,
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; then run edit.paste",
"{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning; then run edit.paste",
has_doc,
import_emf
),
+5 -3
View File
@@ -39,7 +39,7 @@ pub mod jxlread;
mod legacy_ai;
mod load;
mod mesh3d;
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note};
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note};
mod heifread;
mod hpgl;
mod jp2read;
@@ -87,8 +87,10 @@ pub use load::{
};
pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source};
pub use load::{losses_summary, overwrite_losses};
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label};
pub(crate) use mesh3d::{mesh_file_names, mesh_files};
#[cfg(test)]
pub(crate) use mesh3d::MAX_TEXTURE_PIXELS;
pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, draws_textures, format_3d_label};
pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_maps, mesh_file_names, mesh_files, textures};
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
pub(crate) use native::preview_png;
pub use native::with_compression_pref;
+1 -1
View File
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.<id>\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG Line truncated
always,
load::open
),
+6 -11
View File
@@ -211,17 +211,11 @@ fn selected_part(n: &Arc<Node>, keep: &HashSet<NodeId>, holders: &HashSet<NodeId
/// its own art, not a whole document of artboards. `renderer` measures the 3D art, and keeps it for
/// the next artboard of the same document.
pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Document {
fn kept(
n: &Arc<Node>,
doc: &Document,
symbols: &SymbolBoxes,
rect: vectorcraft_geom::Rect,
renderer: &mut vectorcraft_render::Renderer,
) -> Option<Arc<Node>> {
fn kept(n: &Arc<Node>, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option<Arc<Node>> {
if matches!(n.kind, NodeKind::Layer { clip: false, .. }) {
let mut layer = Node::clone(n);
let children = layer.children_mut()?;
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
return Some(Arc::new(layer));
}
// A group that doesn't clip keeps only its members over the artboard, so art gathered in one
@@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: &
if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() {
let mut group = Node::clone(n);
let children = group.children_mut()?;
*children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect();
*children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect();
return (!children.is_empty()).then(|| Arc::new(group));
}
let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1;
let mut holds_instance = false;
n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. }));
let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over);
// Measured in boxes of its own, which find symbols through the same index.
let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over);
let reach = vectorcraft_brush::reach_within(n);
let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b });
(n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone())
}
let symbols = doc.symbol_boxes().with_brush_art();
let mut d = doc.clone();
d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect();
d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect();
d
}
+44 -6
View File
@@ -60,8 +60,7 @@ impl Loaded {
}
}
/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG
/// (what browsers, PDF and SVG viewers show).
/// An image ready to embed. CMYK images use JPEG or TIFF; other images use browser-readable formats.
#[derive(Clone)]
pub struct RasterImage {
/// Content key for `Document::images` (identical files share one blob).
@@ -937,8 +936,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
/// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color
/// settings' CMYK, whichever of their extra channels is the alpha
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose
/// merged image is read ([`psdread`]).
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]). Opaque CMYK PSD/PSB merged images retain
/// 8- or 16-bit inks and their CMYK ICC profile as TIFF, within the native CMYK pixel and allocation limits;
/// other CMYK composites use the RGBA decoder's allocation limit ([`psdread`]).
/// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
@@ -961,14 +961,27 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
/// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK
/// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as
/// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in;
/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file
/// names ([`png_with_clip`]).
/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported
/// clipping path ([`image_clip`]).
pub fn raster_image(bytes: &[u8]) -> Result<RasterImage> {
let ppi = super::ppi::resolution(bytes);
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
return Err(err(format!("an image of {w} × {h} pixels is too large to draw")));
}
if psdread::is_psd(bytes) {
if let Some(mut native) = psdread::decode_cmyk(bytes, MAX_RASTER_ALLOC).map_err(err)? {
native.meta.dpi = ppi.map(|(x, y)| (x as f32, y as f32));
let clip = psdread::clipping_path(bytes).and_then(|path| {
let json = serde_json::to_string(&path).ok().filter(|j| j.len() <= MAX_PNG_CLIP)?;
native.meta.text.push(("Description".into(), format!("{CLIP_KEYWORD}\n{json}")));
Some((path, vectorcraft_geom::FillRule::EvenOdd))
});
let data =
craft_image_codecs::encode(&native, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()).map_err(err)?;
let mut img = stored(data, "image/tiff", native.dimensions(), ppi)?;
img.clip = clip;
return Ok(img);
}
let cms = vectorcraft_color::cms::active();
let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?;
return Ok(png_with_clip(img, psdread::clipping_path(bytes)));
@@ -1173,6 +1186,31 @@ pub(crate) fn png_clip(png: &[u8]) -> Option<vectorcraft_geom::PathData> {
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
}
/// The imported clipping-path marker in a stored PNG or CMYK TIFF, within the path budget.
pub(crate) fn image_clip(blob: &ImageBlob) -> Option<vectorcraft_geom::PathData> {
if blob.mime == "image/png" {
return png_clip(&blob.bytes);
}
if blob.mime != "image/tiff" {
return None;
}
use tiff::tags::{Tag, Type, ValueBuffer};
let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(blob.bytes.as_slice())).ok()?;
let mut ifd = d.image_ifd();
let entry = ifd.find_entry(Tag::ImageDescription)?;
if entry.field_type() != Type::ASCII || entry.count() > (MAX_PNG_CLIP + CLIP_KEYWORD.len() + 2) as u64 {
return None;
}
let mut buf = ValueBuffer::empty(Type::ASCII);
ifd.find_tag_buf(Tag::ImageDescription, &mut buf).ok()??;
let json = buf.as_bytes().strip_prefix(CLIP_KEYWORD.as_bytes())?.strip_prefix(b"\n")?;
let json = json.strip_suffix(b"\0").unwrap_or(json);
if json.len() > MAX_PNG_CLIP {
return None;
}
vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok())
}
/// An image as a document of its physical size at the resolution it declares (as Place sizes it;
/// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file.
pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
+378 -47
View File
@@ -9,13 +9,24 @@
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
//! an open solid or a turned plane is seen from both sides.
//!
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it
//! after the layer, and OBJ and USDA name PNG files written beside them (`<name>-texture-1.png`…).
//!
//! Formats: glTF 2.0 <https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html>, USD
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>).
//! <https://openusd.org/release/index.html> (USDZ: <https://openusd.org/release/spec_usdz.html>;
//! textures: <https://openusd.org/release/spec_usdpreviewsurface.html>), OBJ and MTL
//! <https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>.
use std::fmt::Write as _;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_render::effects::SolidMesh;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_render::effects::{MeshGraphics, SolidMesh};
/// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default.
pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
@@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"];
pub const DEFAULT_FORMAT_3D: &str = "usda";
/// The meters in a point (1/72 inch).
const METERS_PER_POINT: f64 = 0.0254 / 72.0;
/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another
/// size, and the sizes it takes.
pub(crate) const TEXTURE_SIZE: u32 = 1024;
pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096);
/// The most texture pixels one export draws, all its assets together.
pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096;
/// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`.
pub fn format_3d_label(format: &str) -> &'static str {
@@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String {
stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect()
}
/// The names of the files [`mesh_files`] writes for `stem` in `format`.
pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, String> {
/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`,
/// so an MTL `map_Kd` line and a USD asset path name it as one word.
fn texture_name(stem: &str, k: usize) -> String {
format!("{}-texture-{}.png", texture_stem(stem), k + 1)
}
/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as
/// [`texture_name`] names the texture.
fn opacity_name(stem: &str, k: usize) -> String {
format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1)
}
/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures.
fn texture_stem(stem: &str) -> String {
stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect()
}
/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images`
/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each
/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold
/// theirs.
pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result<Vec<String>, String> {
let beside = |mut names: Vec<String>, stem: &str, maps: bool| {
for (k, map) in images.iter().enumerate() {
names.push(texture_name(stem, k));
if maps && *map {
names.push(opacity_name(stem, k));
}
}
names
};
match format {
"obj" => {
let stem = obj_stem(stem);
Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")])
Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true))
}
"gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
"usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)),
"gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]),
_ => {
let key = "format";
Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", ")))
@@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result<Vec<String>, S
}
}
/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the
/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the
/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Texture {
pub png: Arc<Vec<u8>>,
pub opacity: Option<Arc<Vec<u8>>>,
pub uv: Vec<[f64; 2]>,
}
/// A distinct picture of a 3D object: the PNG and its opacity map.
type Picture = (Arc<Vec<u8>>, Option<Arc<Vec<u8>>>);
/// The distinct pictures of `textures` in order of first use, and the index among them of each
/// part's (`None` for a part without one).
fn images(parts: usize, textures: &[Option<Texture>]) -> (Vec<Picture>, Vec<Option<usize>>) {
let mut out: Vec<Picture> = vec![];
let index = (0..parts)
.map(|k| {
let t = textures.get(k)?.as_ref()?;
Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| {
out.push((t.png.clone(), t.opacity.clone()));
out.len() - 1
}))
})
.collect();
(out, index)
}
/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]).
pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect()
}
/// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the
/// OBJ with its MTL after it.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
let names = mesh_file_names(stem, format)?;
let bytes = match format {
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
let (images, image) = images(parts.len(), textures);
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
let names = mesh_file_names(stem, format, &maps)?;
let pictures: Vec<Arc<Vec<u8>>> = images.iter().map(|(p, _)| p.clone()).collect();
let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps };
let pngs = || pictures.iter().map(|p| p.as_ref().clone());
let bytes: Vec<Vec<u8>> = match format {
"obj" => {
let (obj, mtl) = obj(&obj_stem(stem), parts);
vec![obj.into_bytes(), mtl.into_bytes()]
let stem = obj_stem(stem);
let (obj, mtl) = obj(&stem, &scene);
let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone())));
[obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect()
}
"gltf" => vec![gltf(stem, &scene).into_bytes()],
"usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(),
_ => {
let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())];
members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png)));
vec![super::zip::store_aligned(&members, 64)?]
}
"gltf" => vec![gltf(stem, parts).into_bytes()],
"usda" => vec![usda(stem, parts).into_bytes()],
_ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?],
};
Ok(names.into_iter().zip(bytes).collect())
}
/// The distinct colors of `parts` in order, and each part's index among them.
fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec<usize>) {
let mut colors: Vec<[f32; 4]> = vec![];
let index = parts
/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and
/// `maps` says for each picture whether it has an opacity map.
struct Scene<'a> {
parts: &'a [SolidMesh],
textures: &'a [Option<Texture>],
image: &'a [Option<usize>],
pictures: &'a [Arc<Vec<u8>>],
maps: &'a [bool],
}
impl Scene<'_> {
/// Part `k`'s texture coordinates and picture, when it has a picture.
fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> {
let t = self.textures.get(k)?.as_ref()?;
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
}
}
/// A material: a color, with a picture that replaces its red, green and blue.
#[derive(Clone, Copy, PartialEq)]
struct Material {
color: [f32; 4],
image: Option<usize>,
}
/// The distinct materials of `scene`'s parts in order, and each part's index among them.
fn materials(scene: &Scene) -> (Vec<Material>, Vec<usize>) {
let mut out: Vec<Material> = vec![];
let index = scene
.parts
.iter()
.map(|p| {
colors.iter().position(|c| *c == p.color).unwrap_or_else(|| {
colors.push(p.color);
colors.len() - 1
.enumerate()
.map(|(k, p)| {
let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) };
out.iter().position(|c| *c == m).unwrap_or_else(|| {
out.push(m);
out.len() - 1
})
})
.collect();
(colors, index)
(out, index)
}
/// An sRGB channel (0..1) as linear light.
@@ -96,8 +217,9 @@ fn num(v: f64) -> String {
format!("{v}")
}
fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
let (colors, material) = materials(parts);
fn obj(stem: &str, scene: &Scene) -> (String, String) {
let parts = scene.parts;
let (materials, material) = materials(scene);
let mut o = String::new();
let _ = writeln!(o, "mtllib {stem}.mtl");
let _ = writeln!(o, "o {stem}");
@@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) {
let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2]));
}
}
// OBJ's texture coordinates run up from the picture's bottom.
for k in 0..parts.len() {
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
}
}
for p in parts {
for n in &p.mesh.normals {
let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2]));
}
}
let mut base = 1usize;
let (mut base, mut uv_base) = (1usize, 1usize);
for (k, p) in parts.iter().enumerate() {
let _ = writeln!(o, "g Solid_{}", k + 1);
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
for t in &p.mesh.triangles {
let [a, b, c] = t.map(|i| i as usize + base);
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
if textured {
let [a, b, c] = t.map(|i| i as usize);
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
} else {
let [a, b, c] = t.map(|i| i as usize + base);
let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}");
}
}
base += p.mesh.positions.len();
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
}
let mut m = String::new();
for (k, c) in colors.iter().enumerate() {
for (k, mat) in materials.iter().enumerate() {
let c = mat.color;
let _ = writeln!(m, "newmtl Material_{}", k + 1);
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
let _ = writeln!(m, "d {}", num(f64::from(c[3])));
match mat.image {
// The picture holds the color; Kd multiplies it.
Some(_) => {
let _ = writeln!(m, "Kd 1 1 1");
}
None => {
let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2])));
}
}
// A picture's opacity map holds the opacity, as gray levels.
let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) });
let _ = writeln!(m, "illum 1");
if let Some(i) = mat.image {
let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i));
if scene.maps.get(i).copied().unwrap_or(false) {
let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i));
}
}
}
(o, m)
}
fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
let (colors, material) = materials(parts);
fn gltf(stem: &str, scene: &Scene) -> String {
let parts = scene.parts;
let (materials, material) = materials(scene);
let mut buffer: Vec<u8> = vec![];
let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]);
let mut view = |buffer: &mut Vec<u8>, bytes: Vec<u8>, target: u32| -> usize {
@@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
}));
accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" }));
accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" }));
primitives.push(json!({
let mut primitive = json!({
"attributes": { "POSITION": at, "NORMAL": at + 1 },
"indices": at + 2,
"material": material.get(k).copied().unwrap_or(0),
}));
});
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
let coords = view(&mut buffer, bytes, 34962);
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" }));
}
primitives.push(primitive);
}
let materials: Vec<Value> = colors
let materials: Vec<Value> = materials
.iter()
.enumerate()
.map(|(k, c)| {
.map(|(k, mat)| {
let c = mat.color;
let mut m = json!({
"name": format!("Material_{}", k + 1),
"pbrMetallicRoughness": {
@@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
},
"doubleSided": true,
});
if let Some(i) = mat.image {
// The picture holds the color and the opacity; the factor multiplies them.
m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]);
m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i });
}
if c[3] < 1.0 {
m["alphaMode"] = json!("BLEND");
}
m
})
.collect();
let doc = json!({
let mut doc = json!({
"asset": { "version": "2.0", "generator": "VectorCraft" },
"scene": 0,
"scenes": [{ "nodes": [0] }],
@@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String {
"bufferViews": views,
"accessors": accessors,
});
if !scene.pictures.is_empty() {
// Linear filtering, mipmaps, and coordinates held at the picture's edge.
doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]);
doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect());
doc["images"] = Value::Array(
scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(),
);
}
serde_json::to_string_pretty(&doc).unwrap_or_default()
}
@@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String {
out
}
fn usda(stem: &str, parts: &[SolidMesh]) -> String {
let (colors, material) = materials(parts);
fn usda(stem: &str, scene: &Scene) -> String {
let parts = scene.parts;
let (materials, material) = materials(scene);
let root = prim_name(stem);
let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2]));
let list = |items: Vec<String>| items.join(", ");
@@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String {
linear(c[2])
);
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
// USD's texture coordinates run up from the picture's bottom.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
}
let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n");
}
let _ = writeln!(u, " def Scope \"Materials\"\n {{");
for (k, c) in colors.iter().enumerate() {
let m = k + 1;
for (k, mat) in materials.iter().enumerate() {
let (m, c) = (k + 1, mat.color);
let at = format!("/{root}/Materials/Material_{m}");
let _ = writeln!(u, " def Material \"Material_{m}\"\n {{");
let _ = writeln!(u, " token outputs:surface.connect = </{root}/Materials/Material_{m}/Surface.outputs:surface>\n");
let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n");
let _ = writeln!(u, " def Shader \"Surface\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\"");
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
match mat.image {
// The picture holds the color, and the opacity when the face is not opaque.
Some(_) => {
let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>");
if c[3] < 1.0 {
let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>");
} else {
let _ = writeln!(u, " float inputs:opacity = 1");
}
}
None => {
let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2]));
let _ = writeln!(u, " float inputs:opacity = {}", c[3]);
}
}
let _ = writeln!(u, " float inputs:roughness = 1");
let _ = writeln!(u, " token outputs:surface\n }}\n }}");
let _ = writeln!(u, " token outputs:surface\n }}");
if let Some(i) = mat.image {
let _ = writeln!(u, "\n def Shader \"Texture\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\"");
let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i));
let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>");
let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\"");
let _ = writeln!(u, " token inputs:wrapS = \"clamp\"");
let _ = writeln!(u, " token inputs:wrapT = \"clamp\"");
let _ = writeln!(u, " float3 outputs:rgb");
if c[3] < 1.0 {
let _ = writeln!(u, " float outputs:a");
}
let _ = writeln!(u, " }}");
let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{");
let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\"");
let _ = writeln!(u, " string inputs:varname = \"st\"");
let _ = writeln!(u, " float2 outputs:result\n }}");
}
let _ = writeln!(u, " }}");
}
let _ = writeln!(u, " }}\n}}");
u
}
/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order
/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its
/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]),
/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with
/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so
/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`].
pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result<Vec<Option<Texture>>, String> {
let mut renderer: Option<vectorcraft_render::Renderer> = None;
// Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map
// (`None`: nothing drawn).
let mut drawn: Vec<Drawn> = vec![];
let mut out = vec![];
for part in parts {
let Some(g) = &part.graphics else {
out.push(None);
continue;
};
let Some(frame) = texture_frame(g) else {
out.push(None);
continue;
};
let scale = f64::from(size) / frame.width().max(frame.height());
let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size);
let (w, h) = (fit(frame.width()), fit(frame.height()));
let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g));
let png = match drawn.iter().find(same) {
Some((_, _, png)) => png.clone(),
None => {
let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? {
None => None,
Some(art) => {
*pixels = pixels.saturating_add(u64::from(w) * u64::from(h));
if *pixels > MAX_TEXTURE_PIXELS {
return Err(format!(
"the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})"
));
}
let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new);
Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?)
}
};
drawn.push((part, frame, png.clone()));
png
}
};
out.push(png.map(|(png, opacity)| {
let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect();
Texture { png, opacity, uv }
}));
}
Ok(out)
}
/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an
/// area and whose graphics draw something? Nothing is rendered.
pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool {
parts.iter().any(|p| {
p.graphics
.as_ref()
.is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_))))
})
}
/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when
/// they span an area.
fn texture_frame(g: &MeshGraphics) -> Option<Rect> {
g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite())
}
/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map.
type Drawn<'a> = (&'a SolidMesh, Rect, Option<Picture>);
/// Do `a` and `b` draw the same graphics on their face?
fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool {
a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object
}
/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at
/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on
/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at
/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole
/// picture.
fn picture(
doc: &Document,
renderer: &mut vectorcraft_render::Renderer,
(color, face, object): ([f32; 4], f32, f32),
mut art: Node,
(frame, scale): (Rect, f64),
(w, h): (u32, u32),
) -> Result<Picture, String> {
// The color reaches two pixels past the frame, so the picture's edge pixels are covered.
let reach = 2.0 / scale;
let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach);
let fill = Paint::solid(Color::rgb(color[0], color[1], color[2]));
let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0));
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let object = unit(object);
ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 };
art.opacity *= unit(face);
let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]);
group.opacity = object;
let group = Arc::new(group);
let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?);
let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0));
let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?;
let alpha: Vec<u8> = drawn.pixels.iter().skip(3).step_by(4).copied().collect();
let opacity = if alpha.iter().all(|a| *a == 255) {
None
} else {
let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?;
let mut png = vec![];
gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?;
Some(Arc::new(png))
};
Ok((Arc::new(drawn.to_png()?), opacity))
}
#[cfg(test)]
mod tests;
+133 -14
View File
@@ -7,7 +7,7 @@ use super::*;
fn square(color: [f32; 4]) -> SolidMesh {
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
SolidMesh { mesh, color }
SolidMesh::plain(mesh, color)
}
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
@@ -18,9 +18,14 @@ fn text(files: &[(String, Vec<u8>)], name: &str) -> String {
String::from_utf8(bytes.clone()).unwrap()
}
/// [`mesh_files`] without textures.
fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result<Vec<(String, Vec<u8>)>, String> {
mesh_files(stem, format, parts, &[])
}
#[test]
fn obj_numbers_corners_across_solids_and_names_its_materials() {
let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
let obj = text(&files, "Box.obj");
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
@@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
#[test]
fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap();
let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap();
assert_eq!(g["asset"]["version"], "2.0");
let uri = g["buffers"][0]["uri"].as_str().unwrap();
@@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
assert!(g["materials"][0].get("alphaMode").is_none());
assert_eq!(g["materials"][0]["doubleSided"], true);
// Without graphics there are no textures.
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
}
#[test]
fn usda_is_y_up_in_points_with_a_material_for_each_color() {
let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap();
let u = text(&files, "My Box.usda");
assert!(u.starts_with("#usda 1.0\n"));
assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}");
@@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
// sRGB 0.5 is about 0.214 linear.
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
assert_eq!(u.matches('{').count(), u.matches('}').count());
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
}
#[test]
fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap();
let files = plain_files("Box", "usdz", &[square(RED)]).unwrap();
let (name, zip) = &files[0];
assert_eq!(name, "Box.usdz");
// The local header: 30 bytes, the name, then the extra field.
@@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
assert_eq!(u16_at(8), 0, "stored, not deflated");
let start = 30 + u16_at(26) + u16_at(28);
assert_eq!(start % 64, 0);
let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1;
assert_eq!(&zip[start..start + layer.len()], layer.as_slice());
let archive = super::super::zip::Archive::open(zip, 8).unwrap();
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer));
@@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() {
#[test]
fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() {
let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap();
let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box__1.obj", "Box__1.mtl"]);
assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n"));
assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]);
assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]);
assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]);
assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]);
}
#[test]
@@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() {
let mut part = square(RED);
part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0];
part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0];
let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj");
assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}");
let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda");
let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda");
assert!(usda.contains("(20000001, 0, 0)"));
}
#[test]
fn an_unknown_format_is_refused() {
assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err());
assert!(mesh_file_names("Box", "").is_err());
assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]);
assert!(plain_files("Box", "fbx", &[square(RED)]).is_err());
assert!(mesh_file_names("Box", "", &[]).is_err());
assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]);
}
#[test]
@@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() {
assert_eq!(prim_name(""), "_");
assert_eq!(prim_name("é/x"), "__x");
}
/// A red square, then a blue one whose corners show picture `png` (u to the right, v down).
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
}
#[test]
fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
let png = b"\x89PNG picture".to_vec();
let (parts, pictures) = textured(&png);
// OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG
// written beside it, with its name in one word.
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
assert_eq!(files[2].1, png);
let obj = text(&files, "My_Box.obj");
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
assert_eq!(mtl.matches("map_Kd").count(), 1);
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
let at = view["byteOffset"].as_u64().unwrap() as usize;
let first: Vec<f32> = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect();
assert_eq!(first, [0.0, 1.0]);
let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize];
assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0);
assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0]));
assert_eq!(g["textures"][0]["source"], 0);
assert_eq!(g["samplers"][0]["wrapS"], 33071);
let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap();
assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png);
// USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it.
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
let u = text(&files, "Box.usda");
assert_eq!(u.matches("primvars:st").count(), 1);
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
assert!(u.contains("string inputs:varname = \"st\""));
assert_eq!(u.matches('{').count(), u.matches('}').count());
// USDZ: the layer first, then the picture, each on a 64-byte boundary.
let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1;
let archive = super::super::zip::Archive::open(&zip, 8).unwrap();
assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u)));
assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone()));
let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize;
let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize;
let first = 30 + u16_at(26) + u16_at(28);
let second = first + u32_at(18);
assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second");
let data = second + 30 + u16_at(second + 26) + u16_at(second + 28);
assert_eq!((first % 64, data % 64), (0, 0));
assert_eq!(&zip[data..data + png.len()], png.as_slice());
}
#[test]
fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() {
let (parts, mut pictures) = textured(b"picture");
if let Some(t) = pictures[1].as_mut() {
t.opacity = Some(Arc::new(b"gray".to_vec()));
}
// OBJ: the opacity map, written after its texture, is the MTL's map_d.
let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap();
let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect();
assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]);
assert_eq!(files[3].1, b"gray");
assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names);
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}");
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let material = &g["materials"][1];
assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND")));
let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha");
let u = text(&usda, "Box.usda");
assert!(u.contains("float inputs:opacity.connect = </Box/Materials/Material_2/Texture.outputs:a>") && u.contains("float outputs:a"), "{u}");
// An opaque textured face reads no opacity from its picture.
let (_, plain) = textured(b"picture");
let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])];
let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda");
assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}");
let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl");
assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}");
}
#[test]
fn parts_sharing_a_picture_write_it_once() {
let (mut parts, mut pictures) = textured(b"one");
parts.push(square(BLUE));
pictures.push(pictures[1].clone());
assert_eq!(image_maps(&pictures), [false]);
let files = mesh_files("Box", "obj", &parts, &pictures).unwrap();
assert_eq!(files.len(), 3);
assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material");
assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]);
assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]);
assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png");
}
+42
View File
@@ -500,6 +500,48 @@ pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f
}
}
/// An opaque CMYK composite as its original 8- or 16-bit ink samples. Other modes,
/// composites with transparency, and images beyond the native CMYK pixel or allocation limit return `None`.
pub(super) fn decode_cmyk(bytes: &[u8], max_alloc: u64) -> Result<Option<craft_image_codecs::Image>, String> {
use craft_image_codecs::{ChannelLayout, Image, SampleType};
let mut r = Reader::new(bytes);
let h = header(&mut r)?;
if h.mode != Mode::Cmyk || (h.channels > 4 && merged_alpha(h.layers, h.psb)) {
return Ok(None);
}
let pixels = u64::from(h.width) * u64::from(h.height);
if pixels > vectorcraft_doc::cmyk::MAX_CMYK_PIXELS {
return Ok(None);
}
let sample_bytes = usize::from(h.depth / 8);
let samples = pixels * 4 * sample_bytes as u64;
let icc = resources(h.resources, false)
.find(|(id, _, _)| *id == 1039)
.map(|(_, _, data)| data)
.filter(|data| data.len() <= 16 << 20 && vectorcraft_doc::cmyk::icc_color_space(data) == Some(*b"CMYK"));
if samples.saturating_mul(2).saturating_add(icc.map_or(0, |p| p.len() as u64)) > max_alloc {
return Ok(None);
}
let count = pixels as usize;
let data = channel_data(r.rest(), &h, 4, row_bytes(h.width as usize, h.depth))?;
let mut out = Vec::with_capacity(samples as usize);
for i in 0..count {
for channel in 0..4 {
let at = (channel * count + i) * sample_bytes;
if h.depth == 8 {
out.push(255 - data.get(at).copied().ok_or(TRUNCATED)?);
} else {
let pair = data.get(at..at + 2).ok_or(TRUNCATED)?.try_into().map_err(|_| TRUNCATED)?;
out.extend((65535 - u16::from_be_bytes(pair)).to_ne_bytes());
}
}
}
let sample = if h.depth == 16 { SampleType::U16 } else { SampleType::U8 };
let mut image = Image::from_raw(h.width, h.height, ChannelLayout::Cmyk, sample, out).map_err(|e| e.to_string())?;
image.icc = icc.map(<[u8]>::to_vec);
Ok(Some(image))
}
/// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink
/// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than
/// `max_alloc` bytes.
@@ -97,6 +97,132 @@ fn every_colour_mode_and_depth_reads() {
assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]);
}
#[test]
fn cmyk_psd_place_keeps_the_native_ink_samples() {
let f = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[191, 255], &[127, 0], &[63, 127], &[223, 0]]));
let p = json!({"name": "inks.psd", "dataBase64": vectorcraft_format::base64_encode(&f)});
let mut s = Session::new();
s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap();
let info = s.execute("file.place.info", &p).unwrap();
assert_eq!(info["colorMode"], "CMYK");
let placed = s.execute("file.place", &p).unwrap();
let id = NodeId(placed["ids"][0].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("placed PSD is an image") };
let blob = d.images.get(&im.key).unwrap();
assert!(blob.is_cmyk());
assert_eq!(blob.cmyk().unwrap().data, [64, 128, 192, 32, 0, 255, 128, 255]);
}
#[test]
fn cmyk_psd_native_budget_keeps_the_rgba_fallback_available() {
let bytes = psd(1, 4, (2, 1), 16, 4, &[], &[], &[], &raw(&[&[0xff; 4], &[0xff; 4], &[0xff; 4], &[0; 4]]));
assert!(super::psdread::decode_cmyk(&bytes, 24).unwrap().is_none());
assert_eq!(decode(&bytes, 24, naive).unwrap().into_raw(), [0, 0, 0, 255, 0, 0, 0, 255]);
assert!(decode(&bytes, 1, naive).is_err());
}
#[test]
fn cmyk_psd_depth_and_compression_preserve_exact_samples() {
for version in [1, 2] {
for depth in [8, 16] {
let values = if depth == 8 { [191u16, 127, 63, 223] } else { [0xcdef, 0x89ab, 0x4567, 0x0123] };
let planes: Vec<Vec<u8>> = values.iter().map(|v| if depth == 8 { vec![*v as u8] } else { v.to_be_bytes().to_vec() }).collect();
let uncompressed = planes.concat();
for method in 0..=3u16 {
let mut data = method.to_be_bytes().to_vec();
match method {
0 => data.extend(&uncompressed),
1 => {
for p in &planes {
let count = (p.len() + 1) as u32;
if version == 2 { data.extend(count.to_be_bytes()) } else { data.extend((count as u16).to_be_bytes()) }
}
for p in &planes {
data.push((p.len() - 1) as u8);
data.extend(p);
}
}
_ => {
// One sample per row has the same bytes with or without prediction.
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
std::io::Write::write_all(&mut z, &uncompressed).unwrap();
data.extend(z.finish().unwrap());
}
}
let bytes = psd(version, 4, (1, 1), depth, 4, &[], &[], &[], &data);
let img = raster_image(&bytes).unwrap();
assert!(img.blob.is_cmyk(), "version {version}, depth {depth}, compression {method}");
assert_eq!(img.blob.is_cmyk16(), depth == 16);
let decoded = craft_image_codecs::decode(&img.blob.bytes).unwrap();
let expected: Vec<u8> =
values.iter().flat_map(|v| if depth == 8 { vec![255 - *v as u8] } else { (65535 - v).to_ne_bytes().to_vec() }).collect();
assert_eq!(decoded.data(), expected);
assert!(super::psdread::decode_cmyk(&bytes, 1).unwrap().is_none());
assert!(super::psdread::decode_cmyk(&bytes[..bytes.len() - data.len() + 2], 1 << 30).is_err());
}
}
}
let planes: [&[u8]; 5] = [&[255], &[255], &[255], &[255], &[128]];
let saved = psd(1, 5, (1, 1), 8, 4, &[], &[], &[], &raw(&planes));
assert!(raster_image(&saved).unwrap().blob.is_cmyk(), "a saved selection is not transparency");
let alpha = psd(1, 5, (1, 1), 8, 4, &[], &[], &layer_count(-1, false), &raw(&planes));
let img = raster_image(&alpha).unwrap();
assert!(!img.blob.is_cmyk());
assert_eq!(craft_image_codecs::decode(&img.blob.bytes).unwrap().to_rgba8()[3], 128);
}
#[test]
fn cmyk_psd_links_keep_inks_profile_resolution_and_clipping() {
let profile = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GENERIC_CMYK).unwrap();
let mut res = Vec::new();
res.extend((144u32 << 16).to_be_bytes());
res.extend([0, 1, 0, 1]);
res.extend((144u32 << 16).to_be_bytes());
res.extend([0, 1, 0, 1]);
let make = |clip: &[u8], ink: u8| {
let resources = [resource(1039, b"", &profile), resource(1005, b"", &res), clip.to_vec()].concat();
psd(1, 4, (2, 1), 8, 4, &[], &resources, &[], &raw(&[&[255 - ink; 2], &[127; 2], &[63; 2], &[223; 2]]))
};
let dir = vectorcraft_testkit::TempDir::new("psd-cmyk-links");
let cut = write_file(&dir, "cut.psd", &make(&triangle_resources(), 64));
let square = write_file(&dir, "square.psd", &make(&square_resources(), 96));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 20, "height": 10, "colorMode": "cmyk"})).unwrap();
assert_eq!(s.execute("file.place.info", &json!({"path": cut})).unwrap()["colorMode"], "CMYK");
let r = s.execute("file.place", &json!({"path": cut, "at": [0.5, 0.25]})).unwrap();
let group = NodeId(r["ids"][0].as_u64().unwrap());
let id = r["image"].as_u64().unwrap();
assert_eq!(r["width"], 1.0);
assert_eq!(r["height"], 0.5);
let check = |s: &mut Session, ink, linked| {
let info = s.execute("links.info", &json!({"id": id})).unwrap();
assert_eq!(info["colorMode"], "CMYK");
assert_eq!(info["linked"], linked);
assert_eq!(info["ppi"], json!([144.0, 144.0]));
let d = &s.doc().unwrap().doc;
let NodeKind::Image(im) = &d.node(NodeId(id)).unwrap().kind else { panic!("placed image") };
let blob = d.images.get(&im.key).unwrap();
assert_eq!(blob.cmyk().unwrap().data, [ink, 128, 192, 32, ink, 128, 192, 32]);
assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(profile.as_ref()));
assert_eq!(
super::load::image_clip(blob),
Some(clipping_path(&make(&if ink == 64 { triangle_resources() } else { square_resources() }, ink)).unwrap())
);
};
check(&mut s, 64, true);
let triangle = clip_group(&s.doc().unwrap().doc, group);
s.execute("links.relink", &json!({"ids": [id], "path": square})).unwrap();
check(&mut s, 96, true);
assert_ne!(clip_group(&s.doc().unwrap().doc, group).0, triangle.0);
std::fs::write(&square, make(&triangle_resources(), 64)).unwrap();
s.execute("links.update", &json!({"ids": [id]})).unwrap();
check(&mut s, 64, true);
assert_eq!(clip_group(&s.doc().unwrap().doc, group), triangle);
s.execute("links.embed", &json!({"ids": [id]})).unwrap();
check(&mut s, 64, false);
}
#[test]
fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() {
// Half-transparent red, stored on white: (255, 127, 127) with alpha 128.
+39 -1
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use serde_json::json;
use vectorcraft_doc::Document;
use vectorcraft_doc::{Document, Node, NodeKind};
use super::*;
@@ -212,6 +212,44 @@ fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_a
assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself");
}
/// The art over an artboard, among 300 instances with drop shadows and 2,000 symbols, is found
/// reading the symbol list once, and keeps the instances over it.
#[test]
fn art_over_an_artboard_reads_the_symbol_list_once() {
let mut d = Document::new(100.0, 100.0);
let square = |d: &mut Document, side: f64| {
let r = vectorcraft_geom::Rect::new(-side, -side, side, side);
let ap =
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0);
Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), ap))
};
for i in 0..2000 {
let art = square(&mut d, 0.5);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art });
}
let art = square(&mut d, 2.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art });
let layer = d.layers[0].id;
// Twenty rows of 15: the first ten over the artboard, the rest below it.
let ids: Vec<_> = (0..300)
.map(|i| {
let xf = vectorcraft_geom::Affine::translate((f64::from(i % 15) * 6.0 + 5.0, f64::from(i / 15) * 10.0 + 5.0));
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
d.insert(Some(layer), usize::MAX, n).unwrap()
})
.collect();
let before = vectorcraft_doc::symbols_read();
let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new());
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
assert_eq!(ids.iter().filter(|id| kept.node(**id).is_some()).count(), 150);
}
/// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset)
/// has the artboard's (or asset's) name as `<title>`; Save's SVG and Export for Screens' Full
/// Document keep the document's.
+55 -9
View File
@@ -247,10 +247,11 @@ impl Resources {
fn expand(&mut self, d: &Document) {
let mut symbols: Vec<String> = self.symbols.iter().cloned().collect();
let mut patterns: Vec<String> = self.patterns.iter().cloned().collect();
let boxes = d.symbol_boxes();
while !symbols.is_empty() || !patterns.is_empty() {
let mut more = Resources::default();
for name in symbols.drain(..) {
if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) {
if let Some(sym) = boxes.symbol(&name) {
more.add(&sym.art);
}
}
@@ -511,7 +512,7 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> {
/// art of a placed document (`d` as [`Document::with_placed_art`] gives it, for that art's
/// resources).
pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> (BTreeSet<UsedFont>, BTreeSet<NodeId>) {
let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() };
let mut walk = Printed::new(d);
for l in layers {
walk.node(l, Some(areas));
}
@@ -523,7 +524,7 @@ pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -
/// found as [`printed_type`] finds them for Print: visible objects of the document that aren't on
/// a template layer.
pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: Option<&[Rect]>) -> Option<String> {
let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() };
let mut walk = Printed::new(d);
for l in layers {
walk.node(l, areas);
}
@@ -534,6 +535,9 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas:
/// The walk of [`printed_type`].
struct Printed<'a> {
d: &'a Document,
/// `d`'s symbols, found by name. Each object is measured in boxes of its own made from these
/// ([`vectorcraft_doc::SymbolBoxes::unmeasured`]).
boxes: vectorcraft_doc::SymbolBoxes<'a>,
/// Whether the walk is among the objects of the document, not in art drawn for one.
own: bool,
fonts: BTreeSet<UsedFont>,
@@ -544,7 +548,13 @@ struct Printed<'a> {
patterns: BTreeSet<String>,
}
impl Printed<'_> {
impl<'a> Printed<'a> {
/// A walk of `d` among its own objects, nothing found yet.
fn new(d: &'a Document) -> Self {
let boxes = d.symbol_boxes();
Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }
}
/// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit
/// while [`Printed::own`] is set: those whose bounds meet one of `areas`, or with `None` (in the
/// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live
@@ -625,7 +635,7 @@ impl Printed<'_> {
let clipped = match (clip, areas) {
(false, _) => None,
(true, Some(a)) => Some(self.clip(n, a)),
(true, None) => vectorcraft_render::painted_bounds(self.d, n).map(|c| vec![c]),
(true, None) => vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n).map(|c| vec![c]),
};
for c in children {
self.node(c, clipped.as_deref().or(areas));
@@ -641,9 +651,8 @@ impl Printed<'_> {
/// Adds the fonts of symbol `name`'s art, the first time it is shown.
fn symbol(&mut self, name: &str) {
let d = self.d;
if self.symbols.insert(name.to_string())
&& let Some(s) = d.symbols.iter().find(|s| s.name == name)
&& let Some(s) = self.boxes.symbol(name)
{
self.art(&s.art);
}
@@ -660,12 +669,13 @@ impl Printed<'_> {
/// Whether what `n` paints, its effects applied, meets one of `areas`.
fn meets(&self, n: &Node, areas: &[Rect]) -> bool {
vectorcraft_render::painted_bounds(self.d, n).is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b)))
vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n)
.is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b)))
}
/// The parts of `areas` inside the bounds of clip group `n` (its clipping path's).
fn clip(&self, n: &Node, areas: &[Rect]) -> Vec<Rect> {
let Some(c) = vectorcraft_render::painted_bounds(self.d, n) else { return areas.to_vec() };
let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) else { return areas.to_vec() };
areas.iter().filter(|r| c.intersect(**r).area() > 0.0 || r.contains_rect(c)).map(|r| r.intersect(c)).collect()
}
}
@@ -2378,4 +2388,40 @@ mod dirty_tests {
s.execute("edit.undo", &json!({})).unwrap();
assert!(!s.doc().unwrap().is_dirty(), "back to the saved state");
}
/// The walk Print and the exports make over 300 instances with drop shadows, among 2,000
/// symbols, reads the symbol list once to find their symbols.
#[test]
fn printed_type_reads_the_symbol_list_once() {
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let art = Node::path(
d.alloc_id(),
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)),
vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0),
);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
}
let art = Node::path(
d.alloc_id(),
vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)),
vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0),
);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) });
let l = d.layers[0].id;
for i in 0..300 {
let xf = vectorcraft_geom::Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 10.0));
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
d.insert(Some(l), usize::MAX, n).unwrap();
}
let before = vectorcraft_doc::symbols_read();
printed_type(&d, &d.layers, &[Rect::new(0.0, 0.0, 100.0, 100.0)]);
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
}
}
+2 -2
View File
@@ -713,12 +713,12 @@ type FileClip = (PathData, FillRule);
/// The clipping path the file of image content `blob` draws it through, in its pixel space, as it
/// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB
/// file's ([`fileio::png_clip`]).
/// file's ([`fileio::image_clip`]).
fn file_clip(blob: &ImageBlob) -> Option<FileClip> {
if let Some(path) = blob.separated_clip() {
return Some((path, FillRule::NonZero));
}
(blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd))
fileio::image_clip(blob).map(|path| (path, FillRule::EvenOdd))
}
/// What happens to the clip of an object a link update remakes.
+20 -2
View File
@@ -357,6 +357,7 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
&& prev != isolation
{
crate::cmd::settle_interaction(s)?;
add_drawn_live_paint(s, prev, Some(isolation))?;
let st = s.doc_mut()?;
crate::cmd::distortcmds::finish_edit_text(st, prev);
}
@@ -369,6 +370,19 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn
/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one
/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is
/// inside it; → the group when paths were added.
fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> {
let d = &s.doc()?.doc;
let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) };
if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) {
return Ok(None);
}
Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g))
}
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
@@ -378,10 +392,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
&& let Some(inner) = st.isolation.filter(|i| *i != layer && st.doc.ancestry(*i).is_some_and(|a| a.contains(&layer)))
{
crate::cmd::settle_interaction(s)?;
let left = add_drawn_live_paint(s, inner, Some(layer))?.unwrap_or(inner);
let st = s.doc_mut()?;
crate::cmd::distortcmds::finish_edit_text(st, inner);
st.isolation = Some(layer);
st.selection.set([inner]);
st.selection.set([left]);
st.revision += 1;
return ok();
}
@@ -396,6 +411,8 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
};
if let Some(leave_mode) = leave_mode {
if let Some(i) = st.isolation {
crate::cmd::settle_interaction(s)?;
add_drawn_live_paint(s, i, None)?;
crate::cmd::distortcmds::finish_edit_text(s.doc_mut()?, i);
}
leave_mode(s, p)?;
@@ -405,10 +422,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
let prev = s.active().and_then(|d| d.isolation);
if let Some(i) = prev {
crate::cmd::settle_interaction(s)?;
let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i);
let st = s.doc_mut()?;
st.isolation = None;
crate::cmd::distortcmds::finish_edit_text(st, i);
let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(i);
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
st.selection.set([target]);
// A guide path isolated while Lock Guides is on isn't selected (#1534).
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
+9 -1
View File
@@ -245,7 +245,15 @@ pub fn specs() -> Vec<CommandSpec> {
crate::cmd::maskedit::outside_mask_editing,
isolate
),
cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation),
cmd!(
"object.exitIsolation",
"Exit Isolation Mode",
[],
None,
"{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same",
has_doc,
exit_isolation
),
cmd!(
"object.setProps",
"Object Properties",
+11 -1
View File
@@ -1276,7 +1276,7 @@ fn aligned_between(tab: &vectorcraft_doc::TabStop, from: f64, x: f64) -> bool {
/// The frames of the story that type object `id` belongs to (its thread in thread order, else `id`
/// alone), each with the length of its text in bytes.
fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
pub(crate) fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
let Some(st) = s.active() else { return vec![] };
let d = &st.doc;
let frames = d.text_threads.iter().find(|thread| thread.contains(&id)).cloned().unwrap_or_else(|| vec![id]);
@@ -1314,6 +1314,16 @@ fn move_editing_selection(
at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::<usize>()
};
let (anchor, caret) = (story(anchor), story(caret));
select_story_range(s, id, anchor, caret)
}
/// The Type tool's anchor and caret become story positions `anchor` and `caret` of the story that
/// frame `id` belongs to, as its frames are now. The caret stays in `id` while its place is there,
/// and else goes to the frame that holds it, with the anchor in that frame; that frame becomes the
/// selection when it was not selected.
pub(crate) fn select_story_range(s: &mut Session, id: NodeId, anchor: usize, caret: usize) -> Result<()> {
let start_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().take_while(|(g, _)| *g != f).map(|(_, n)| n).sum::<usize>();
let len_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().find(|(g, _)| *g == f).map_or(0, |(_, n)| *n);
let after = story_frames(s, id);
let fits = |f: NodeId| (start_of(&after, f)..=start_of(&after, f) + len_of(&after, f)).contains(&caret);
let frame = if fits(id) { Some(id) } else { after.iter().map(|(f, _)| *f).find(|f| fits(*f)) };
+1 -1
View File
@@ -91,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Placed File Info",
[],
None,
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
"{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images; opaque CMYK PSD/PSB merged images keep 8- or 16-bit inks within VectorCraft's 67,108,864-pixel native CMYK limit and allocation allowance; other CMYK composites use the RGB decoder's allocation limit), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}",
always,
info
),
+1 -1
View File
@@ -270,7 +270,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> {
Ok((a.min(b), a.max(b)))
}
fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "text.editRange";
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
let t = text_ref(s, id)?;
+52 -7
View File
@@ -10,8 +10,8 @@ use super::object::choice;
use super::threads::ThreadIndex;
use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds};
use super::{
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
switch_or, targets, text_param,
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids,
number_or, switch_or, targets, text_param,
};
pub fn specs() -> Vec<CommandSpec> {
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Insert Character",
["Type"],
None,
"{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} append to the selected text objects",
"{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} insert at the Type tool's caret, replacing its selection, while it edits text and no ids are given; otherwise append to the selected text objects. forcedLineBreak is U+2028, a new line in the same paragraph; paragraphReturn is a line feed, which starts a new paragraph",
has_selection,
insert_char
),
@@ -786,8 +786,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
let plain = t.plain_text();
let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8);
// Soft wraps → explicit breaks (replace the space before the wrap when there is one).
let mut breaks: Vec<usize> =
lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && plain.as_bytes().get(b - 1) != Some(&b'\n')).collect();
// A line after a paragraph return or a forced line break (U+2028) already starts there.
let hard = |b: usize| plain.get(..b).is_some_and(|s| s.ends_with(['\n', '\u{2028}']));
let mut breaks: Vec<usize> = lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && !hard(b)).collect();
breaks.sort_unstable();
breaks.dedup();
for b in breaks.into_iter().rev() {
@@ -1525,8 +1526,9 @@ pub(crate) fn special_char(name: &str) -> Option<&'static str> {
"thirdSpace" => "\u{2004}",
"quarterSpace" => "\u{2005}",
"tab" => "\t",
// Our text model breaks lines at paragraph returns only.
"forcedLineBreak" | "paragraphReturn" => "\n",
// A line break inside the paragraph, as Shift+Enter types it.
"forcedLineBreak" => "\u{2028}",
"paragraphReturn" => "\n",
_ => return None,
})
}
@@ -1576,6 +1578,11 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
(None, None, None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(),
(None, None, None, None) => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")),
};
if named_ids(p)?.is_none()
&& let Some(r) = insert_at_type_caret(s, &text)?
{
return Ok(r);
}
let ids = texts(s, p, C)?;
// When `text` is empty and every object ends with a run of text, the document and its undo
// history stay as they are.
@@ -1606,6 +1613,44 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> {
Ok(ids_json(&ids))
}
/// `type.insert` while the Type tool edits text: `text` replaces the tool's selection (inserts at
/// its caret) as one undo step, and the caret goes after it. `None` when no text is being edited.
fn insert_at_type_caret(s: &mut Session, text: &str) -> Result<Option<Value>> {
let tool = s.tool_options();
let Some(id) = tool.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) };
let d = &s.doc()?.doc;
let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { return Ok(None) };
let len = vectorcraft_text::edit::runs_len(&t.runs);
let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len));
let (x, y) = (g("start"), g("end"));
let (a, b) = (x.min(y), x.max(y));
// After Select All in threaded text the whole story is selected: the other frames' text goes
// in the same edit, as when typing replaces it.
let story: Vec<NodeId> = tool.get("story").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect();
let clear: Vec<u64> = if a == 0 && b == len && story.contains(&id) {
let has_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(o)) if !o.runs.iter().all(|r| r.text.is_empty()));
story.iter().filter(|f| **f != id && has_text(f)).map(|f| f.0).collect()
} else {
vec![]
};
if text.is_empty() && a == b && clear.is_empty() {
return Ok(Some(ids_json(&[id])));
}
// A typing session ends first: the insertion is a step of its own.
if tool.get("typing").and_then(Value::as_bool) == Some(true) {
s.set_tool_option("commitTyping", &Value::Bool(true));
s.commit_interaction()?;
}
// The frame's place in the story once the edit has cleared the frames in `clear`.
let start: usize =
super::panelcmds::story_frames(s, id).iter().take_while(|(f, _)| *f != id).filter(|(f, _)| !clear.contains(&f.0)).map(|(_, n)| n).sum();
let r = super::textedit::edit_range(s, &json!({"id": id.0, "start": a, "end": b, "insert": text, "clear": clear}))?;
let caret = r.get("caret").and_then(Value::as_u64).map_or(a + text.len(), |c| c as usize);
// Threaded text re-flows in the edit: the caret goes to the frame its place moved to.
super::panelcmds::select_story_range(s, id, start + caret, start + caret)?;
Ok(Some(ids_json(&[id])))
}
// ---------- Find and Replace ----------
fn is_word(c: char) -> bool {
+157
View File
@@ -246,6 +246,163 @@ fn export_3d_writes_into_a_folder_or_one_zip() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A blue 100 × 100 square extruded straight on, with a red 10 × 20 graphic "Mark" mapped onto its
/// front at its center and onto its back 30 pt to the right (as the back is seen from behind),
/// collected as a 3D asset in `format`.
fn mapped(format: &str) -> (Session, u64) {
let mut s = session();
let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone();
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]}));
let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap();
run(&mut s, "paint.setFill", json!({"color": "#0000ff"}));
run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "depth": 20.0}}));
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [id]}));
run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "face": "back", "x": 30.0, "ids": [id]}));
run(&mut s, "layer.setProps", json!({"id": id, "name": "Box"}));
let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap();
(s, asset)
}
/// The color of pixel `(x, y)` of PNG `png`.
fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] {
image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0
}
fn is_red(p: [u8; 4]) -> bool {
p[0] > 200 && p[1] < 50 && p[2] < 50 && p[3] == 255
}
fn is_blue(p: [u8; 4]) -> bool {
p[0] < 50 && p[1] < 50 && p[2] > 200 && p[3] == 255
}
#[test]
fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() {
for (format, names) in [
("usda", vec!["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]),
("usdz", vec!["Box.usdz"]),
("gltf", vec!["Box.gltf"]),
("obj", vec!["Box.obj", "Box.mtl", "Box-texture-1.png", "Box-texture-2.png"]),
] {
let (mut s, _) = mapped(format);
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}");
}
// The front's picture: the cap's 100 pt across 128 pixels, blue with the red graphic at the
// middle; the back's: the graphic 30 pt to the right as seen from behind, which is to the left
// in the art's plane.
let (mut s, _) = mapped("usda");
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (front, back) = (&out[1].1, &out[2].1);
assert_eq!(image::load_from_memory(front).unwrap().to_rgba8().dimensions(), (128, 128));
assert!(is_red(pixel(front, 64, 64)) && is_blue(pixel(front, 2, 2)) && is_blue(pixel(front, 64, 10)));
let at = |pt: f64| (pt * 1.28) as u32;
assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64));
// The USDA's front cap shows the front picture through st, up from the picture's bottom.
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert_eq!(usda.matches("primvars:st").count(), 2);
assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap");
// glTF holds both pictures, and a cap's coordinates stay inside its picture.
let (mut s, _) = mapped("gltf");
let out = files(&run(&mut s, "assets.export3D", json!({})));
let g: Value = serde_json::from_slice(&out[0].1).unwrap();
assert_eq!(g["images"].as_array().map(Vec::len), Some(2));
let png = vectorcraft_format::base64_decode(g["images"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap();
assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default");
}
#[test]
fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() {
let half = |a: u8| (120..=135).contains(&a);
// A half-opaque fill: the face and the graphic over it are each drawn at half opacity, so the
// graphic covers three quarters.
let (mut s, asset) = mapped("usda");
let doc = &s.active().unwrap().doc;
let id = doc.asset(asset).unwrap().nodes[0];
let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(on[0] > on[2] && (185..=197).contains(&on[3]), "{on:?}");
assert!(around[2] > 200 && half(around[3]), "{around:?}");
let usda = String::from_utf8(out[0].1.clone()).unwrap();
assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity");
// An OBJ's opacity map has the alpha as gray levels.
run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out[3].0, "Box-texture-1-opacity.png");
let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8();
let (g_on, g_around) = (gray.get_pixel(64, 64).0[0], gray.get_pixel(2, 2).0[0]);
assert!((185..=197).contains(&g_on) && half(g_around), "{g_on} {g_around}");
// A half-opaque object: the face and the graphic are drawn opaque, and the whole picture at
// half opacity.
let (mut s, asset) = mapped("usda");
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
run(&mut s, "transparency.set", json!({"ids": [id.0], "opacity": 50}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(on[0] > 200 && on[2] < 50 && half(on[3]), "{on:?}");
assert!(around[2] > 200 && around[0] < 50 && half(around[3]), "{around:?}");
// A gradient whose stops are clear: the face is clear, and the graphic keeps its opacity.
let (mut s, asset) = mapped("usda");
let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0];
run(&mut s, "select.set", json!({"ids": [id.0]}));
let clear = json!({"stops": [{"offset": 0, "color": "#0000ff", "opacity": 0}, {"offset": 1, "color": "#0000ff", "opacity": 0}]});
run(&mut s, "paint.setFill", json!({"gradient": clear}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2));
assert!(is_red(on), "{on:?}");
assert_eq!(around[3], 0, "{around:?}");
}
#[test]
fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() {
let (mut s, asset) = mapped("obj");
for bad in [json!(64), json!(5000), json!(512.5), json!("512"), json!(-1)] {
assert!(s.execute("assets.export3D", &json!({"textureSize": bad})).is_err(), "{bad}");
}
// Without its graphics the box is one plain mesh, as before.
let id = s.doc().unwrap().doc.asset(asset).unwrap().nodes[0].0;
run(&mut s, "select.set", json!({"ids": [id]}));
run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}}));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
let obj = String::from_utf8(out[0].1.clone()).unwrap();
assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1);
}
#[test]
fn texture_pixels_are_counted_across_one_export() {
let (s, asset) = mapped("gltf");
let d = &s.doc().unwrap().doc;
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap();
let mut pixels = 0;
let made = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap();
assert_eq!((made.iter().flatten().count(), pixels), (2, 2 * 128 * 128));
let mut pixels = crate::cmd::fileio::MAX_TEXTURE_PIXELS - 128 * 128;
let e = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap_err();
assert!(e.contains("textureSize"), "{e}");
}
#[test]
fn only_graphics_that_draw_count_as_textures() {
let parts_of = |s: &Session, asset: u64| {
let d = &s.doc().unwrap().doc;
let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap();
vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap()
};
let (mut s, asset) = mapped("obj");
assert!(crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
// With its symbol gone the graphic draws nothing, so the export writes no texture.
run(&mut s, "symbol.delete", json!({"name": "Mark"}));
assert!(!crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset)));
let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128})));
assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]);
}
#[test]
fn three_d_assets_round_trip_through_the_native_format() {
let mut s = session();
+273
View File
@@ -4762,6 +4762,279 @@ fn live_paint_refuses_type_and_images_and_changes_nothing() {
assert!(!vectorcraft_tools::builder::live_paint_takes(&node(&s, text_group)));
}
/// A horizontal open path across [`live`]'s group at `y`, drawn with the Pen's defaults.
fn line_across(s: &mut Session, y: f64) -> NodeId {
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 160, "y": y}]})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
/// Paths drawn in an isolated Live Paint group join it when isolation mode ends: they go among its
/// sources and cut the faces they cross, which take their sources' fill, a painted face they do not
/// cross keeps its fill, and the whole addition is one undo step, which Undo takes back to the
/// drawn paths in the group and Redo makes again.
#[test]
fn live_paint_isolation_adds_drawn_paths_on_exit() {
use vectorcraft_tools::builder::{face_at, faces, sources};
let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
let mut s = session();
let g = live(&mut s);
s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
// Two lines from left of the group that end in its right face, so they cut only the other two.
let line = |s: &mut Session, y: f64| {
let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap();
NodeId(r["id"].as_u64().unwrap())
};
let (a, b) = (line(&mut s, 30.0), line(&mut s, 70.0));
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path drawn in isolation goes into the group");
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.exitIsolation", &json!({})).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.isolation, None);
assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step");
assert_eq!(d.selection.objects, vec![g]);
let n = node(&s, g);
let src = sources(&n).unwrap();
assert_eq!(src.children().unwrap().len(), 4);
for id in [a, b] {
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources");
}
assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three");
assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill");
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
for y in [15.0, 85.0] {
assert_eq!(face_at(&n, Point::new(25.0, y)).unwrap().appearance.fill_paint(), red, "a new face takes its source's fill");
}
s.execute("edit.undo", &json!({})).unwrap();
let n = node(&s, g);
assert_eq!(faces(&n).len(), 3);
assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2);
for id in [a, b] {
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "Undo puts {id} back in the group as drawn");
}
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 7);
}
/// Leaving isolation mode in a Live Paint group with nothing drawn in it records no undo step and
/// leaves the document as it is. Type, and a path that is hidden, stay in the group as they are,
/// while a group of paths drawn beside them joins it.
#[test]
fn live_paint_isolation_adds_only_paths_it_takes() {
use vectorcraft_tools::builder::{faces, sources};
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
s.execute("object.exitIsolation", &json!({})).unwrap();
assert!(s.doc().unwrap().doc == before.0, "an exit with nothing drawn changes nothing");
assert_eq!(s.doc().unwrap().history.undo.len(), before.1, "and records no undo step");
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
let hidden = line_across(&mut s, 50.0);
s.edit("t", |d, _| {
d.node_mut(hidden).unwrap().visible = false;
Ok(())
})
.unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.exitIsolation", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "type and a hidden path add nothing");
assert_eq!(faces(&node(&s, g)).len(), 3);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g));
s.execute("object.exitIsolation", &json!({})).unwrap();
let n = node(&s, g);
assert_eq!(faces(&n).len(), 9, "the group of paths joined");
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(paths), Some(sources(&n).unwrap().id));
for id in [text, hidden] {
assert_eq!(d.parent_of(id), Some(g), "{id} stays in the group");
assert!(d.node(id).is_some());
}
}
/// A group drawn in an isolated Live Paint group that holds a locked path stays in it as it is when
/// isolation mode ends, as a locked path drawn there does.
#[test]
fn live_paint_isolation_leaves_a_group_holding_a_locked_path() {
use vectorcraft_tools::builder::faces;
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("t", |d, _| {
d.node_mut(b).unwrap().locked = true;
Ok(())
})
.unwrap();
let steps = s.doc().unwrap().history.undo.len();
s.execute("object.exitIsolation", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g));
assert_eq!(faces(&node(&s, g)).len(), 3);
}
/// Type drawn in an isolated Live Paint group stays in it when Gap Options or Merge make the group's
/// faces and edges again, including type in a Live Paint group merged into another, and Release
/// puts it beside the released paths.
#[test]
fn live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release() {
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type");
let c = rect(&mut s, 120.0, 20.0, 100.0, 20.0);
s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Merge keeps the type");
let other = rect(&mut s, 300.0, 300.0, 50.0, 50.0);
let h = NodeId(s.execute("livePaint.make", &json!({"ids": [other.0]})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": h.0})).unwrap();
let text2 = NodeId(s.execute("text.create", &json!({"x": 310, "y": 320, "text": "Yo"})).unwrap()["id"].as_u64().unwrap());
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("livePaint.merge", &json!({"ids": [g.0, h.0]})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(text2), Some(g), "the type of the merged group moves with its paths");
s.execute("livePaint.release", &json!({"ids": [g.0]})).unwrap();
let d = &s.doc().unwrap().doc;
for id in [text, text2] {
assert_eq!(d.parent_of(id), d.default_layer(), "Release keeps {id}");
}
}
/// Art drawn in an isolated Live Paint group and named like one of the group's parts is not taken
/// for one: type named "Live Paint Sources" stays in the group through Gap Options, and a group of
/// paths named "Face" joins the group when isolation mode ends.
#[test]
fn live_paint_isolation_keeps_art_named_like_its_parts() {
use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources};
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("object.setProps", &json!({"id": text.0, "name": SOURCES_NAME})).unwrap();
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.setProps", &json!({"id": paths.0, "name": "Face"})).unwrap();
s.execute("object.exitIsolation", &json!({})).unwrap();
let n = node(&s, g);
assert_eq!(faces(&n).len(), 9, "the group named Face joined");
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id));
s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type named like the sources");
}
/// Type drawn in an isolated Live Paint group under the name of a face, an edge or the sources
/// group is not one of the group's parts: Gap Options, Info and Make count only the faces and edges
/// Live Paint made, and Expand keeps the type.
#[test]
fn live_paint_does_not_count_art_named_like_its_parts() {
use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, SOURCES_NAME};
let mut s = session();
let g = live(&mut s);
let edges = s.execute("livePaint.info", &json!({"group": g.0})).unwrap()["edges"].as_array().unwrap().len();
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let mut texts = vec![];
for (i, name) in [FACE_NAME, EDGE_NAME, SOURCES_NAME].into_iter().enumerate() {
let r = s.execute("text.create", &json!({"x": 20 + 20 * i, "y": 20, "text": "Hi"})).unwrap();
let t = NodeId(r["id"].as_u64().unwrap());
s.execute("object.setProps", &json!({"id": t.0, "name": name})).unwrap();
texts.push(t);
}
s.execute("object.exitIsolation", &json!({})).unwrap();
let r = s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap();
assert_eq!(r["faces"], 3, "Gap Options counts the faces Live Paint made");
let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap();
assert_eq!(info["faces"].as_array().unwrap().len(), 3);
assert_eq!(info["edges"].as_array().unwrap().len(), edges);
let r = s.execute("livePaint.make", &json!({"ids": [g.0]})).unwrap();
assert_eq!((r["faces"].as_u64(), r["edges"].as_u64()), (Some(3), Some(edges as u64)));
s.execute("livePaint.expand", &json!({"ids": [g.0]})).unwrap();
let d = &s.doc().unwrap().doc;
for t in texts {
assert_eq!(d.parent_of(t), Some(g), "Expand keeps {t}");
}
}
/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group
/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and
/// joins the group with the tile saved.
#[test]
fn live_paint_in_a_pattern_tile_adds_a_shape_still_being_drawn_on_exit() {
use vectorcraft_tools::builder::{is_live_paint, sources};
let mut s = session();
two(&mut s);
s.execute("object.pattern.make", &json!({"name": "P"})).unwrap();
let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
let v = ViewInfo::default();
s.select_tool("rectangle", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 40.0), v).unwrap();
assert!(s.interaction_unapplied());
s.execute("object.exitIsolation", &json!({})).unwrap();
let st = s.doc().unwrap();
assert!(st.doc.pattern_edit.is_none());
let art = &st.doc.pattern("P").unwrap().art;
let n = art.iter().find(|n| is_live_paint(n)).expect("the tile holds the Live Paint group");
assert_eq!(sources(n).unwrap().children().unwrap().len(), 3, "the rectangle joined the sources");
}
/// Isolating a level outside an isolated Live Paint group, as the isolation bar's back arrow does,
/// leaves the group and adds the paths drawn in it; isolating a path drawn in it does not.
#[test]
fn live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside() {
use vectorcraft_tools::builder::{faces, sources};
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let a = line_across(&mut s, 50.0);
s.execute("object.isolate", &json!({"id": a.0})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the path is still being drawn in the group");
assert_eq!(faces(&node(&s, g)).len(), 3);
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
assert_eq!(s.doc().unwrap().isolation, Some(layer));
let n = node(&s, g);
assert_eq!(faces(&n).len(), 6);
assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&n).unwrap().id));
}
/// A group of paths drawn in an isolated Live Paint group and then isolated itself joins the Live
/// Paint group when isolation mode ends, or when a level outside the Live Paint group is isolated.
#[test]
fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() {
use vectorcraft_tools::builder::{faces, sources};
for to_layer in [false, true] {
let mut s = session();
let g = live(&mut s);
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": paths.0})).unwrap();
assert_eq!(faces(&node(&s, g)).len(), 3, "isolating the drawn group stays in the Live Paint group");
if to_layer {
let layer = s.doc().unwrap().doc.parent_of(g).unwrap();
s.execute("object.isolate", &json!({"id": layer.0})).unwrap();
} else {
s.execute("object.exitIsolation", &json!({})).unwrap();
}
let n = node(&s, g);
assert_eq!(faces(&n).len(), 9, "the drawn group joined (to the layer: {to_layer})");
assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id));
}
}
/// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and
/// graphic style link, and return it as it then is.
fn dress_live_group(s: &mut Session, g: NodeId) -> Node {
+135
View File
@@ -615,6 +615,141 @@ fn clicking_an_image_samples_its_pixel() {
assert_eq!(node(&s, dst).appearance.fill_paint().color(), Some(Color::rgb8(128, 128, 64)), "5 x 5 average of both pixels");
}
/// Gradient mesh points picked with Direct Selection or the Mesh tool take the color the
/// Eyedropper then samples from an image or from other art, each sample one undo step, and only
/// they change: the mesh's other points and its appearance stay as they were (#8090).
#[test]
fn picked_mesh_points_take_the_eyedropper_sample() {
let mut s = session();
// Two pixels, orange and teal, 100 pt each, at (300, 0).
let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat();
let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
s.edit("Place", |d, _| {
d.images.insert("px".into(), ImageBlob::png(png.to_vec()));
let l = d.layers[0].id;
let id = d.alloc_id();
let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0);
let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None };
d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string()))
})
.unwrap();
let m = rect(&mut s, 10.0);
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
let red = rect(&mut s, 100.0);
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let colors = |s: &Session| match node(s, m).kind {
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(),
k => panic!("not a mesh: {k:?}"),
};
let white = colors(&s)[0];
assert!(colors(&s).iter().all(|c| *c == white && *c != Color::rgb8(255, 0, 0)));
let appearance = node(&s, m).appearance;
let v = ViewInfo::default();
let pick = |s: &mut Session, tool: &str, i: usize, shift: bool| {
s.select_tool(tool, v).unwrap();
let q = match node(s, m).kind {
NodeKind::Mesh(g) => g.points[i].p,
k => panic!("not a mesh: {k:?}"),
};
let mods = Mods { shift, ..Default::default() };
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap();
}
};
let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0));
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
pick(&mut s, "directSelection", 0, false);
let undo = undo_len(&s);
click(&mut s, 450.0, 50.0, Mods::default());
assert_eq!(colors(&s), [teal, white, white, white], "the picked point takes the image's color");
assert_eq!(node(&s, m).appearance, appearance, "the mesh's appearance stays");
assert_eq!(undo_len(&s), undo + 1, "one undo step");
// The Eyedropper keeps the picks: a Shift-click samples into the point again.
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { shift: true, ..Default::default() }), v).unwrap();
assert_eq!(colors(&s), [orange, white, white, white]);
assert_eq!(undo_len(&s), undo + 2);
// A sample of the color the point already has changes nothing and adds no step.
s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0), v).unwrap();
assert_eq!(undo_len(&s), undo + 2, "no step when nothing changes");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(colors(&s), [teal, white, white, white]);
// Two points picked with the Mesh tool both take a plain click's sample of other art, and the
// art keeps its fill.
pick(&mut s, "mesh", 1, false);
pick(&mut s, "mesh", 3, true);
let undo = undo_len(&s);
click(&mut s, 125.0, 35.0, Mods::default());
let r = Color::rgb8(255, 0, 0);
assert_eq!(colors(&s), [teal, r, white, r]);
assert_eq!(undo_len(&s), undo + 1, "one undo step for every picked point");
assert_eq!(node(&s, m).appearance, appearance);
assert_eq!(node(&s, red).appearance.fill_paint().color(), Some(r));
// Back in the Mesh tool the two points are still picked: a fill color recolors just them.
s.select_tool("mesh", v).unwrap();
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
let b = Color::rgb8(0, 0, 255);
assert_eq!(colors(&s), [teal, b, white, b], "the picks go back to the Mesh tool");
// Without picked points a click on an image samples into the whole selected mesh as before.
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
click(&mut s, 450.0, 50.0, Mods::default());
assert_eq!(colors(&s), [teal, b, white, b], "the points keep their colors");
assert_ne!(node(&s, m).appearance, appearance);
}
/// A Cmd-click with the Direct Selection tool the Eyedropper lends picks gradient mesh points for
/// the Eyedropper: the lent tool starts from the Eyedropper's picks, so a Shift-click adds to
/// them, and the Eyedropper samples into what the lent tool left picked (#8090).
#[test]
fn mesh_points_picked_through_the_lent_tool_take_the_eyedropper_sample() {
let mut s = session();
// Two pixels, orange and teal, 100 pt each, at (300, 0).
let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat();
let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
s.edit("Place", |d, _| {
d.images.insert("px".into(), ImageBlob::png(png.to_vec()));
let l = d.layers[0].id;
let id = d.alloc_id();
let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0);
let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None };
d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string()))
})
.unwrap();
let m = rect(&mut s, 10.0);
s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap();
let colors = |s: &Session| match node(s, m).kind {
NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(),
k => panic!("not a mesh: {k:?}"),
};
let white = colors(&s)[0];
let v = ViewInfo::default();
let press = |s: &mut Session, i: usize, mods: Mods| {
let q = match node(s, m).kind {
NodeKind::Mesh(g) => g.points[i].p,
k => panic!("not a mesh: {k:?}"),
};
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap();
}
};
let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0));
s.execute("select.set", &json!({"ids": [m.0]})).unwrap();
s.select_tool("directSelection", v).unwrap();
press(&mut s, 0, Mods::default());
s.select_tool("eyedropper", v).unwrap();
// Cmd-click point 3: Direct Selection, lent, picks it in place of point 0.
press(&mut s, 3, Mods { cmd: true, ..Default::default() });
assert_eq!(s.tool_id(), "eyedropper");
click(&mut s, 450.0, 50.0, Mods::default());
assert_eq!(colors(&s), [white, white, white, teal], "the point the lent tool picked takes the sample");
// Cmd+Shift-click point 0 adds it to the Eyedropper's pick.
press(&mut s, 0, Mods { cmd: true, shift: true, ..Default::default() });
click(&mut s, 350.0, 50.0, Mods::default());
assert_eq!(colors(&s), [orange, white, white, orange], "both picked points take the sample");
}
/// A CMYK document with one image of `px` (one row, 100 pt a pixel) at (300, 0).
fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session {
let mut s = Session::new();
+81
View File
@@ -4109,6 +4109,17 @@ fn area_to_point_turns_wraps_into_breaks() {
assert_eq!(txt.replace('\n', " "), "one two three four five six");
}
/// Convert To Point Type keeps the lines that a paragraph return or a forced line break (U+2028)
/// starts as they are: neither gets a paragraph return added after it.
#[test]
fn area_to_point_keeps_forced_line_breaks() {
let mut s = session();
let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 0, "text": "ab\u{2028}c\nd", "area": {"width": 300, "height": 200}})).unwrap());
sel(&mut s, &[a]);
s.execute("type.convertToPointType", &json!({})).unwrap();
assert_eq!(plain(&s, a), "ab\u{2028}c\nd");
}
#[test]
fn placeholder_and_insert_characters() {
let mut s = session();
@@ -4124,6 +4135,76 @@ fn placeholder_and_insert_characters() {
assert!(s.execute("type.insert", &json!({"char": "nope"})).is_err());
}
/// Type › Insert Break Character › Forced Line Break (`type.insert {char: "forcedLineBreak"}`)
/// starts a new line in the same paragraph (U+2028, as Shift+Enter types it), so the paragraph's
/// space before does not come between the two lines; `paragraphReturn` starts a new paragraph.
/// Each insert is one undo step.
#[test]
fn insert_forced_line_break_differs_from_paragraph_return() {
fn second_line_gap(s: &Session, id: NodeId) -> f64 {
let NodeKind::Text(t) = &node(s, id).kind else { panic!("not text") };
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
assert_eq!(lay.lines.len(), 2, "{:?}", t.plain_text());
lay.lines[1].baseline - lay.lines[0].baseline
}
let mut s = session();
let mut gaps = Vec::new();
for (c, want) in [("forcedLineBreak", "ab\u{2028}c"), ("paragraphReturn", "ab\nc")] {
let t = text(&mut s, "ab");
sel(&mut s, &[t]);
s.execute("text.setFormat", &json!({"ids": [t.0], "spaceBefore": 30})).unwrap();
let steps = undo_len(&s);
s.execute("type.insert", &json!({"char": c})).unwrap();
assert_eq!(undo_len(&s), steps + 1, "{c}");
s.execute("type.insert", &json!({"text": "c"})).unwrap();
assert_eq!(plain(&s, t), want, "{c}");
gaps.push(second_line_gap(&s, t));
}
assert!(gaps[1] - gaps[0] > 29.0, "space before only at the paragraph return: {gaps:?}");
// The same character by `unicode` and by `text`.
let t = text(&mut s, "");
sel(&mut s, &[t]);
s.execute("type.insert", &json!({"unicode": "2028"})).unwrap();
s.execute("type.insert", &json!({"text": "\u{2028}"})).unwrap();
assert_eq!(plain(&s, t), "\u{2028}\u{2028}");
}
/// While the Type tool edits text, the Insert Special, Whitespace and Break menu items
/// (`type.insert` without `ids`) insert at its caret or replace its selection, as one undo step,
/// and the caret goes after the insertion; `ids` still appends to those objects.
#[test]
fn insert_character_goes_to_the_type_tool_caret() {
use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
let mut s = session();
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for k in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap();
}
let t = s.doc().unwrap().selection.objects[0];
s.tool_text("abcd", v).unwrap();
for _ in 0..2 {
s.tool_key(ToolKey::Left, Mods::default(), v).unwrap();
}
let steps = undo_len(&s);
s.execute("type.insert", &json!({"text": ""})).unwrap();
assert_eq!(undo_len(&s), steps, "an empty insert changes nothing");
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}cd");
assert_eq!(s.tool_options()["caret"], json!(5));
s.tool_text("X", v).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}Xcd");
s.tool_key(ToolKey::Left, Mods { shift: true, ..Mods::default() }, v).unwrap();
s.execute("type.insert", &json!({"char": "paragraphReturn"})).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}\ncd");
s.execute("type.insert", &json!({"ids": [t.0], "text": "!"})).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}\ncd!");
s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(plain(&s, t), "ab\u{2028}Xcd", "the replacement is one undo step");
}
/// `type.insert` by code (#5108): `code` as a Windows Alt+0 code types (Windows-1252 for
/// 128–159, the code point otherwise), `unicode` as a hex code point.
#[test]
+35
View File
@@ -2289,6 +2289,41 @@ fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, Strin
(s, a, b, story)
}
/// Type › Insert Break Character › Forced Line Break (`type.insert`) after Select All in threaded
/// text replaces the whole story, every frame's text, as one undo step.
#[test]
fn insert_character_replaces_the_whole_story_that_select_all_selected() {
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
s.execute("select.all", &json!({})).unwrap();
let steps = undo_labels(&s).len();
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step");
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), "\u{2028}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story);
}
/// When `type.insert` at the caret in the first frame of threaded text pushes the caret's place on
/// into the next frame, the Type tool's caret goes there with it, and typing goes after the
/// insertion.
#[test]
fn insert_character_moves_the_caret_with_the_text_it_flows_on() {
let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame();
let first = obj(&s, a).plain_text();
// Before the last word of the first frame: two line breaks there push the line after the
// first one on into the second frame.
let at = first.trim_end().rfind(' ').map_or(0, |k| k + 1);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": at, "caret": at}));
for _ in 0..2 {
s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap();
}
assert!(obj(&s, a).plain_text().len() < at + 6, "the second break flows on into the second frame");
s.tool_text("X", ViewInfo::default()).unwrap();
let want = format!("{}\u{2028}\u{2028}X{}", &story[..at], &story[at..]);
assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), want);
}
#[test]
fn remove_breaks_takes_the_whole_story_that_select_all_selected() {
let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame();
+23 -1
View File
@@ -173,6 +173,12 @@ impl Session {
let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id)))
.then(|| self.tool.options())
.filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end"));
// The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked
// for the Eyedropper, which samples into them (#8090), and for the tool after it.
let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper")
.then(|| self.tool.options().get("meshPoints").cloned())
.flatten()
.filter(|v| v.as_array().is_some_and(|a| !a.is_empty()));
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
self.apply_actions(acts)?;
self.keep_tool_settings();
@@ -180,6 +186,9 @@ impl Session {
if let Some(selection) = text_selection {
self.tool.set_option("textSelection", &selection);
}
if let Some(points) = mesh_points {
self.tool.set_option("meshPoints", &points);
}
if vectorcraft_tools::catalog::is_selection_tool(id) {
self.last_selection_tool = Some(self.tool.id());
self.select_whole_instance(id);
@@ -258,7 +267,13 @@ impl Session {
// The lending tool does not see the press: it counts as a press elsewhere for the clicks a
// double-click or triple-click compares.
self.tool.press_elsewhere();
let lent = self.make_tool(id);
let mut lent = self.make_tool(id);
// The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift
// click adds to (#8090).
if self.tool.id() == "eyedropper" {
let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![]));
lent.set_option("meshPoints", &points);
}
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
@@ -269,10 +284,17 @@ impl Session {
/// Cmd+click that takes the type being edited out of the selection ends its edit (#3779).
pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> {
let Some(lender) = self.lender.take() else { return Ok(()) };
// The points the lent tool left picked go back to the Eyedropper, none when it unpicked
// them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own.
let mesh_points =
(lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten();
let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx));
let r = self.apply_actions(acts);
self.keep_tool_settings();
self.tool = lender;
if let Some(points) = mesh_points {
self.tool.set_option("meshPoints", &points);
}
// A gesture that left the selection as it found it (a Shift marquee over nothing) picked
// nothing: the selection keeps what it was, the Pen's last anchor or an earlier pick.
let left = self.active().map(|d| (d.uid, d.selection.clone()));
+10
View File
@@ -1569,6 +1569,16 @@ fn headless_backend_methods() {
assert_eq!(entry["label"], "Trim at Crossings Tool");
assert!(entry["shortcut"].is_null());
assert_eq!(h.call("ui.tool.select", json!({"tool": trim})).unwrap()["tool"], trim);
// The Enclosing Lasso Tool is listed once, in the Lasso tool's group after the Lasso.
let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID;
let with_enclosing: Vec<_> =
groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == enclosing)).collect();
assert_eq!(with_enclosing.len(), 1, "{enclosing} is in one group");
let ids: Vec<_> = with_enclosing[0].iter().map(|entry| entry["id"].clone()).collect();
assert_eq!(ids, [json!("lasso"), json!(enclosing)]);
assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool");
assert!(with_enclosing[0][1]["shortcut"].is_null());
assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing);
let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso");
assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool")));
assert!(h.call("ui.resize", json!({})).is_err());
+46 -14
View File
@@ -46,12 +46,7 @@ use crate::{Imported, Kind};
const PATTERNS: &str = "hatched and pattern brushes are filled with their average color";
const ENDS_EARLY: &str = "the file ends early: what it held was imported";
const TOO_MANY: &str = "objects past the most one file may hold were left out";
const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read";
/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the
/// limit and does not say whether more items followed, so a picture holding this many may have
/// been cut short.
const READER_ITEMS: usize = 200_000;
const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read";
/// Points a unit of a WMF without a placeable header (1440 units an inch).
const WMF_UNIT: f64 = 72.0 / 1440.0;
@@ -217,6 +212,18 @@ struct Pending {
path: BezPath,
}
/// What `craft_metafile` counted as not read or not played as the file asks.
struct Lost {
/// Records of kinds it doesn't read.
skipped: u32,
/// Images, and pattern brushes (a pen's included), whose bitmap it couldn't read.
images: u32,
/// Clip changes it didn't apply as the file sets them.
clips: u32,
/// Raster operations drawn as a plain copy or left out.
rops: u32,
}
/// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for
/// one that clips nothing in the picture.
type MadeClips = HashMap<*const ClipPath, (Arc<ClipPath>, Option<Arc<Clip>>)>;
@@ -720,14 +727,38 @@ impl Mapper {
}
/// The document: what was drawn on one layer, clipped art in clipping groups.
fn finish(mut self, kind: Kind, skipped: u32) -> Imported {
fn finish(mut self, kind: Kind, lost: Lost) -> Imported {
self.flush();
if skipped > 0 {
let n = skipped;
let s = |n: u32| if n == 1 { "" } else { "s" };
let was = |n: u32| if n == 1 { "was" } else { "were" };
let n = lost.skipped;
if n > 0 {
self.warnings.push(format!("{n} record{} of kinds VectorCraft doesn't read {} skipped", s(n), was(n)));
}
let n = lost.images;
if n > 0 {
self.warnings.push(format!(
"{n} record{} of kinds VectorCraft doesn't read {} skipped",
if n == 1 { "" } else { "s" },
if n == 1 { "was" } else { "were" }
"{n} image{} or pattern brush{} that couldn't be read {} left out",
s(n),
if n == 1 { "" } else { "es" },
was(n)
));
}
let n = lost.clips;
if n > 0 {
self.warnings.push(format!(
"{n} clip{} couldn't be applied as the file sets {}: what is drawn after {} may show more or less than the file does",
s(n),
if n == 1 { "it" } else { "them" },
if n == 1 { "it" } else { "them" }
));
}
let n = lost.rops;
if n > 0 {
self.warnings.push(format!(
"{n} raster operation{} other than a plain copy (masks, inversions) {} drawn as a plain copy or left out",
s(n),
was(n)
));
}
let out = std::mem::take(&mut self.out);
@@ -981,11 +1012,12 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> {
if ends_early(bytes, kind) {
m.warn(ENDS_EARLY);
}
if pic.items.len() >= READER_ITEMS {
if pic.truncated {
m.warn(AT_LIMIT);
}
let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops };
for item in pic.items {
m.item(item);
}
Ok(m.finish(kind, pic.skipped_records))
Ok(m.finish(kind, lost))
}
+2
View File
@@ -16,6 +16,8 @@
//! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`)
//! into a document of one artboard (the picture's frame) and one layer: paths with fills and
//! strokes, clipping, images and text. Records it doesn't read are skipped, with one warning.
//! A picture cut short by a reader limit, images and pattern brushes that can't be read, clips
//! that can't be applied and raster operations other than a plain copy each add a warning.
//! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of
//! document.
//!
+90 -1
View File
@@ -527,11 +527,100 @@ fn a_file_with_more_objects_than_are_read_says_so() {
let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]);
let back = import(&many).unwrap();
assert_eq!(paths(&back.document).len(), 200_000);
assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings);
assert!(back.warnings.iter().any(|w| w.contains("reached a limit")), "{:?}", back.warnings);
// Exactly as many as the reader keeps: nothing was left unread.
let full = import(&hand_emf(5000, 3000, &vec![rect.clone(); 200_000])).unwrap();
assert_eq!(paths(&full.document).len(), 200_000);
assert!(full.warnings.is_empty(), "{:?}", full.warnings);
let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap();
assert!(few.warnings.is_empty(), "{:?}", few.warnings);
}
#[test]
fn a_file_cut_short_by_another_limit_says_so() {
// SAVEDC past the 1,024 levels the reader keeps stops the parse: the rectangle after them is
// not read.
let mut records = vec![(43, le(&[0, 0, 100, 100]))];
records.extend(vec![(33, vec![]); 1100]);
records.push((43, le(&[200, 200, 300, 300])));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(paths(&back.document).len(), 1);
assert_eq!(
back.warnings,
vec!["the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read".to_string()]
);
}
#[test]
fn images_the_reader_does_not_read_are_counted() {
let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 2];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(back.warnings, vec!["2 images or pattern brushes that couldn't be read were left out".to_string()]);
let back = import(&hand_emf(5000, 3000, &records[..1])).unwrap();
assert_eq!(back.warnings, vec!["1 image or pattern brush that couldn't be read was left out".to_string()]);
}
#[test]
fn a_wmf_reports_unread_pattern_brushes_and_raster_operations() {
let records = vec![
// DIBCREATEPATTERNBRUSH (style 5, usage 0) whose bitmap header can't be read.
(0x0142, [le16(&[5, 0]), vec![0xFF; 8]].concat()),
// A bitmap-less DIBBITBLT with DSTINVERT (0x00550009): rop, ySrc, xSrc, reserved, height,
// width, yDest, xDest.
(0x0940, le16(&[0x0009, 0x0055, 0, 0, 0, 100, 100, 0, 0])),
];
let back = import(&hand_wmf(1440, 1440, &records)).unwrap();
assert_eq!(
back.warnings,
vec![
"1 image or pattern brush that couldn't be read was left out".to_string(),
"1 raster operation other than a plain copy (masks, inversions) was drawn as a plain copy or left out".to_string(),
]
);
}
#[test]
fn clips_that_are_not_applied_are_counted() {
// BEGINPATH, a rectangle, ENDPATH, SELECTCLIPPATH with RGN_XOR (3), then a rectangle drawn after it.
let records = vec![(59, vec![]), (43, le(&[100, 100, 2000, 2000])), (60, vec![]), (67, le(&[3])), (43, le(&[500, 500, 600, 600]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(paths(&back.document).len(), 1);
assert_eq!(
back.warnings,
vec!["1 clip couldn't be applied as the file sets it: what is drawn after it may show more or less than the file does".to_string()]
);
// RGN_AND (1) is applied.
let mut records = records;
records[3] = (67, le(&[1]));
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
}
/// An EMR_BITBLT of the 100 × 100 box at the origin with `rop` and no source bitmap.
fn bitblt(rop: u32) -> Vec<u8> {
// Bounds; destination; the operation; the source origin, transform (identity) and background
// color; usage, then no BITMAPINFO and no bits.
let mut body = vec![0; 16];
body.extend(le(&[0, 0, 100, 100, rop as i32, 0, 0]));
body.extend(le_f32(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]));
body.extend(le(&[0, 0, 0, 0, 0, 0]));
body
}
#[test]
fn raster_operations_that_are_not_played_are_counted() {
// DSTINVERT and PATINVERT take no source bitmap and are left out.
let records = vec![(76, bitblt(0x0055_0009)), (76, bitblt(0x005A_0049))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert_eq!(
back.warnings,
vec!["2 raster operations other than a plain copy (masks, inversions) were drawn as a plain copy or left out".to_string()]
);
// WHITENESS is played.
let back = import(&hand_emf(5000, 3000, &[(76, bitblt(0x00FF_0062))])).unwrap();
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
}
/// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box.
fn png_stretch_dibits(png: &[u8]) -> Vec<u8> {
// Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start);
+2
View File
@@ -54,6 +54,8 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] }
serde_json = { workspace = true }
# `draw_text`, to write test files with live text as other writers do.
krilla = { workspace = true, features = ["simple-text"] }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
# An independent raster oracle for gradient placement in PDF forms. These are test-only macOS
# bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer.
+18 -15
View File
@@ -118,7 +118,7 @@ impl Exporter<'_> {
if several && !elements.iter().skip(1).all(|(c, _)| shape_is_coverage(c)) {
let doc = self.doc;
let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc));
match knockout_masks(BrushSearch::new(doc, brushes), &elements) {
match knockout_masks(BrushSearch::new(&self.symbols, brushes), &elements) {
Ok(above) => {
// Every mask is made before anything is drawn: when the symbol objects the
// masks may hold run out, one would leave out art its element covers, and
@@ -452,7 +452,7 @@ impl Exporter<'_> {
// A dynamic symbol's instance shows its own appearance changes, and the instance's
// fill stains its art, as on the canvas.
let doc = self.doc;
if let Some(sym) = doc.symbols.iter().find(|x| &x.name == symbol) {
if let Some(sym) = self.symbols.symbol(symbol) {
let changed;
let art: &Node = if n.extras().symbol_overrides.is_empty() && vectorcraft_doc::symbol_overrides::stain(n).is_none() {
&sym.art
@@ -968,8 +968,10 @@ enum SharedArt {
/// A search for the brushed strokes drawing an object draws, whose brush art can hold many more
/// objects than the stroked path.
struct BrushSearch<'a> {
doc: &'a Document,
struct BrushSearch<'a, 'd> {
doc: &'d Document,
/// `doc`'s symbols, found by name.
symbols: &'a vectorcraft_doc::SymbolBoxes<'d>,
/// The brushes the export draws strokes with ([`Exporter::brush_art`]); a stroke whose brush
/// is not among them is drawn as a plain stroke.
brushes: &'a [vectorcraft_brush::Brush],
@@ -983,9 +985,10 @@ struct BrushSearch<'a> {
exhausted: bool,
}
impl<'a> BrushSearch<'a> {
fn new(doc: &'a Document, brushes: &'a [vectorcraft_brush::Brush]) -> Self {
Self { doc, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false }
impl<'a, 'd> BrushSearch<'a, 'd> {
/// A search through the document of `symbols`.
fn new(symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, brushes: &'a [vectorcraft_brush::Brush]) -> Self {
Self { doc: symbols.document(), symbols, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false }
}
/// Takes `n` objects from [`Self::left`]; false, and the search exhausted, when fewer are left.
@@ -1046,8 +1049,7 @@ impl<'a> BrushSearch<'a> {
NodeKind::SymbolInstance { symbol, .. } => {
// A dynamic symbol's instance draws its art with its own appearance changes: the
// art is copied once for each set of changes, counted before it is copied.
let doc = self.doc;
match doc.symbols.iter().find(|s| &s.name == symbol) {
match self.symbols.symbol(symbol) {
Some(s) if !n.extras().symbol_overrides.is_empty() => {
let key = format!("{symbol}\u{0}{:?}", n.extras().symbol_overrides);
self.shared(SharedArt::Dynamic, &key, |search| {
@@ -1080,8 +1082,7 @@ impl<'a> BrushSearch<'a> {
/// Whether the art of the symbol named `name` draws a brushed stroke.
fn symbol(&mut self, name: &str, depth: usize) -> bool {
let doc = self.doc;
let Some(s) = doc.symbols.iter().find(|s| s.name == name) else { return false };
let Some(s) = self.symbols.symbol(name) else { return false };
self.shared(SharedArt::Symbol, name, |search| search.node(&s.art, true, depth))
}
@@ -1177,7 +1178,8 @@ mod tests {
let square = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0));
let art = Node::group(NodeId(0), vec![Arc::new(square), Arc::new(instance())]);
d.symbols.push(Symbol { dynamic: true, name: "Loop".into(), art: Arc::new(art) });
let mut search = BrushSearch::new(&d, &[]);
let symbols = d.symbol_boxes();
let mut search = BrushSearch::new(&symbols, &[]);
assert!(!search.node(&instance(), true, 0));
assert!(!search.exhausted);
assert!(MAX_KNOCKOUT_MASK_OBJECTS - search.left < 10, "{} objects", MAX_KNOCKOUT_MASK_OBJECTS - search.left);
@@ -1205,11 +1207,12 @@ mod tests {
.collect();
Node::group(NodeId(0), instances)
};
let mut search = BrushSearch::new(&d, &[]);
let symbols = d.symbol_boxes();
let mut search = BrushSearch::new(&symbols, &[]);
assert!(search.node(&group(true), true, 0));
assert!(search.exhausted);
assert_eq!(search.left, 0);
let mut search = BrushSearch::new(&d, &[]);
let mut search = BrushSearch::new(&symbols, &[]);
assert!(!search.node(&group(false), true, 0));
assert!(!search.exhausted);
// The group, the 1,000 instances, and one copy of the art counted and looked through.
@@ -1247,6 +1250,6 @@ mod tests {
vectorcraft_doc::placed_document::prime(&placed, Arc::new(vec![]), brushed_art());
let n = Node::new(NodeId(0), NodeKind::PlacedDocument(Box::new(placed)));
let brushes = vectorcraft_brush::library(&d);
assert!(BrushSearch::new(&d, &brushes).node(&n, true, 0));
assert!(BrushSearch::new(&d.symbol_boxes(), &brushes).node(&n, true, 0));
}
}
+1 -1
View File
@@ -134,7 +134,7 @@ impl Exporter<'_> {
self.inline_depth += 1;
for ig in &layout.inlines {
let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue };
let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue };
let Some(sym) = self.symbols.symbol(&art.symbol) else { continue };
let mut node = (*sym.art).clone();
// Strokes scale with the art, as on the canvas.
node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true);
+22 -10
View File
@@ -1,6 +1,6 @@
use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY};
use super::state::{
Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgba_png, same_outline,
Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline,
stroke_layer, stroke_outline,
};
use super::{
@@ -304,27 +304,39 @@ impl<'a> Device<'a> for Builder<'_> {
self.add_image(key, || None, xf);
return;
}
let mut decoded: Option<Decoded> = None;
// RGB samples, or RGBA when the image has an alpha channel or is drawn white.
let mut decoded: Option<(Decoded, bool)> = None;
r.with_rgba(
|img, alpha| {
let (w, h, sf) = (img.width(), img.height(), img.scale_factors());
let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]);
let rgba: Vec<u8> = match img {
_ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(),
ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(),
ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(),
let px = match (img, alpha) {
// An opaque image's RGB samples are encoded as they are, with no copy.
(ImageData::Rgb(d), None) if !white => (d.data, false),
// Gray samples are stored as RGB: as a gray PNG, the image would become a
// grayscale image that a fill color colorizes.
(ImageData::Luma(d), None) if !white => (d.data.iter().flat_map(|g| [*g; 3]).collect(), false),
(img, alpha) => {
let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]);
let rgba: Vec<u8> = match img {
_ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(),
ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(),
ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(),
};
(rgba, true)
}
};
decoded = Some((rgba, w, h, sf));
decoded = Some(((px.0, w, h, sf), px.1));
},
None,
);
let Some((rgba, w, h, sf)) = decoded else {
let Some(((px, w, h, sf), alpha)) = decoded else {
self.warn("an image could not be decoded and was skipped");
return;
};
self.raster_scales.insert(key, sf);
let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64);
self.add_image(key, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf);
let png = move || if alpha { rgba_png(px, w, h) } else { rgb_png(px, w, h) };
self.add_image(key, || png().map(|png| (ImageBlob::new("image/png", png), w, h)), xf);
}
Image::Stencil(s) => {
let white = self.white_images;
+5
View File
@@ -340,6 +340,11 @@ pub(super) fn rgba_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
pub(super) fn rgb_png(rgb: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?;
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
}
pub(super) fn gray_png(gray: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> {
let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?;
craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()
+7 -4
View File
@@ -215,7 +215,7 @@ fn stream_kind(pdf: &Pdf, id: ObjectIdentifier, dict: &Dict<'_>) -> String {
}
/// `bytes` for a message, in whole megabytes, or gigabytes when it is a whole number of them.
fn decoded_size(bytes: usize) -> String {
pub(crate) fn decoded_size(bytes: usize) -> String {
const GB: usize = 1 << 30;
if bytes >= GB && bytes.is_multiple_of(GB) { format!("{} GB", bytes / GB) } else { format!("{} MB", bytes >> 20) }
}
@@ -323,10 +323,13 @@ pub struct TrimPages {
pub bleed: [f64; 4],
}
/// Preserve the application's existing accepted file sizes. Ordinary stream decoding still
/// uses the shared reader's immutable per-document limits, and its input copy is fallible.
/// The shared reader's options: files of any size are accepted. Ordinary stream decoding uses the shared reader's immutable per-document limits, and its input
/// copy is fallible. One image may decode to the bytes and pixels of
/// [`crate::streams::image_limits`] for this build, past the shared reader's defaults.
pub(crate) fn open_options() -> craft_pdf::OpenOptions {
craft_pdf::OpenOptions { max_input_bytes: usize::MAX, ..Default::default() }
let (bytes, pixels) = crate::streams::image_limits(crate::streams::LARGE_IMAGES);
let decode_limits = craft_pdf::syntax::DecodeLimits::default().with_max_decoded_image(bytes).with_max_image_pixels(pixels);
craft_pdf::OpenOptions { max_input_bytes: usize::MAX, decode_limits }
}
pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: &craft_pdf::OpenOptions) -> Result<Pdf, PdfError> {
+98 -16
View File
@@ -15,9 +15,21 @@ use craft_pdf::syntax::object::{Array, Dict, FromBytes, MaybeRef, Name, Object,
/// million, 4 bytes each).
pub(crate) const MAX_DECODED: usize = 256 << 20;
/// Whether this build reads the larger images of [`image_limits`]: a 64-bit build that isn't for
/// the web.
pub(crate) const LARGE_IMAGES: bool = cfg!(all(target_pointer_width = "64", not(target_family = "wasm")));
/// The most bytes one image XObject may decode to and the most pixels it may have, for a build
/// that reads `large` images: 4 GiB and 2^30 pixels (31404 × 31403 pixels are 2.76 GiB in RGB and
/// 3.67 GiB in CMYK), otherwise 1 GiB and 2^28 pixels (an A0 sheet scanned at 300 ppi is 399 MiB
/// in RGB and 532 MiB in CMYK). The shared reader takes the same two figures ([`crate::pages::open_options`]).
pub(crate) const fn image_limits(large: bool) -> (u64, u64) {
if large { (1 << 32, 1 << 30) } else { (1 << 30, 1 << 28) }
}
/// The most an image XObject may decode to when its own size asks for more than
/// [`MAX_DECODED`]: 1 GB (an A0 sheet scanned at 300 ppi is 418 MB in RGB, 557 MB in CMYK).
const MAX_IMAGE_DECODED: usize = 1 << 30;
/// [`MAX_DECODED`]: the bytes of [`image_limits`] for this build.
const MAX_IMAGE_DECODED: usize = image_limits(LARGE_IMAGES).0 as usize;
/// The longest row a predictor may have, in bytes.
const MAX_ROW: usize = 1 << 24;
@@ -779,31 +791,42 @@ mod tests {
/// A one-page PDF drawing one flat 8-bit DeviceRGB image of `w` × `h` pixels, Flate-compressed.
fn one_image_pdf(w: usize, h: usize) -> Vec<u8> {
image_pdf(&format!("/Width {w} /Height {h} /ColorSpace /DeviceRGB"), &flat(&[200, 180, 150].repeat(w), h), None)
}
/// `row` repeated `h` times, Flate-compressed as it is written.
fn flat(row: &[u8], h: usize) -> Vec<u8> {
let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
let row: Vec<u8> = [200, 180, 150].repeat(w);
for _ in 0..h {
std::io::Write::write_all(&mut e, &row).unwrap();
std::io::Write::write_all(&mut e, row).unwrap();
}
let image = e.finish().unwrap();
e.finish().unwrap()
}
/// A one-page PDF drawing one 8-bit image with the size and color space of `keys` and the
/// Flate-compressed samples `data`; with `smask`, a soft mask with those keys and data.
fn image_pdf(keys: &str, data: &[u8], smask: Option<(&str, &[u8])>) -> Vec<u8> {
let stream = |keys: &str, data: &[u8]| {
let dict =
format!("<< /Type /XObject /Subtype /Image {keys} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", data.len());
[dict.as_bytes(), data, b"\nendstream"].concat()
};
let content = b"q 595 0 0 842 0 0 cm /Im0 Do Q";
let mut out = b"%PDF-1.6\n".to_vec();
let mut offsets = vec![];
let objects: Vec<Vec<u8>> = vec![
let mut objects: Vec<Vec<u8>> = vec![
b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>".to_vec(),
[format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content, b"\nendstream"].concat(),
[
format!(
"<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n",
image.len()
)
.as_bytes(),
&image,
b"\nendstream",
]
.concat(),
];
match smask {
Some((mask_keys, mask_data)) => {
objects.push(stream(&format!("{keys} /SMask 6 0 R"), data));
objects.push(stream(mask_keys, mask_data));
}
None => objects.push(stream(keys, data)),
}
for (i, o) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
@@ -828,6 +851,65 @@ mod tests {
assert_eq!(info.map(|i| i.pages.len()).unwrap(), 1);
}
#[test]
fn a_64_bit_desktop_build_reads_larger_images_and_others_keep_their_limits() {
assert_eq!(image_limits(false), (1 << 30, 1 << 28));
assert_eq!(image_limits(true), (1 << 32, 1 << 30));
let (bytes, pixels) = image_limits(LARGE_IMAGES);
assert_eq!(MAX_IMAGE_DECODED as u64, bytes);
let limits = crate::pages::open_options().decode_limits;
assert_eq!((limits.max_decoded_image(), limits.max_image_pixels()), (bytes, pixels));
// An image declaring more is held to this build's limit, which a refusal of it names.
let d = dict("<< /Subtype /Image /Width 70000 /Height 70000 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode >>");
assert_eq!(budget(&d), MAX_IMAGE_DECODED);
let most = if LARGE_IMAGES { "4 GB" } else { "1 GB" };
assert_eq!(crate::pages::decoded_size(MAX_IMAGE_DECODED), most);
}
/// The only image of `doc`, as stored: its width, height and channel layout.
fn stored_image(doc: &vectorcraft_doc::Document) -> (u32, u32, image::ExtendedColorType) {
use image::ImageDecoder as _;
let blobs: Vec<_> = doc.images.values().collect();
let [blob] = blobs[..] else { panic!("one image expected, found {}", blobs.len()) };
let decoder = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().unwrap().into_decoder().unwrap();
let (w, h) = decoder.dimensions();
(w, h, decoder.original_color_type())
}
#[test]
fn an_image_past_1_gb_and_2_to_the_28_pixels_opens_on_a_64_bit_desktop_build() {
if !LARGE_IMAGES {
return;
}
// 18919 × 18919 RGB pixels: 358 million pixels, 1.07 GB decoded (#4366).
let side = 18919;
let doc = crate::import(&one_image_pdf(side, side)).unwrap();
// Opaque: stored as RGB, without an alpha channel.
assert_eq!(stored_image(&doc), (side as u32, side as u32, image::ExtendedColorType::Rgb8));
}
#[test]
fn opaque_images_are_stored_without_an_alpha_channel_and_masked_ones_with_one() {
let rgb = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), None);
assert_eq!(stored_image(&crate::import(&rgb).unwrap()), (4, 2, image::ExtendedColorType::Rgb8));
let gray = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[120; 4], 2), None);
assert_eq!(stored_image(&crate::import(&gray).unwrap()), (4, 2, image::ExtendedColorType::Rgb8));
let mask = ("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[0, 85, 170, 255], 2)[..]);
let masked = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), Some(mask));
assert_eq!(stored_image(&crate::import(&masked).unwrap()), (4, 2, image::ExtendedColorType::Rgba8));
}
#[test]
fn an_image_of_more_pixels_than_the_limit_is_left_out_with_a_warning() {
let (_, pixels) = image_limits(LARGE_IMAGES);
// One more row than a square of the limit's pixels; its data isn't looked at.
let side = 1u64 << (pixels.ilog2() / 2);
let pdf = image_pdf(&format!("/Width {side} /Height {} /ColorSpace /DeviceGray", side + 1), &flat(&[0; 16], 1), None);
let report = crate::import_with_report(&pdf, &crate::ImportOptions::default()).unwrap();
assert!(report.document.images.is_empty());
assert!(report.warnings.iter().any(|w| w.contains("an image could not be decoded and was skipped")), "{:?}", report.warnings);
}
#[test]
fn object_and_cross_reference_streams_are_looked_at_before_the_file_is_read() {
let stream = |dict: &str, data: &[u8]| {
+54
View File
@@ -223,6 +223,60 @@ fn an_instance_whose_art_reaches_the_page_is_written() {
assert!(fills.contains(&[255, 0, 0, 255]) && fills.contains(&[0, 0, 255, 255]), "{fills:?}");
}
/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), with an instance of
/// "Mark" at (25, 25) and, in a knockout group above a green square, a half-opaque one at (70, 70).
/// With `second` the blue square's symbol is named that instead.
fn marks(second: &str) -> Document {
let mut d = doc(100.0, 100.0);
for i in 0..2000 {
let art = rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), Color::BLACK);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
}
for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] {
let art = rect_node(Rect::new(-10.0, -10.0, 10.0, 10.0), color);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) }));
let green = rect_node(Rect::new(60.0, 60.0, 80.0, 80.0), Color::rgb(0.0, 1.0, 0.0));
let mut above = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) });
above.opacity = 0.5;
let mut group = Node::group(NodeId(0), vec![Arc::new(green), Arc::new(above)]);
group.knockout = vectorcraft_doc::Knockout::On;
add(&mut d, group);
d
}
/// Instances among many symbols are written with the first symbol of their name, the same bytes
/// as when no other symbol has that name.
#[test]
fn instances_are_written_with_the_first_symbol_of_their_name() {
let d = marks("Mark");
assert!(uncompressed(&d) == uncompressed(&marks("Other")), "the files differ");
let fills: Vec<[u8; 4]> = leaves(&roundtrip(&d)).iter().filter_map(|n| Some(n.appearance.fill_paint().color()?.to_rgba8(1.0))).collect();
assert!(fills.contains(&[255, 0, 0, 255]) && !fills.contains(&[0, 0, 255, 255]), "{fills:?}");
}
/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once
/// to find their symbols.
#[test]
fn an_export_reads_the_symbol_list_once() {
let mut d = marks("Other");
for i in 0..300 {
let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2);
let mut n = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
add(&mut d, n);
}
let before = vectorcraft_doc::symbols_read();
export(&d, &PdfOptions::default()).expect("export");
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
}
#[test]
fn an_instance_whose_brush_art_reaches_the_page_is_written() {
// The symbol's art: a line from (0, 40) to (0, 60) with a 1 pt stroke painted by a 20 pt round
+2
View File
@@ -51,3 +51,5 @@ craft-tiff = { workspace = true }
craft-psd = { workspace = true }
proptest = { workspace = true }
serde_json = { workspace = true }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
+1 -1
View File
@@ -57,7 +57,7 @@ pub fn sample(doc: &Document, nodes: Vec<Node>, region: Rect, scale: f64, mono:
/// take too many cells: `n` then draws as it is.
pub fn art(doc: &Document, n: &Node) -> Option<Node> {
let ht = Halftone::of(n)?;
let found = Renderer::new().live_found(doc, &Arc::new(n.clone()));
let found = Renderer::new().live_found(&doc.symbol_boxes(), &Arc::new(n.clone()));
let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(at) = cache.iter().position(|(node, was, _)| was.0 == found.0 && node == n) {
let kept = cache.remove(at);
+8 -2
View File
@@ -6,7 +6,13 @@ use super::{BezPath, Document, FillRule, Node, NodeKind, Rect, SymbolBoxes, brus
/// geometry effects, and the shadows and glows of it and its members. Symbol instances are
/// measured by their art in `doc` ([`Node::visual_bounds_with`]).
pub fn painted_bounds(doc: &Document, n: &Node) -> Option<Rect> {
brush_fx::cull_bounds(&doc.symbol_boxes(), n)
painted_bounds_with(&doc.symbol_boxes(), n)
}
/// [`painted_bounds`] with symbol instances measured by their art in `symbols` (made with
/// [`Document::symbol_boxes`]).
pub fn painted_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
brush_fx::cull_bounds(symbols, n)
}
/// [`painted_bounds`] of `n` without the room it leaves for brush art past the brushed strokes of
@@ -70,7 +76,7 @@ pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Vec<vectorcraf
/// The outline, with `n`'s geometry effects applied, that the canvas clips `n`'s Rasterize with
/// Create Clipping Mask to. Object › Rasterize's clipping mask follows it.
pub fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> {
fx::drawn_outline(doc, n)
fx::drawn_outline(&doc.symbol_boxes(), n)
}
/// The outlines a drag draws for `nodes` with Real-time Drawing off: one for each object in them,
+11 -13
View File
@@ -397,9 +397,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
// effects in a symbol's art and a live object's content paint past it.
_ if has_object_fx(n) => {
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => {
symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n))
}
NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)),
_ => None,
};
let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref());
@@ -466,7 +464,7 @@ fn pieces_within(symbols: &SymbolBoxes, art: &Node, depth: usize, budget: &mut u
NodeKind::Path { .. } | NodeKind::Compound { .. } if has_fx(art) => visual_bounds(symbols, art),
NodeKind::SymbolInstance { symbol, .. } if depth < vectorcraft_doc::depth::MAX_DEPTH && has_instance_row_effects(art) => {
let doc = symbols.document();
let reshaped = doc.symbols.iter().find(|s| s.name == *symbol).and_then(|s| {
let reshaped = symbols.symbol(symbol).and_then(|s| {
let count = s.art.count() as u64;
if count > *budget {
return None;
@@ -501,13 +499,15 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
/// The outline the renderer clips `n`'s Feather, Inner Glow and Rasterize with Create Clipping
/// Mask to: a path's or compound path's geometry with its object-level geometry effects applied,
/// the outline of the art [`Renderer::fx_art`] makes for an object with object effects, and with
/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`].
pub(crate) fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> {
/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. The symbols of
/// instances are found in `symbols`.
pub(crate) fn drawn_outline(symbols: &SymbolBoxes, n: &Node) -> Option<(BezPath, FillRule)> {
let doc = symbols.document();
if let Some(art) = effects::crop_marks_art(n) {
return drawn_outline(doc, art.children()?.first()?);
return drawn_outline(symbols, art.children()?.first()?);
}
if has_object_fx(n) {
let art = Renderer::new().fx_art(doc, &Arc::new(n.clone()), false);
let art = Renderer::new().fx_art(symbols, &Arc::new(n.clone()), false);
return effects::clip_outline(&art);
}
match &n.kind {
@@ -545,7 +545,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le
if is_container(n) && !makes_art && !effects::has_item_geometry(n) {
object.appearance.items.clear();
}
let art = Renderer::new().fx_art(doc, &Arc::new(object), false);
let art = Renderer::new().fx_art(symbols, &Arc::new(object), false);
if art.children().is_some() && !has_object_fx(&art) {
return evaluated_outlines(doc, symbols, &art, left, out);
}
@@ -570,7 +570,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le
NodeKind::SymbolInstance { .. } => {
push_outline(n.geometric_bounds_with(symbols).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()), left, out)
}
_ => push_outline(drawn_outline(doc, n).map(|(path, _)| path), left, out),
_ => push_outline(drawn_outline(symbols, n).map(|(path, _)| path), left, out),
}
}
@@ -690,9 +690,7 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b
// symbol instance's art paint past that art.
_ if has_object_fx(n) => {
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } => {
symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n))
}
NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)),
_ => None,
};
let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref());
+18 -19
View File
@@ -481,7 +481,7 @@ impl Renderer {
/// What [`Self::draw_object_fx`] draws inside the object's transparency group.
fn draw_object_fx_art(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>, cache: bool) {
if !self.charge_fx_instance(f.doc, a) {
if !self.charge_fx_instance(f.symbols, a) {
return;
}
// A path whose Transform effects after its Rasterize effect hold options that reach its
@@ -493,7 +493,7 @@ impl Renderer {
{
return self.draw_staged(ctx, f, stage, &bp, *rule);
}
let art = self.fx_art(f.doc, a, cache);
let art = self.fx_art(f.symbols, a, cache);
// Art the cache did not keep is made again in the next frame.
let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art));
let outer = self.made_again;
@@ -545,9 +545,9 @@ impl Renderer {
/// frame's symbol budget as an instance without effects is (`draw_node`): an instance whose
/// effects reshape its art draws through here, and nested instances would otherwise expand
/// without a limit. True for any other object.
pub(crate) fn charge_fx_instance(&mut self, doc: &vectorcraft_doc::Document, a: &Node) -> bool {
pub(crate) fn charge_fx_instance(&mut self, symbols: &SymbolBoxes, a: &Node) -> bool {
let NodeKind::SymbolInstance { symbol, .. } = &a.kind else { return true };
let count = doc.symbols.iter().find(|s| &s.name == symbol).map_or(0, |s| s.art.count() as u64);
let count = symbols.symbol(symbol).map_or(0, |s| s.art.count() as u64);
let mut used = self.symbol_nodes;
let room = vectorcraft_doc::charge_symbol_art(&mut used, count, || ((), count)).is_some();
self.symbol_nodes = used;
@@ -562,7 +562,7 @@ impl Renderer {
/// is made from live objects it evaluated ([`evaluates_live`]), or from type, symbol art or
/// colors shaded through the color settings ([`reads_outside`]), is kept only while what it
/// reads from outside `a` stays the same ([`Self::live_found`]).
pub(super) fn fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>, cache: bool) -> Arc<Node> {
pub(super) fn fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Arc<Node> {
let key = Arc::as_ptr(a) as usize;
let mut kept = None;
if cache
@@ -574,7 +574,7 @@ impl Renderer {
Some(was) => kept = Some((art.clone(), was.0)),
}
}
let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(doc, a));
let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(symbols, a));
if let Some((art, was)) = kept
&& found.as_ref().is_some_and(|f| f.0 == was)
{
@@ -590,11 +590,11 @@ impl Renderer {
Some((art, was)) => {
let now = match &found {
Some(f) => Some(f.0),
None => self.outside_key(doc, a),
None => self.outside_key(symbols, a),
};
if was == now { art } else { self.make_fx_art(doc, a) }
if was == now { art } else { self.make_fx_art(symbols, a) }
}
None => self.make_fx_art(doc, a),
None => self.make_fx_art(symbols, a),
};
if cache {
let bytes = crate::lru::node_bytes(&art);
@@ -607,24 +607,24 @@ impl Renderer {
/// held until the frame ends ([`Renderer::measured`]), for [`Self::fx_art`] to keep if `a` is
/// drawn. What is measured but never drawn (culled, off the view) is let go, and isn't kept in
/// place of what is drawn.
pub(crate) fn measured_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> {
pub(crate) fn measured_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> {
let key = Arc::as_ptr(a) as usize;
if let Some((node, art, found)) = self.fx_arts.get(&key, self.stamp)
&& Arc::ptr_eq(node, a)
{
let (art, was) = (art.clone(), found.as_ref().map(|f| f.0));
if was.is_none_or(|was| self.live_found(doc, a).0 == was) {
if was.is_none_or(|was| self.live_found(symbols, a).0 == was) {
return art;
}
}
let now = self.outside_key(doc, a);
let now = self.outside_key(symbols, a);
if let Some((node, art, was)) = self.measured.get(&key)
&& Arc::ptr_eq(node, a)
&& *was == now
{
return art.clone();
}
let art = self.make_fx_art(doc, a);
let art = self.make_fx_art(symbols, a);
// Art held for an object before (made from what it read then) gives way.
if let Some(old) = self.measured.remove(&key) {
self.measured_bytes = self.measured_bytes.saturating_sub(crate::lru::node_bytes(&old.1));
@@ -657,18 +657,17 @@ impl Renderer {
/// The key of what `a`'s art reads from outside it ([`Self::live_found`]), `None` when it reads
/// nothing.
fn outside_key(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Option<u64> {
(evaluates_live(a) || reads_outside(a)).then(|| self.live_found(doc, a).0)
fn outside_key(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<u64> {
(evaluates_live(a) || reads_outside(a)).then(|| self.live_found(symbols, a).0)
}
/// The art [`Self::fx_art`] draws for `a`, made now.
fn make_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> {
fn make_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> {
let doc = symbols.document();
// Whether the art is a 3D effect's ([`Self::three_d_art_bounds`]).
let mut three_d = false;
let symbol = match &a.kind {
NodeKind::SymbolInstance { symbol, .. } => {
doc.symbols.iter().find(|s| s.name == *symbol).map(|s| crate::brush_fx::instance_art(&s.art, a))
}
NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)),
_ => None,
};
let container = is_container(a);
+4 -4
View File
@@ -1066,7 +1066,7 @@ fn a_measuring_pass_sweeps_the_bounds_of_held_art_as_they_double() {
}
let mut r = Renderer::new();
// Held here, as the art kept to draw is.
let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d, n)).collect();
let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d.symbol_boxes(), n)).collect();
assert_eq!((held.len(), r.three_d_bounds.len()), (3000, 3000));
assert!(r.three_d_sweeps <= 2, "{} sweeps", r.three_d_sweeps);
}
@@ -1193,7 +1193,7 @@ fn drawing_takes_measured_art_out_of_the_budget() {
let mut r = Renderer::new();
r.bounds_of(&d.symbol_boxes(), &n);
assert!(r.measured_bytes > 0);
r.fx_art(&d, &n, true);
r.fx_art(&d.symbol_boxes(), &n, true);
assert_eq!((r.measured_bytes, r.measured.len()), (0, 0), "taken out when drawn");
let mut r = Renderer::new();
r.render(&d, 800, 100, Affine::IDENTITY, &RenderOptions::default());
@@ -1343,11 +1343,11 @@ fn art_measured_again_takes_the_place_of_the_held() {
let n = d.layers[0].children().unwrap()[0].clone();
let key = Arc::as_ptr(&n) as usize;
let mut r = Renderer::new();
let art = r.measured_fx_art(&d, &n);
let art = r.measured_fx_art(&d.symbol_boxes(), &n);
let bytes = r.measured_bytes;
// As if it had read something else then.
r.measured.insert(key, (n.clone(), art, Some(7)));
r.measured_fx_art(&d, &n);
r.measured_fx_art(&d.symbol_boxes(), &n);
assert_eq!((r.measured_bytes, r.measured.len()), (bytes, 1));
}
+1 -1
View File
@@ -285,7 +285,7 @@ mod renderer;
mod text_geom;
mod threads;
pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, rasterize_stage};
pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage};
pub use frame::FrameStats;
use frame::{
ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey,
+30 -22
View File
@@ -21,7 +21,7 @@ use std::sync::{Arc, Weak};
use vectorcraft_doc::live::{GradientMesh, MeshQuad};
use vectorcraft_doc::placed_document::ReadDocument;
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes};
use vectorcraft_geom::{Affine, BezPath, Point, Vec2};
use vello_cpu::RenderContext;
use vello_cpu::peniko;
@@ -109,10 +109,11 @@ pub fn expand_live(n: &Node) -> Vec<Node> {
/// their address). Art is hashed by the addresses of its `Arc`s, which copies of the document
/// share: a copy of the document has the same key. It also returns weak references to the reads
/// found, and what the walk found ([`Walked`]) when it found no placed file and no such image.
fn resources_key(doc: &Document, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) {
/// Symbols are found by name in `symbols`.
fn resources_key(symbols: &SymbolBoxes, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) {
let mut h = DefaultHasher::new();
let mut shown = Shown::default();
hash_resources(doc, n, &mut shown, &mut h);
hash_resources(symbols, n, &mut shown, &mut h);
let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins };
(walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked))
}
@@ -175,8 +176,9 @@ struct Shown {
/// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and
/// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern
/// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads,
/// such images and plug-in effects found.
fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) {
/// such images and plug-in effects found. Symbols are found by name in `symbols`.
fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) {
let doc = symbols.document();
let mut todo = vec![];
let mut next = Some(n);
while let Some(art) = next {
@@ -198,7 +200,7 @@ fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut
}
match &c.kind {
NodeKind::SymbolInstance { symbol, .. } => {
if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) {
if let Some(s) = symbols.symbol(symbol) {
(Arc::as_ptr(&s.art) as usize).hash(h);
if first_seen(&mut shown.seen, Arc::as_ptr(&s.art) as usize) {
todo.push(&s.art);
@@ -462,14 +464,14 @@ fn spread_to_edges(px: &mut [vello_cpu::color::PremulRgba8], filled: Vec<bool>,
}
impl Renderer {
/// The [`resources_key`] of `n` in `doc`, with the frame's [`DocInputs`] ([`Found`]): `n` is a
/// live node, or an object with effects whose art ([`Renderer::fx_art`]) can be made from
/// evaluated live objects, type, symbol art or colors shaded through the color settings. The
/// key is made from the [`Walk`] kept for `n` while `doc`'s symbols and patterns are those it
/// read; `n` is walked again when they changed, and in every frame when the walk found a
/// placed file or an image whose own fills or strokes follow its pixels.
pub(crate) fn live_found(&mut self, doc: &Document, n: &Arc<Node>) -> Found {
let inputs = self.doc_inputs(doc);
/// The [`resources_key`] of `n` in the document of `symbols`, with the frame's [`DocInputs`]
/// ([`Found`]): `n` is a live node, or an object with effects whose art ([`Renderer::fx_art`])
/// can be made from evaluated live objects, type, symbol art or colors shaded through the color
/// settings. The key is made from the [`Walk`] kept for `n` while the document's symbols and
/// patterns are those it read; `n` is walked again when they changed, and in every frame when
/// the walk found a placed file or an image whose own fills or strokes follow its pixels.
pub(crate) fn live_found(&mut self, symbols: &SymbolBoxes, n: &Arc<Node>) -> Found {
let inputs = self.doc_inputs(symbols.document());
let at = Arc::as_ptr(n) as usize;
if let Some((node, walked, read)) = self.live.walks.get(&at, self.stamp)
&& std::ptr::eq(node.as_ptr(), Arc::as_ptr(n))
@@ -481,7 +483,7 @@ impl Renderer {
{
self.live.walked += 1;
}
let (key, reads, walked) = resources_key(doc, inputs.cms, inputs.names, n);
let (key, reads, walked) = resources_key(symbols, inputs.cms, inputs.names, n);
if let Some(walked) = walked {
// The bytes count the key and the entry, and the node's allocation that the weak
// reference keeps.
@@ -491,11 +493,12 @@ impl Renderer {
(key, inputs, reads)
}
fn live_expanded(&mut self, doc: &Document, a: &Arc<Node>, cache: bool) -> Expanded {
fn live_expanded(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Expanded {
let doc = symbols.document();
let key = Arc::as_ptr(a) as usize;
// An evaluation the cache does not keep is made without the key, so the copy that
// `draw_live_node` makes is not walked.
let resources = cache.then(|| self.live_found(doc, a));
let resources = cache.then(|| self.live_found(symbols, a));
if let Some(resources) = &resources
&& let Some(e) = self.live.expanded.get(&key, self.stamp)
&& Arc::ptr_eq(&e.0, a)
@@ -550,7 +553,7 @@ impl Renderer {
let knockout = !f.opts.outline
&& matches!(a.kind, NodeKind::Blend { .. })
&& a.knockout.resolve(self.knockout)
&& vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.doc, a, true));
&& vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.symbols, a, true));
let enclosing = std::mem::replace(&mut self.knockout, knockout);
if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) {
let blends = self.blends_through(a);
@@ -575,7 +578,7 @@ impl Renderer {
| NodeKind::Intertwine { .. }
| NodeKind::Group { .. }
| NodeKind::Layer { .. } => {
let items = self.live_expanded(f.doc, a, cache);
let items = self.live_expanded(f.symbols, a, cache);
// An evaluation the cache did not keep is made again in the next frame.
let kept = cache && self.live.expanded.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &items));
let outer = self.made_again;
@@ -818,7 +821,12 @@ mod tests {
let envelope = Node::new(d.alloc_id(), envelope);
let key = |d: &Document| {
std::thread::scope(|s| {
std::thread::Builder::new().stack_size(256 << 10).spawn_scoped(s, || resources_key(d, 0, 0, &envelope).0).unwrap().join().unwrap()
std::thread::Builder::new()
.stack_size(256 << 10)
.spawn_scoped(s, || resources_key(&d.symbol_boxes(), 0, 0, &envelope).0)
.unwrap()
.join()
.unwrap()
})
};
let before = key(&d);
@@ -850,8 +858,8 @@ mod tests {
frame: Box::new(Affine::IDENTITY),
};
let envelope = Node::new(d.alloc_id(), envelope);
let before = resources_key(&d, 0, 0, &envelope).0;
let before = resources_key(&d.symbol_boxes(), 0, 0, &envelope).0;
d.symbols[2].art = y.clone();
assert_ne!(resources_key(&d, 0, 0, &envelope).0, before, "the art of every instance is hashed");
assert_ne!(resources_key(&d.symbol_boxes(), 0, 0, &envelope).0, before, "the art of every instance is hashed");
}
}
+2 -2
View File
@@ -36,7 +36,7 @@ impl Renderer {
// drawn otherwise, measured as below.
_ if measures_three_d(a)
&& let Some(b) = {
let art = self.measured_fx_art(symbols.document(), a);
let art = self.measured_fx_art(symbols, a);
self.three_d_art_bounds(symbols, &art)
} =>
{
@@ -578,7 +578,7 @@ impl Renderer {
self.draw_image_in(ctx, f, &f.doc.shown_image(n, im), None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated)
}
NodeKind::SymbolInstance { symbol, xf } => {
if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) {
if let Some(sym) = f.symbols.symbol(symbol) {
// The instance draws when the frame has room for its art's objects; a symbol
// with 9-slice guides is placed cell by cell (`Self::sliced_art`).
let mut used = self.symbol_nodes;
+2 -2
View File
@@ -32,14 +32,14 @@ impl Renderer {
return;
}
for r in t.runs.iter().filter_map(|r| r.inline.as_ref()) {
if !f.doc.symbols.iter().any(|s| s.name == r.symbol) && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) {
if f.symbols.symbol(&r.symbol).is_none() && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) {
log::warn!("inline graphic shows symbol {:?}, which the document doesn't have: it draws nothing", r.symbol);
}
}
self.inline_depth += 1;
for ig in &g.inlines {
let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue };
let Some(sym) = f.doc.symbols.iter().find(|s| s.name == art.symbol) else { continue };
let Some(sym) = f.symbols.symbol(&art.symbol) else { continue };
// Strokes scale with the art (it is sized to the type, as in the SVG `<use>`).
let (node, kept) = self.placed_art(&sym.art, t.xf * ig.xf * f.doc.symbol_natural_xf(&art.symbol), true, None);
self.draw_placed_art(ctx, f, &node, kept);
+70
View File
@@ -314,6 +314,76 @@ fn past_the_measured_placements_an_instance_is_culled_by_an_estimate_of_its_art_
assert!(img.pixel(3, 20)[3] > 0, "{:?}", img.pixel(3, 20));
}
/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), and an instance of
/// "Mark" at (25, 25) and one with a drop shadow at (70, 70). With `second` the blue square's
/// symbol is named that instead.
fn marks(second: &str) -> Document {
let mut d = Document::new(100.0, 100.0);
for i in 0..2000 {
let art = rect_node(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
}
for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] {
let art = rect_node(&mut d, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::solid(color), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
let l = d.layers[0].id;
let plain = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) });
let mut shadowed = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) });
shadowed.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 4, "y": 4, "blur": 0}),
visible: true,
});
d.insert(Some(l), 0, plain).unwrap();
d.insert(Some(l), 1, shadowed).unwrap();
d
}
/// Instances among many symbols draw the first symbol of their name, the same pixels as when no
/// other symbol has that name.
#[test]
fn instances_draw_the_first_symbol_of_their_name() {
let img = render(&marks("Mark"));
assert_eq!(img.pixel(25, 25), [255, 0, 0, 255]);
assert_eq!(img.pixel(70, 70), [255, 0, 0, 255]);
assert!(img.pixels == render(&marks("Other")).pixels, "the pixels differ");
}
/// A frame that draws 300 instances with drop shadows, among 2,000 symbols, and an envelope around
/// instances reads the symbol list once to find their symbols.
#[test]
fn a_frame_reads_the_symbol_list_once() {
let mut d = marks("Other");
let l = d.layers[0].id;
for i in 0..300 {
let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2);
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
d.insert(Some(l), usize::MAX, n).unwrap();
}
let content = Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((50.0, 50.0)) }));
let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 };
let envelope = NodeKind::Envelope {
content: vec![content],
kind: Box::new(kind),
fidelity: 50.0,
editing: false,
options: Default::default(),
frame: Box::new(Affine::IDENTITY),
};
let envelope = Node::new(d.alloc_id(), envelope);
d.insert(Some(l), usize::MAX, envelope).unwrap();
let before = vectorcraft_doc::symbols_read();
render(&d);
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
}
/// Symbols 0 to 29 each hold two instances of the next, sheared two ways, so that the 2^30
/// instances drawn from the first are all placed differently. Symbol 30 holds a square with a drop
/// shadow. An instance of symbol 0 lies far left of the view. With `effect`, every instance has
+3 -2
View File
@@ -1241,9 +1241,10 @@ fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() {
let inst = d.layers[0].children().unwrap()[0].clone();
let mut r = Renderer::new();
r.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES - 1;
assert!(r.charge_fx_instance(&d, &inst), "one object fits");
let symbols = d.symbol_boxes();
assert!(r.charge_fx_instance(&symbols, &inst), "one object fits");
assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES);
assert!(!r.charge_fx_instance(&d, &inst), "the next does not");
assert!(!r.charge_fx_instance(&symbols, &inst), "the next does not");
assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES);
}
+2
View File
@@ -47,3 +47,5 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] }
craft-svg = { workspace = true, features = ["tree-render", "tree-text"] }
vectorcraft-testkit = { workspace = true }
proptest = { workspace = true }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
+4
View File
@@ -117,6 +117,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix:
linked: Vec::new(),
instance_xf: Affine::IDENTITY,
symbols: HashMap::new(),
symbol_lookup: doc.symbol_boxes(),
symbol_nest: 0,
symbol_nodes: 0,
inline_graphic: false,
@@ -301,6 +302,9 @@ struct Writer<'a> {
instance_xf: Affine,
/// What each symbol's instances can share, by symbol name (see [`Writer::symbol_use`]).
symbols: HashMap<String, SymbolDef>,
/// The document's symbols, found by name ([`vectorcraft_doc::SymbolBoxes::symbol`]) in time
/// independent of how many symbols the document holds.
symbol_lookup: vectorcraft_doc::SymbolBoxes<'a>,
/// Symbols being written inside one another (instances nested deeper are left out: a symbol
/// can't contain itself).
symbol_nest: u32,
+16 -14
View File
@@ -51,15 +51,16 @@ fn export_shape_bounds(n: &Node) -> Option<Rect> {
impl Reuse {
const NONE: Self = Self { moves: false, turns: false, scales: false };
/// What a def of symbol art `art` stands for.
pub(crate) fn of(doc: &Document, art: &Node) -> Self {
/// What a def of symbol art `art` stands for, in `doc`. `find` finds the symbol of each
/// instance in it by name.
pub(crate) fn of<'d>(doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, art: &Node) -> Self {
let mut r = Self { moves: true, turns: true, scales: true };
r.scan(doc, art, 0);
r.scan(doc, find, art, 0);
r
}
/// Narrow down to what `n` (inside symbols nested `depth` deep) allows.
fn scan(&mut self, doc: &Document, n: &Node, depth: u32) {
fn scan<'d>(&mut self, doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, n: &Node, depth: u32) {
let pattern = |p: &Paint| matches!(p, Paint::Pattern { .. });
let text_patterns = matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| pattern(&r.style.fill) || pattern(&r.style.stroke)));
let unlinked_mask = n.extras().mask.as_ref().is_some_and(|m| !m.linked);
@@ -95,17 +96,17 @@ impl Reuse {
if doc.symbol_nine_slice(symbol).is_some() {
self.scales = false;
}
if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) {
self.scan(doc, &s.art, depth + 1);
if let Some(s) = find(symbol) {
self.scan(doc, find, &s.art, depth + 1);
}
}
_ => {}
}
if let Some(m) = &n.extras().mask {
self.scan(doc, &m.art, depth);
self.scan(doc, find, &m.art, depth);
}
for c in n.children().into_iter().flatten() {
self.scan(doc, c, depth);
self.scan(doc, find, c, depth);
}
}
@@ -481,7 +482,7 @@ impl Writer<'_> {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
let custom = !n.extras().symbol_overrides.is_empty();
if symbols.insert((symbol.clone(), custom.then_some(n.id)))
&& let Some(s) = self.doc.symbols.iter().find(|s| s.name == *symbol)
&& let Some(s) = self.symbol_lookup.symbol(symbol)
{
stack.push(if custom { std::sync::Arc::new(vectorcraft_brush::instance_art(&s.art, n)) } else { s.art.clone() });
}
@@ -518,7 +519,7 @@ impl Writer<'_> {
/// its geometry, so the region also covers the geometry's box, placed, grown by the strokes'
/// and effects' reach unscaled.
fn region_attrs(&mut self, nodes: &[&Node]) -> String {
let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes());
let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured());
let mut art_reach = std::mem::take(&mut self.art_reach);
let region = self.region_of(&symbols, &mut art_reach, nodes);
self.region_boxes = Some(symbols);
@@ -528,7 +529,7 @@ impl Writer<'_> {
/// The box of what each of `nodes` paints, as [`Self::paint_box`] measures it.
fn paint_boxes(&mut self, nodes: &[&Node]) -> Vec<Option<Option<Rect>>> {
let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes());
let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured());
let mut art_reach = std::mem::take(&mut self.art_reach);
let boxes = nodes.iter().map(|n| self.paint_box(&symbols, &mut art_reach, n)).collect();
self.region_boxes = Some(symbols);
@@ -615,7 +616,7 @@ impl Writer<'_> {
return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?);
}
let symbol = match &n.kind {
NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)),
NodeKind::SymbolInstance { symbol, xf } => self.symbol_lookup.symbol(symbol).map(|s| (s, xf)),
_ => None,
};
if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() {
@@ -1026,7 +1027,7 @@ impl Writer<'_> {
let doc = self.doc;
// The instances nested in an inline graphic's art are ordinary instances again.
let inline = std::mem::take(&mut self.inline_graphic);
let Some(sym) = doc.symbols.iter().find(|s| s.name == *symbol) else { return };
let Some(sym) = self.symbol_lookup.symbol(symbol) else { return };
if self.symbol_nest > MAX_SYMBOL_NEST {
return;
}
@@ -1113,7 +1114,8 @@ impl Writer<'_> {
return None;
}
if !self.symbols.contains_key(&sym.name) {
let reuse = Reuse::of(self.doc, &sym.art);
let lookup = &self.symbol_lookup;
let reuse = Reuse::of(self.doc, &|name| lookup.symbol(name), &sym.art);
self.symbols.insert(sym.name.clone(), SymbolDef { id: None, reuse, nodes: 0 });
}
let def = self.symbols.get(&sym.name)?;
+2 -2
View File
@@ -680,7 +680,7 @@ impl Writer<'_> {
}
return 0;
}
let bounds = n.visual_bounds_with(&self.doc.symbol_boxes());
let bounds = n.visual_bounds_with(&self.symbol_lookup.unmeasured());
// An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first.
let grow = 18.0 / self.doc.raster_ppi();
let reach: f64 =
@@ -705,7 +705,7 @@ impl Writer<'_> {
// object's geometry turned into it, grown by what its strokes and other paint add
// around it in the document: a square that far to each side, as it measures in
// user space along each axis (a miter corner reaches that far along both).
let symbols = self.doc.symbol_boxes();
let symbols = self.symbol_lookup.unmeasured();
let visual = input.visual_bounds_with(&symbols).unwrap_or_default();
let user_box = if sf.moves_only() {
visual - sf.origin()
+3 -3
View File
@@ -202,7 +202,7 @@ pub(crate) fn import_finding(
hidden: found.hidden,
uses: found.uses,
symbols: HashMap::new(),
symbol_names: HashSet::new(),
symbol_names: HashMap::new(),
symbol_suffixes: HashMap::new(),
pattern_suffixes: HashMap::new(),
blends: fx::blends(&xml, &scan.markers),
@@ -360,8 +360,8 @@ struct Importer {
uses: HashMap<String, String>,
/// The symbols made so far, by `<symbol>` id.
symbols: HashMap<String, SymbolMade>,
/// The names of the symbols made so far.
symbol_names: HashSet<String>,
/// The names of the symbols made so far, each with its index in the document's symbols.
symbol_names: HashMap<String, usize>,
/// Where the suffixes of each symbol and pattern name base go on from (`unique_name`).
symbol_suffixes: HashMap<String, usize>,
pattern_suffixes: HashMap<String, usize>,
+6 -4
View File
@@ -207,9 +207,11 @@ impl Importer {
None => {
let base = self.name_of(&sym).to_string();
let names = &self.symbol_names;
let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains(n));
self.symbol_names.insert(name.clone());
let reuse = Reuse::of(&self.doc, &art);
let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains_key(n));
let doc = &self.doc;
let find = |n: &str| names.get(n).and_then(|&i| doc.symbols.get(i)).filter(|s| s.name == n);
let reuse = Reuse::of(doc, &find, &art);
self.symbol_names.insert(name.clone(), self.doc.symbols.len());
let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse };
self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) });
self.symbols.insert(sym, made);
@@ -862,7 +864,7 @@ mod tests {
hidden: HashSet::new(),
uses: HashMap::new(),
symbols: HashMap::new(),
symbol_names: HashSet::new(),
symbol_names: HashMap::new(),
symbol_suffixes: HashMap::new(),
pattern_suffixes: HashMap::new(),
blends: HashMap::new(),
+58
View File
@@ -69,6 +69,64 @@ fn three_instances_give_one_symbol_and_three_uses() {
assert!(boxes.iter().any(|b| (b.x0 - 90.0).abs() < 1e-3 && (b.y0 - 30.0).abs() < 1e-3), "{boxes:?}");
}
/// 2,000 symbols, then two named "Mark" (a red square with a black stroke, then a blue one) and
/// "Holder", holding an instance of "Mark". Instances: "Mark" moved, "Mark" stretched (written as
/// its own art) and "Holder". With `second` the blue square's symbol is named that instead.
fn marks(second: &str) -> Document {
let mut d = Document::new(200.0, 120.0);
for i in 0..2000 {
let art = Node::path(
d.alloc_id(),
shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)),
Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0),
);
d.symbols.push(Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) });
}
for (name, color) in [("Mark", Color::rgb8(255, 0, 0)), (second, Color::rgb8(0, 0, 255))] {
let ap = Appearance::basic(Paint::solid(color), Paint::solid(Color::BLACK), 2.0);
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), ap);
d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
}
let held = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((5.0, 5.0)) });
let holder = Node::group(d.alloc_id(), vec![Arc::new(held)]);
d.symbols.push(Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(holder) });
instance(&mut d, "Mark", Affine::translate((25.0, 25.0)));
instance(&mut d, "Mark", Affine::translate((80.0, 60.0)) * Affine::scale_non_uniform(2.0, 1.0));
instance(&mut d, "Holder", Affine::translate((150.0, 60.0)));
d
}
/// Instances among many symbols are written with the first symbol of their name, the same SVG as
/// when no other symbol has that name.
#[test]
fn instances_are_written_with_the_first_symbol_of_their_name() {
let svg = export(&marks("Mark"), &ExportOptions::default());
assert_eq!(svg, export(&marks("Other"), &ExportOptions::default()));
assert!(svg.contains("#ff0000") && !svg.contains("#0000ff"), "{svg}");
}
/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once
/// to find their symbols.
#[test]
fn an_export_reads_the_symbol_list_once() {
let mut d = marks("Other");
for i in 0..300 {
let xf = Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 8.0)) * Affine::scale(0.2);
let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf });
n.appearance.effects.push(vectorcraft_doc::Effect {
id: "stylize.dropShadow".into(),
params: serde_json::json!({"x": 1, "y": 1, "blur": 0}),
visible: true,
});
let l = d.layers[0].id;
d.insert(Some(l), usize::MAX, n).unwrap();
}
let before = vectorcraft_doc::symbols_read();
export(&d, &ExportOptions::default());
let read = vectorcraft_doc::symbols_read() - before;
assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len());
}
/// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it, with no
/// `<use>`: at 200 × 150 its 10 × 10 corner square stays 10 × 10 and its center square becomes
/// 30 × 20. An instance at the natural size still uses the def.
+6
View File
@@ -28,6 +28,12 @@ icu_segmenter = "2.3"
# Grapheme clusters (a Thai consonant with its vowel and tone marks, an accented letter, an emoji
# sequence) for caret movement; MIT OR Apache-2.0, already in the build.
unicode-segmentation = "1.13"
# Hyphenation patterns and rules for German, Polish, Portuguese, Italian, Bulgarian, Turkish and
# Russian; MIT OR Apache-2.0, already in the build through the engine's spell checking.
craft-proof = { workspace = true }
# Composes a decomposed Cyrillic word (`и` + U+0306 is `й`) before its script check; MIT OR
# Apache-2.0, already in the build through craft-proof.
unicode-normalization = "0.1.26"
# Draws COLR colour glyphs whose paints documents have no form for (sweep gradients, compositing
# modes) into images: the canvas's renderer, already in the build.
vello_cpu = { workspace = true }
+142 -13
View File
@@ -9,8 +9,11 @@
//! [`set_hyphenation_exceptions`].
//!
//! Each run hyphenates in its own language ([`vectorcraft_doc::CharStyle::language`]). English
//! uses the rules above; eleven Indian languages use bundled hyph-utf8 patterns. Other languages
//! only break at user exceptions. Indic breaks always preserve Unicode grapheme boundaries.
//! uses the rules above; eleven Indian languages use bundled hyph-utf8 patterns; German, Polish,
//! Portuguese, Italian, Bulgarian, Turkish and Russian use craft-proof's patterns and rules (German,
//! Polish, Portuguese and Italian only in builds that embed their patterns). Other languages only
//! break at user exceptions. Indic and craft-proof breaks always preserve Unicode grapheme
//! boundaries.
use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard, OnceLock};
@@ -18,22 +21,28 @@ use std::sync::{Mutex, MutexGuard, OnceLock};
use vectorcraft_doc::HyphenationOptions;
mod indic;
mod proof;
#[derive(Clone, Copy, Debug)]
pub(crate) enum Language {
None,
English,
Indic(u8),
/// One of [`proof::TAGS`].
Proof(u8),
}
impl Language {
/// Select rules by the primary BCP 47 subtag; absent tags retain the English default.
pub(crate) fn from_tag(tag: Option<&str>) -> Self {
let primary = tag.unwrap_or("en").split('-').next().unwrap_or_default();
let index = |tags: &[&str]| tags.iter().position(|t| primary.eq_ignore_ascii_case(t)).and_then(|i| u8::try_from(i).ok());
if primary.eq_ignore_ascii_case("en") {
Self::English
} else if let Some(i) = index(&indic::TAGS) {
Self::Indic(i)
} else {
indic::TAGS.iter().position(|t| primary.eq_ignore_ascii_case(t)).and_then(|i| u8::try_from(i).ok()).map_or(Self::None, Self::Indic)
index(&proof::TAGS).map_or(Self::None, Self::Proof)
}
}
}
@@ -189,11 +198,16 @@ fn onset_pair(a: char, b: char) -> bool {
/// Whether text in `language` (a [`vectorcraft_doc::CharStyle::language`]: a BCP 47 tag, `None` for
/// the default, English: USA) has break points of its own.
pub fn language_has_patterns(language: Option<&str>) -> bool {
!matches!(Language::from_tag(language), Language::None)
match Language::from_tag(language) {
Language::None => false,
Language::Proof(index) => proof::available(usize::from(index)),
Language::English | Language::Indic(_) => true,
}
}
/// Language-specific break points as character indices. Indic patterns and exceptions are
/// filtered to whole graphemes; the paragraph's length options count Unicode characters.
/// Language-specific break points as character indices. Indic and craft-proof points and
/// exceptions are filtered to whole graphemes; the paragraph's length options count Unicode
/// characters.
pub fn hyphen_points_for_language(word: &str, opts: &HyphenationOptions, language: Option<&str>) -> Vec<usize> {
points_for(word, opts, Language::from_tag(language))
}
@@ -220,14 +234,15 @@ pub fn hyphen_points_in(word: &str, opts: &HyphenationOptions, patterns: bool) -
points_for(word, opts, if patterns { Language::English } else { Language::None })
}
/// Apply exceptions first, then language rules and paragraph limits, protecting Indic clusters.
/// Apply exceptions first, then language rules and paragraph limits, protecting Indic and
/// craft-proof clusters.
pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Language) -> Vec<usize> {
if let Some(ex) = exception_for(word) {
let mut points = match ex {
Exception::Never => vec![],
Exception::Only(pts) => lowercase_points_to_word(word, &pts),
};
if matches!(language, Language::Indic(_)) {
if matches!(language, Language::Indic(_) | Language::Proof(_)) {
indic::retain_boundaries(word, &mut points);
}
return points;
@@ -241,8 +256,9 @@ pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Langua
if n <= longer_than || !c.iter().all(|&ch| is_word_char(ch)) {
return vec![];
}
// A capitalised run like "NASA" or a proper name stays whole only when all caps.
if c.iter().all(|c| c.is_uppercase()) {
// A capitalised run like "NASA" or a proper name stays whole only when all caps. Combining
// marks have no case, so a decomposed capital ("O" + U+0308) counts by its letter.
if c.iter().filter(|&&ch| !unicode_normalization::char::is_combining_mark(ch)).all(|c| c.is_uppercase()) {
return vec![];
}
if !opts.capitalized && c.first().is_some_and(|c| c.is_uppercase()) {
@@ -250,8 +266,9 @@ pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Langua
}
let before = usize::try_from(opts.after_first).unwrap_or(usize::MAX).max(1);
let after = usize::try_from(opts.before_last).unwrap_or(usize::MAX).max(1);
if let Language::Indic(index) = language {
let mut points = indic::points(word, usize::from(index));
if let Language::Indic(index) | Language::Proof(index) = language {
let mut points =
if matches!(language, Language::Indic(_)) { indic::points(word, usize::from(index)) } else { proof::points(word, usize::from(index)) };
points.retain(|p| *p >= before && n.saturating_sub(*p) >= after);
indic::retain_boundaries(word, &mut points);
return points;
@@ -308,6 +325,112 @@ pub(crate) fn with_hyphenation_exceptions_for_test(source: &str, f: impl FnOnce(
#[cfg(test)]
mod tests {
use super::*;
use craft_proof::hyphen::Patterns;
/// Paragraph options that let every point through: words of any length, one letter each side.
fn open() -> HyphenationOptions {
HyphenationOptions { words_longer_than: 0, after_first: 1, before_last: 1, ..Default::default() }
}
/// Bulgarian, Turkish and Russian break by their own syllable rules in every build, with
/// regional tags too.
#[test]
fn rule_languages_break_by_their_own_rules() {
for (tags, word, points) in [
(["bg", "bg-BG"], "планина", vec![3, 5]),
(["tr", "TR-cy"], "öğrenci", vec![2, 5]),
(["tr", "tr-TR"], "kardeş", vec![3]),
(["ru", "ru-RU"], "родина", vec![2, 4]),
(["ru", "RU"], "сестра", vec![3]),
] {
for tag in tags {
assert_eq!(hyphen_points_for_language(word, &open(), Some(tag)), points, "{tag}: {word}");
}
}
// Capitals keep their points.
assert_eq!(hyphen_points_for_language("Родина", &open(), Some("ru")), vec![2, 4]);
}
/// German, Polish, Portuguese and Italian break at their own TeX patterns when craft-proof
/// embeds them, and not at all otherwise (two letters on each side, as TeX's defaults keep).
#[test]
fn pattern_languages_break_at_their_own_patterns() {
let open = || HyphenationOptions { after_first: 2, before_last: 2, ..open() };
for (tags, patterns, word, points) in [
(["de", "de-CH"], Patterns::de(), "Silbentrennung", vec![3, 6, 10]),
(["pl", "pl-PL"], Patterns::pl(), "kobieta", vec![2, 5]),
(["pt", "pt-BR"], Patterns::pt(), "computador", vec![3, 5, 7]),
(["it", "it-CH"], Patterns::it(), "montagna", vec![3, 5]),
] {
for tag in tags {
let got = hyphen_points_for_language(word, &open(), Some(tag));
if patterns.is_empty() {
assert!(got.is_empty(), "{tag}: {word}: no patterns embedded, no English fallback: {got:?}");
} else {
assert_eq!(got, points, "{tag}: {word}");
}
}
}
// A letter outside the language's patterns sends craft-proof to a general syllable
// heuristic, which isn't the language's own: the word stays whole.
for (tag, word) in [("de", "Søndergaard"), ("pl", "Müllerowa"), ("pt", "Łódzkaliano"), ("it", "Łódzkaliano")] {
assert!(hyphen_points_for_language(word, &open(), Some(tag)).is_empty(), "{tag}: {word}");
}
}
/// A word outside its language's script stays whole: craft-proof would hyphenate it as English.
#[test]
fn other_scripts_in_a_language_get_no_english_points() {
for (tag, word) in [("ru", "typography"), ("bg", "typography"), ("ru", "Москваcity"), ("bg", "ёжикова"), ("tr", "родина")]
{
assert!(hyphen_points_for_language(word, &open(), Some(tag)).is_empty(), "{tag}: {word}");
}
// A combining stress mark in a Russian word, and a joiner in a German one.
assert!(hyphen_points_for_language("моло\u{301}ко", &open(), Some("ru")).is_empty());
assert!(hyphen_points_for_language("Silben\u{200d}trennung", &open(), Some("de")).is_empty());
for tag in ["fr", "es", "hr", "cs", "sr", "nl", "sa", "ur", "x-none", "zz"] {
assert!(hyphen_points_for_language("typography", &open(), Some(tag)).is_empty(), "{tag}");
assert!(hyphen_points_for_language("родина", &open(), Some(tag)).is_empty(), "{tag}");
}
}
/// A decomposed word breaks as its composed spelling does, at the matching characters, and a
/// decomposed all-capitals word stays whole as the composed one does.
#[test]
fn decomposed_words_break_as_composed_ones() {
for tag in ["ru", "bg"] {
let composed = hyphen_points_for_language("чайник", &open(), Some(tag));
assert!(!composed.is_empty(), "{tag}");
// `и` + U+0306 is `й`: points after it move one character on.
let shifted: Vec<usize> = composed.iter().map(|&p| if p >= 3 { p + 1 } else { p }).collect();
assert_eq!(hyphen_points_for_language("чаи\u{306}ник", &open(), Some(tag)), shifted, "{tag}");
}
assert!(hyphen_points_for_language("ÖĞRENCİ", &open(), Some("tr")).is_empty());
assert!(hyphen_points_for_language("O\u{308}ĞRENCİ", &open(), Some("tr")).is_empty(), "decomposed capitals");
assert_eq!(hyphen_points_for_language("o\u{308}ğrenci", &open(), Some("tr")), vec![3, 6]);
}
/// The paragraph's limits and the Preferences exceptions apply to the new languages as they
/// do to English.
#[test]
fn limits_and_exceptions_apply_in_the_rule_languages() {
let d = HyphenationOptions::default();
// 3 letters each side by default: "ро-ди-на" keeps neither point, "сес-тра" keeps its one.
assert!(hyphen_points_for_language("родина", &d, Some("ru")).is_empty());
assert_eq!(hyphen_points_for_language("сестра", &d, Some("ru")), vec![3]);
assert!(hyphen_points_for_language("сестра", &HyphenationOptions { words_longer_than: 6, ..d.clone() }, Some("ru")).is_empty());
assert!(hyphen_points_for_language("Сестра", &HyphenationOptions { capitalized: false, ..d.clone() }, Some("ru")).is_empty());
assert!(hyphen_points_for_language("СЕСТРА", &d, Some("ru")).is_empty(), "all capitals");
assert!(hyphen_points_for_language("", &open(), Some("ru")).is_empty());
assert!(hyphen_points_for_language("я", &open(), Some("ru")).is_empty());
with_exceptions("родина, kar-deş", || {
assert!(hyphen_points_for_language("родина", &open(), Some("ru")).is_empty());
assert_eq!(hyphen_points_for_language("kardeş", &d, Some("tr")), vec![3], "marked points ignore the limits");
});
with_exceptions("ро-дина", || {
assert_eq!(hyphen_points_for_language("родина", &open(), Some("ru")), vec![2]);
});
}
fn with_exceptions(source: &str, f: impl FnOnce()) {
with_hyphenation_exceptions_for_test(source, f);
@@ -319,9 +442,15 @@ mod tests {
for l in [None, Some("en-US"), Some("en-GB"), Some("EN-gb"), Some("en")] {
assert!(language_has_patterns(l), "{l:?}");
}
for l in [Some("de"), Some("fr"), Some("pt"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] {
for l in [Some("fr"), Some("es"), Some("hr"), Some("cs"), Some("nl"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] {
assert!(!language_has_patterns(l), "{l:?}");
}
for l in ["bg", "tr", "ru", "BG-bg", "tr-CY", "ru-RU"] {
assert!(language_has_patterns(Some(l)), "{l}");
}
for (l, embedded) in [("de", Patterns::de()), ("pl", Patterns::pl()), ("pt", Patterns::pt()), ("it", Patterns::it())] {
assert_eq!(language_has_patterns(Some(l)), !embedded.is_empty(), "{l}");
}
for tag in indic::TAGS {
assert!(language_has_patterns(Some(tag)));
assert!(language_has_patterns(Some(&format!("{}-IN", tag.to_uppercase()))));
+76
View File
@@ -0,0 +1,76 @@
//! Break points from craft-proof for the languages it has rules or patterns of its own for:
//! German, Polish, Portuguese and Italian (hyph-utf8's TeX patterns, embedded only when craft-proof
//! is built with `CRAFT_I18N_DIR`), Bulgarian and Turkish (syllable rules) and Russian (word-division
//! rules). craft-proof hyphenates any other word as English; those points are dropped here, so a
//! word outside its language's script, or one these rules don't cover, stays whole.
use craft_proof::hyphen::{Patterns, ProofLang, Source, word_breaks_in};
use unicode_normalization::UnicodeNormalization;
use unicode_script::{Script, UnicodeScript};
pub(super) const TAGS: [&str; 7] = ["de", "pl", "pt", "it", "bg", "tr", "ru"];
fn lang(index: usize) -> Option<ProofLang> {
Some(match *TAGS.get(index)? {
"de" => ProofLang::De,
"pl" => ProofLang::Pl,
"pt" => ProofLang::Pt,
"it" => ProofLang::It,
"bg" => ProofLang::Bg,
"tr" => ProofLang::Tr,
"ru" => ProofLang::Ru,
_ => return None,
})
}
/// The pattern file of a pattern language, `None` for the languages with rules.
fn patterns(lang: ProofLang) -> Option<&'static Patterns> {
match lang {
ProofLang::De => Some(Patterns::de()),
ProofLang::Pl => Some(Patterns::pl()),
ProofLang::Pt => Some(Patterns::pt()),
ProofLang::It => Some(Patterns::it()),
_ => None,
}
}
/// Whether the language has break points in this build: the rule languages always, the pattern
/// languages when their patterns are embedded.
pub(super) fn available(index: usize) -> bool {
lang(index).is_some_and(|l| patterns(l).is_none_or(|p| !p.is_empty()))
}
/// A Latin letter or a combining mark.
fn latin(c: char) -> bool {
matches!(c.script(), Script::Latin | Script::Inherited) && c != '\u{200c}' && c != '\u{200d}'
}
/// A Cyrillic letter, as craft-proof's Russian rules read them.
fn cyrillic(c: char) -> bool {
matches!(c, '\u{0400}'..='\u{052F}') && c.is_alphabetic()
}
/// Whether `word` is written in the language's script, and the sources of points that come from
/// the language's own rules or patterns. A Cyrillic word is checked composed, as craft-proof
/// hyphenates it: `и` + U+0306 is `й`, while a stress mark, which composes with nothing, is not a
/// letter.
fn fits(lang: ProofLang, word: &str) -> Option<&'static [Source]> {
let all = |f: fn(char) -> bool| word.chars().all(f);
let composed_cyrillic = || word.nfc().all(cyrillic);
match lang {
ProofLang::De | ProofLang::Pl | ProofLang::Pt | ProofLang::It => all(latin).then_some(&[Source::Patterns, Source::Dictionary]),
ProofLang::Tr => word.chars().all(|c| latin(c) || matches!(c, '\'' | '’')).then_some(&[Source::Rules]),
ProofLang::Bg => composed_cyrillic().then_some(&[Source::Rules]),
ProofLang::Ru => composed_cyrillic().then_some(&[Source::Heuristic]),
_ => None,
}
}
/// Character-index candidates for one language, before the paragraph's limits; empty when the
/// word isn't in the language's script or the language's own rules give it none.
pub(super) fn points(word: &str, index: usize) -> Vec<usize> {
let Some(lang) = lang(index) else { return vec![] };
let Some(sources) = fits(lang, word) else { return vec![] };
let (points, source) = word_breaks_in(word, lang);
if sources.contains(&source) { points } else { vec![] }
}
+34 -3
View File
@@ -1108,18 +1108,49 @@ fn each_run_hyphenates_in_its_own_language() {
let saved_without_one = hyphens(None);
assert!(saved_without_one > 0, "some words hyphenated");
assert_eq!(hyphens(Some("en-GB")), saved_without_one);
assert_eq!(hyphens(Some("de")), 0, "German has no break points yet");
assert_eq!(hyphens(Some("fr")), 0, "French has no break points yet");
assert_eq!(hyphens(Some("ru")), 0, "English words in a Russian run are not hyphenated as English");
assert_eq!(hyphens(Some("x-from-a-file")), 0, "a tag that isn't known has no hyphenation");
// both in one paragraph: the English run breaks and the German one doesn't
// both in one paragraph: the English run breaks and the French one doesn't
let mut t = area(&format!("{text} {text}"), style(14.0), frame, Justify::Left);
t.para.hyphenate = true;
edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("de".into()));
edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("fr".into()));
let l = layout(db(), &t);
let at: Vec<usize> = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect();
assert!(!at.is_empty() && at.iter().all(|b| *b < text.len()), "hyphens only in the English run: {at:?}");
}
/// A justified Russian paragraph in a narrow frame breaks its long words at the Russian rules'
/// points with either composer, and not at all with Hyphenate off.
#[test]
fn a_russian_run_hyphenates_at_russian_break_points() {
let text = "Государственное законодательство регулирует достопримечательности.";
let frame = Rect::new(0.0, 0.0, 120.0, 600.0);
let st = CharStyle { language: Some("ru-RU".into()), ..style(14.0) };
for composer in [Composer::EveryLine, Composer::SingleLine] {
let mut t = area(text, st.clone(), frame, Justify::JustifyLeft);
t.para.composer = composer;
t.para.hyphenate = true;
let l = layout(db(), &t);
let at: Vec<usize> = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect();
assert!(!at.is_empty(), "{composer:?}: some words hyphenated");
for b in at {
// The word the hyphen splits, and where in it the line ends.
let start = text[..b].rfind(' ').map_or(0, |i| i + 1);
let end = text[b..].find([' ', '.']).map_or(text.len(), |i| b + i);
let word = &text[start..end];
let point = text[start..b].chars().count();
assert!(
hyphen::hyphen_points_for_language(word, &t.para.hyphenation, Some("ru")).contains(&point),
"{composer:?}: {word} broken after {point} letters"
);
}
t.para.hyphenate = false;
assert_eq!(layout(db(), &t).glyphs.iter().filter(|g| g.len == 0).count(), 0, "{composer:?}: Hyphenate off");
}
}
#[test]
fn hyphenated_layout_adds_hyphens() {
let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything.";
+2 -2
View File
@@ -12,8 +12,8 @@ pub mod fold;
mod solid;
mod visibility;
pub use solid::{
Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate,
inflate_each, inflate_together, plane, plane_face_map,
Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map,
extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face,
};
pub use visibility::{VisibleFace, visible_faces};
mod shading;
+1 -1
View File
@@ -28,7 +28,7 @@ pub(crate) use build::PLANES;
use build::{Camera, cuts, edge_distance, newell, section};
pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces};
pub use build::{extrude, plane};
pub use face_map::{FaceMap, extrude_face_map, plane_face_map};
pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face};
#[cfg(test)]
use inflate::GRID_WORK;
pub(crate) use inflate::inflate_faces;
+89
View File
@@ -174,6 +174,95 @@ pub fn plane_face_map(bounds: Rect, view: View) -> Option<FaceMap> {
Some(FaceMap::new(&camera, &placing, true))
}
/// A planar face in its solid's mesh ([`crate::Mesh`]): where the points of the art's plane lie
/// before projection, in the mesh's coordinates (y up), and the face's outward normal there.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeshFace {
/// An art point `p` lies at `x · (p.x - centre.x) + y · (p.y - centre.y) + at`, with the art's
/// center at `at`.
x: V3,
y: V3,
centre: Point,
at: V3,
normal: V3,
/// A plane's mesh turns its normal toward the viewer, so its triangles face either way.
either_side: bool,
}
/// From the effects' view space (y down) to the mesh's (y up).
fn mesh_space(v: V3) -> V3 {
V3(v.0, -v.1, v.2)
}
impl MeshFace {
fn new(camera: &Camera, placing: &Placing, centre: Point, side: f64, either_side: bool) -> Self {
let (x, y, _) = placing.frame();
let at = mesh_space(placing.place(centre));
let normal = mesh_space(camera.rotate(V3(0.0, 0.0, side))).unit();
Self { x: mesh_space(x), y: mesh_space(y), centre, at, normal, either_side }
}
/// The art point that mesh point `m` shows, when `m` lies on the face's plane and a triangle
/// with unit normal `n` there belongs to the face. `None` otherwise, and when the face has no
/// area (a taper of 0 at the back).
pub fn art_point(&self, m: [f64; 3], n: [f64; 3]) -> Option<Point> {
let facing = self.normal.dot(V3(n[0], n[1], n[2]));
let facing = if self.either_side { facing.abs() } else { facing };
// A NaN normal faces no way.
let faces = facing > 1.0 - 1e-6;
if !faces {
return None;
}
// Measured from the art's center, so the tolerance follows the solid's size and not where
// the art lies on the page.
let d = V3(m[0], m[1], m[2]).sub(self.at);
let (xx, xy, yy) = (self.x.dot(self.x), self.x.dot(self.y), self.y.dot(self.y));
let det = xx * yy - xy * xy;
let spans = xx > 1e-24 && yy > 1e-24 && det >= 1e-12 * xx * yy;
if !spans {
return None;
}
let (bx, by) = (self.x.dot(d), self.y.dot(d));
let (px, py) = ((bx * yy - by * xy) / det, (xx * by - xy * bx) / det);
let on = V3(self.x.0 * px + self.y.0 * py, self.x.1 * px + self.y.1 * py, self.x.2 * px + self.y.2 * py);
let off = d.sub(on);
let size = 1.0 + d.dot(d).sqrt();
let p = Point::new(self.centre.x + px, self.centre.y + py);
(p.x.is_finite() && p.y.is_finite() && off.dot(off).sqrt() <= 1e-6 * size).then_some(p)
}
}
/// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with
/// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0
/// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane,
/// and for invalid bounds.
pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option<MeshFace> {
check_bounds(bounds).ok()?;
let o = options.sanitized();
if o.depth <= 0.0 {
return (face == PlanarFace::Front).then(|| plane_mesh_face(bounds, view)).flatten();
}
if !o.cap {
return None;
}
let camera = Camera::new(view, bounds, o.depth);
let (t, side) = match face {
PlanarFace::Front => (0.0, 1.0),
PlanarFace::Back => (1.0, -1.0),
};
let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t);
Some(MeshFace::new(&camera, &placing, bounds.center(), side, false))
}
/// The plane [`super::plane`] turns art with `bounds` into, with `view`, in its mesh
/// ([`MeshFace`]).
pub fn plane_mesh_face(bounds: Rect, view: View) -> Option<MeshFace> {
check_bounds(bounds).ok()?;
let camera = Camera::new(view, bounds, 0.0);
let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0);
Some(MeshFace::new(&camera, &placing, bounds.center(), 1.0, true))
}
#[cfg(test)]
#[path = "tests_face_map.rs"]
mod tests;
+65 -1
View File
@@ -1,7 +1,7 @@
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect};
use super::super::{Extrude, Facet, PlanarFace, View, extrude, plane};
use super::{FaceMap, NEAREST, extrude_face_map, plane_face_map};
use super::{FaceMap, MeshFace, NEAREST, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face};
fn square() -> (PathData, Rect) {
let mut b = BezPath::new();
@@ -143,6 +143,70 @@ fn a_page_point_nearer_the_eye_than_the_page_map_allows_has_no_art_point() {
assert_eq!(map.to_art(q), None, "the inverse map takes {q:?} back to an art point the page map has no point for");
}
/// The art point of every corner of each triangle of `mesh` that `face` takes, and how many
/// triangles it takes.
fn mesh_art(mesh: &crate::Mesh, face: &MeshFace) -> (Vec<Point>, usize) {
let (mut points, mut taken) = (vec![], 0);
for t in &mesh.triangles {
let corners: Option<Vec<Point>> = t.iter().map(|&i| face.art_point(mesh.positions[i as usize], mesh.normals[i as usize])).collect();
if let Some(c) = corners {
points.extend(c);
taken += 1;
}
}
(points, taken)
}
#[test]
fn a_caps_mesh_corners_go_back_to_the_art_they_were_made_from() {
let (path, bounds) = square();
let bevel = crate::Bevel { width: 4.0, height: 4.0, ..Default::default() };
let options = Extrude { twist: 30.0, taper: 0.5, bevel: Some(bevel), ..Extrude::default() };
let view = turned(40.0);
let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap();
// The bevel's width sets the walls, and the back cap, out from the front's outline.
let outset = bounds.inflate(4.0, 4.0);
for (face, cap) in [(PlanarFace::Front, bounds), (PlanarFace::Back, outset)] {
let mesh_face = extrude_mesh_face(bounds, options, view, face).unwrap();
let (points, taken) = mesh_art(&mesh, &mesh_face);
// A square cap is two triangles, and none of the bevel's or the walls' triangles are
// taken. The art points undo the back's twist and taper.
assert_eq!(taken, 2, "{face:?}");
for p in points {
let near = corners(cap).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-6, "{face:?}: {p:?} is {near} from the cap's corners");
}
}
// A hollow solid has no caps, and a plane's mesh has only the front, facing either way.
assert_eq!(extrude_mesh_face(bounds, Extrude { cap: false, ..options }, view, PlanarFace::Front), None);
let plane = crate::plane_mesh(&path, FillRule::NonZero, bounds, view).unwrap();
let (points, taken) = mesh_art(&plane, &plane_mesh_face(bounds, view).unwrap());
assert_eq!(taken, plane.triangles.len());
assert!(points.iter().all(|p| corners(bounds).iter().any(|c| c.distance(*p) < 1e-6)), "{points:?}");
assert_eq!(extrude_mesh_face(bounds, Extrude { depth: 0.0, ..options }, view, PlanarFace::Back), None);
}
#[test]
fn a_cap_far_from_the_page_origin_takes_none_of_a_step_bevels_treads() {
let (path, bounds) = square();
let far = vectorcraft_geom::kurbo::Affine::translate((1e7, 1e7));
let path = PathData::from_bezpath(&(far * path.to_bezpath()));
let bounds = far.transform_rect_bbox(bounds);
let bevel = crate::Bevel { width: 4.0, height: 4.0, shape: crate::BevelShape::Step, ..Default::default() };
let options = Extrude { bevel: Some(bevel), ..Extrude::default() };
let view = turned(0.0);
let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap();
let mesh_face = extrude_mesh_face(bounds, options, view, PlanarFace::Front).unwrap();
let (points, taken) = mesh_art(&mesh, &mesh_face);
// The treads face the same way as the cap, a few points behind it: only the cap's two
// triangles are taken, wherever the art lies on the page.
assert_eq!(taken, 2);
for p in points {
let near = corners(bounds).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-6, "{p:?} is {near} from the cap's corners");
}
}
#[test]
fn the_mapped_part_of_a_rectangle_stops_before_the_eye() {
let (_, bounds) = square();
+24 -15
View File
@@ -1,8 +1,9 @@
//! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All
//! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's
//! submenu selects them. Tool gestures emit engine commands. The Trim at Crossings Tool is the
//! exception: it is in the Scissors tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and
//! the All Tools drawer show it, as well as in Path Precision Tools' submenu.
//! submenu selects them. Tool gestures emit engine commands. Two tools are the exceptions: the Trim
//! at Crossings Tool is in the Scissors tool's group and the Enclosing Lasso Tool is in the Lasso
//! tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and the All Tools drawer show them, as
//! well as in their add-ons' submenus.
pub mod anchor_eraser;
pub mod box3d;
@@ -37,25 +38,17 @@ pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart
pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }];
pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, label: "Enclosing Lasso Tool", shortcut: None, icon: "tool-lasso" }];
pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }];
pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }];
/// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the
/// heading the All Tools drawer lists it under (its add-on's name).
const HEADED: &[(&[ToolInfo], &str)] = &[
(PATH_TOOLS, "Path Precision Tools"),
(SMART_PEN, "Smart Pen"),
(ENCLOSING_LASSO, "Enclosing Lasso"),
(CONTOUR, "Contour"),
(BOX_3D, "3D Box"),
(POLYGONAL_LASSO, "Polygonal Lasso"),
];
const HEADED: &[(&[ToolInfo], &str)] =
&[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")];
/// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]).
pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D, POLYGONAL_LASSO];
pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, CONTOUR, BOX_3D, POLYGONAL_LASSO];
/// The heading the All Tools drawer lists tool `id` under: its add-on's name.
pub fn heading(id: &str) -> Option<&'static str> {
@@ -97,7 +90,6 @@ mod tests {
}
assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools")));
assert_eq!(heading(smart_pen::ID), Some("Smart Pen"));
assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso"));
assert_eq!(heading(contour::ID), Some("Contour"));
assert_eq!(heading(box3d::ID), Some("3D Box"));
assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso"));
@@ -122,4 +114,21 @@ mod tests {
assert!(!GROUPS.iter().any(|g| g.iter().any(|t| t.id == trim::ID)), "not listed again under the add-on");
assert_eq!(crate::catalog::all_tools().filter(|t| t.id == trim::ID).count(), 1);
}
/// The Enclosing Lasso Tool is in the Lasso tool's group, right after the Lasso, with no
/// default shortcut, listed once, and still made by its add-on.
#[test]
fn enclosing_lasso_is_in_the_lasso_group_once() {
let id = enclosing_lasso::ID;
let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == id)).collect();
assert_eq!(groups.len(), 1);
let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect();
assert_eq!(ids, ["lasso", id]);
let info = crate::tool_info(id).expect("catalogued");
assert_eq!((info.label, info.shortcut, info.icon), ("Enclosing Lasso Tool", None, "tool-lasso"));
assert_eq!(crate::tool_info("lasso").and_then(|t| t.shortcut), Some("Q"), "the Lasso keeps its shortcut");
assert_eq!(create(id).map(|tool| tool.id()), Some(id));
assert!(heading(id).is_none(), "not listed again under the add-on");
assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1);
}
}
@@ -167,6 +167,13 @@ impl Tool for PolygonalLassoTool {
self.mesh.options()
}
/// Pick the gradient mesh points the Eyedropper held (`meshPoints`).
fn set_option(&mut self, key: &str, value: &serde_json::Value) {
if key == "meshPoints" {
self.mesh.set_options(value);
}
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id));
let mut line = self.vertices.clone();
+8 -2
View File
@@ -38,14 +38,20 @@ fn named(n: &Node, name: &str) -> bool {
n.name.as_deref() == Some(name)
}
/// Is `n` a Live Paint group's part named `name` ([`FACE_NAME`] or [`EDGE_NAME`]): a path with that
/// name? Type, groups and other objects drawn in the group under such a name are not parts.
fn part(n: &Node, name: &str) -> bool {
named(n, name) && n.path_data().is_some()
}
/// Face children of a Live Paint group (paint order).
pub fn faces(group: &Node) -> Vec<&Arc<Node>> {
group.children().map(|c| c.iter().filter(|n| named(n, FACE_NAME)).collect()).unwrap_or_default()
group.children().map(|c| c.iter().filter(|n| part(n, FACE_NAME)).collect()).unwrap_or_default()
}
/// Edge children of a Live Paint group.
pub fn edges(group: &Node) -> Vec<&Arc<Node>> {
group.children().map(|c| c.iter().filter(|n| named(n, EDGE_NAME)).collect()).unwrap_or_default()
group.children().map(|c| c.iter().filter(|n| part(n, EDGE_NAME)).collect()).unwrap_or_default()
}
/// The hidden sources group of a Live Paint group.
+5 -1
View File
@@ -24,7 +24,11 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[
t("groupSelection", "Group Selection Tool", None, "tool-group-select"),
],
&[t("magicWand", "Magic Wand Tool", Some("Y"), "tool-magic-wand")],
&[t("lasso", "Lasso Tool", Some("Q"), "tool-lasso")],
&[
t("lasso", "Lasso Tool", Some("Q"), "tool-lasso"),
// Enclosing Lasso's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once.
t(crate::addons::enclosing_lasso::ID, "Enclosing Lasso Tool", None, "tool-lasso"),
],
&[
t("pen", "Pen Tool", Some("P"), "tool-pen"),
t("addAnchor", "Add Anchor Point Tool", Some("+"), "tool-pen-add"),
+7
View File
@@ -762,6 +762,13 @@ impl Tool for DirectSelectionTool {
fn options(&self) -> Value {
self.mesh.options()
}
/// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group
/// Selection, which selects whole objects, does not.
fn set_option(&mut self, key: &str, value: &Value) {
if key == "meshPoints" && !self.group {
self.mesh.set_options(value);
}
}
/// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh
/// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved
/// goes back and the tool waits for the next press (#1743).
+6
View File
@@ -360,6 +360,12 @@ impl Tool for MeshTool {
fn options(&self) -> serde_json::Value {
self.edit.options()
}
/// Pick the gradient mesh points the Eyedropper held (`meshPoints`).
fn set_option(&mut self, key: &str, value: &serde_json::Value) {
if key == "meshPoints" {
self.edit.set_options(value);
}
}
fn busy(&self) -> bool {
self.edit.dragging()
}
+44
View File
@@ -34,6 +34,13 @@ pub fn grid_of(n: &Node) -> Option<Cow<'_, GradientMesh>> {
}
}
/// The `{id, index}` entries of a `meshPoints` option ([`MeshEdit::options`]); malformed entries
/// are left out.
pub fn points_of(value: &Value) -> Vec<(NodeId, usize)> {
let Some(v) = value.as_array() else { return vec![] };
v.iter().filter_map(|p| Some((NodeId(p.get("id")?.as_u64()?), usize::try_from(p.get("index")?.as_u64()?).ok()?))).collect()
}
/// Can `n` have an editable grid ([`grid_of`])? Its kind alone answers, without building the grid.
pub fn may_have_grid(n: &Node) -> bool {
match &n.kind {
@@ -66,6 +73,16 @@ pub fn part_points(m: &GradientMesh, p: Point, point_tol: f64, line_tol: f64) ->
Some(vec![m.idx(r, c), m.idx(r, c + 1), m.idx(r + 1, c), m.idx(r + 1, c + 1)])
}
/// The points of gradient mesh `m` that a color dropped at `p`, or an Eyedropper click there,
/// recolors: the point within `point_tol`, else the four points around the patch under `p`.
pub fn color_points(m: &GradientMesh, p: Point, point_tol: f64) -> Option<Vec<usize>> {
if let Some(i) = m.point_near(p, point_tol) {
return Some(vec![i]);
}
let (r, c, ..) = m.locate(p)?;
Some(vec![m.idx(r, c), m.idx(r, c + 1), m.idx(r + 1, c), m.idx(r + 1, c + 1)])
}
/// What a press on a mesh grabs: the mesh, the point and (on the focused point) a handle.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MeshGrab {
@@ -307,6 +324,16 @@ impl MeshEdit {
json!({"meshPoints": self.picked.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect::<Vec<_>>()})
}
/// Pick the points a `meshPoints` option lists (see [`points_of`]), with none focused: the
/// points the Eyedropper held when the tool switched back.
pub fn set_options(&mut self, value: &Value) {
if self.drag.is_some() {
return;
}
self.picked = points_of(value).into_iter().collect();
(self.focus, self.click) = (None, None);
}
/// The picked points of the meshes `shown` accepts, filled, and the focused point's handles
/// (lines and ends).
pub fn overlays(&self, cx: &ToolContext, shown: &dyn Fn(NodeId) -> bool) -> Vec<Overlay> {
@@ -637,4 +664,21 @@ mod tests {
assert_eq!(out, vec![Action::Exec("select.set".into(), json!({"ids": [m.0]})), Action::Begin("Move Mesh Points".into())]);
assert_eq!(picked(&t), set(&[(100.0, 100.0), (150.0, 100.0), (100.0, 150.0), (150.0, 150.0)]));
}
/// The tools that pick mesh points pick again the points a `meshPoints` option lists (those the
/// Eyedropper held), leaving malformed entries out; Group Selection picks none.
#[test]
fn mesh_point_tools_take_back_the_eyedroppers_picks() {
let points = json!([{"id": 7, "index": 2}, {"id": 7}, {"id": 7, "index": 0}]);
for id in ["mesh", "directSelection", "lasso", crate::addons::polygonal_lasso::ID] {
let mut t = crate::create(id);
t.set_option("meshPoints", &points);
assert_eq!(picked(&*t), [0, 2], "{id}");
t.set_option("meshPoints", &json!([]));
assert!(picked(&*t).is_empty(), "{id}");
}
let mut t = crate::create("groupSelection");
t.set_option("meshPoints", &points);
assert!(picked(&*t).is_empty(), "Group Selection");
}
}
+221 -4
View File
@@ -10,10 +10,20 @@
//! blend's steps, an envelope's distorted contents). Clicking an image samples its pixels
//! (averaged over the options' raster sample size; a CMYK image gives its ink amounts).
//!
//! With a gradient mesh selected, a click on one of its points gives that point the current solid
//! fill color, and a click inside one of its patches gives it to the patch's four points
//! (`object.mesh.setPointColor`).
//!
//! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click
//! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor
//! {stop}`) and switches back to that tool.
//!
//! Gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso before switching
//! to the Eyedropper stay picked (its `meshPoints` option), and go back to one of those tools
//! switched to next. While a selected, editable mesh has picked points, a click or Shift-click on an image or
//! other art samples the color under the cursor into those points alone (`paint.sampleColor
//! {stroke: false, ids}` with those meshes, which recolors the points through `paint.setFill`).
//!
//! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into
//! the open dialog (`brushKeyColor` UI request) and switches back.
//!
@@ -41,6 +51,28 @@ pub struct EyedropperTool {
text_selection: crate::text::TypeTool,
/// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`].
brush_key_color: bool,
/// The gradient mesh points the tool switched from had picked, each a mesh and a point index.
mesh_points: Vec<(NodeId, usize)>,
}
/// The point of each of `points` that a selected, editable gradient mesh in `cx` has.
fn live_points<'a>(cx: &'a ToolContext, points: &'a [(NodeId, usize)]) -> impl Iterator<Item = (NodeId, Point)> + 'a {
let editable = cx.doc.editable();
points.iter().filter(move |(id, _)| cx.selection.contains(*id) && editable(*id)).filter_map(|(id, index)| {
let Some(NodeKind::Mesh(m)) = cx.doc.node(*id).map(|n| &n.kind) else { return None };
Some((*id, m.points.get(*index)?.p))
})
}
/// The selected, editable gradient meshes in `cx` with one of `points` picked, in range, each once.
fn picked_meshes(cx: &ToolContext, points: &[(NodeId, usize)]) -> Vec<NodeId> {
let mut ids: Vec<NodeId> = vec![];
for (id, _) in live_points(cx, points) {
if !ids.contains(&id) {
ids.push(id);
}
}
ids
}
/// The colour of `paint` at `p` (gradients are sampled along their vector, radial ones honouring
@@ -456,6 +488,21 @@ fn image_color_at(s: &Sampler, n: &Node, p: Point) -> Option<Color> {
Some(Color::rgb(r, g, b))
}
/// The selected, editable gradient mesh and its points that an Eyedropper click at `p` recolors
/// ([`crate::meshedit::color_points`]): the topmost visible object within reach of `p` (locked art
/// included, clipping applied) must be that mesh, and the points are its point within reach of
/// `p`, else the four points around its patch under `p`.
fn selected_mesh_points(cx: &ToolContext, p: Point) -> Option<(NodeId, Vec<usize>)> {
let tol = cx.tol(5.0);
let opt = sample_options(cx);
let leaf = hit_test_visible(cx.doc, p, HitOptions { tol: opt.tol.max(tol), ..opt })?.leaf;
if !cx.selection.contains(leaf) || !cx.doc.editable()(leaf) {
return None;
}
let Some(NodeKind::Mesh(m)) = cx.doc.node(leaf).map(|n| &n.kind) else { return None };
Some((leaf, crate::meshedit::color_points(m, p, tol)?))
}
impl Tool for EyedropperTool {
fn id(&self) -> &'static str {
"eyedropper"
@@ -474,6 +521,17 @@ impl Tool for EyedropperTool {
return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)];
}
let stop = self.stop.as_ref().zip(cx.gradient_stop);
// A plain click on a selected gradient mesh gives the fill color to the point there, else
// to the four points of the patch there.
if stop.is_none()
&& !ev.mods.alt
&& !ev.mods.shift
&& let Paint::Solid { color, .. } = &cx.paint.fill
&& let Some((id, points)) = selected_mesh_points(cx, ev.pos)
{
let params = json!({ "id": id.0, "points": points, "color": color_json(color), "keepModel": true });
return vec![Action::Exec("object.mesh.setPointColor".into(), params)];
}
// Reading a source is independent of its editability. Only Alt's reverse operation
// writes to the clicked object; Shift+Alt appends its appearance to the selection.
let source = if ev.mods.alt && !ev.mods.shift && stop.is_none() {
@@ -488,11 +546,20 @@ impl Tool for EyedropperTool {
return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0, how: true }))];
}
let image = matches!(n.kind, NodeKind::Image(_));
if !(ev.mods.shift || stop.is_some() || image) {
// Picked mesh points take only a color sampled from other art or an image: the sample goes
// to them as a fill, and to nothing else that is selected. A click on a mesh with picked
// points is handled as before.
let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] };
let meshes = if meshes.contains(&src) { vec![] } else { meshes };
if !(ev.mods.shift || stop.is_some() || image || !meshes.is_empty()) {
return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))];
}
let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] };
let color = color_json(&c);
if !meshes.is_empty() {
let ids: Vec<u64> = meshes.iter().map(|id| id.0).collect();
return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))];
}
let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] };
let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())];
self.stop = None;
@@ -506,15 +573,21 @@ impl Tool for EyedropperTool {
if let Some(o) = options.as_object_mut() {
o.insert("stop".into(), json!(self.stop));
o.insert("brushKeyColor".into(), json!(self.brush_key_color));
if !self.mesh_points.is_empty() {
let points: Vec<Value> = self.mesh_points.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect();
o.insert("meshPoints".into(), Value::Array(points));
}
}
options
}
/// Accept a stop target or the selection transferred from the Type tool.
/// Accept a stop target, or the selection or the mesh points picked, transferred from the
/// Type tool or a tool that picks mesh points.
fn set_option(&mut self, key: &str, value: &Value) {
match key {
"stop" => self.stop = value.as_str().map(str::to_string),
"brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false),
"meshPoints" => self.mesh_points = crate::meshedit::points_of(value),
"textSelection" => self.text_selection.set_option(key, value),
_ => {}
}
@@ -525,9 +598,13 @@ impl Tool for EyedropperTool {
self.text_selection.after_command(cx)
}
/// Keep the sampled character range highlighted without activating text input.
/// Keep the sampled character range highlighted without activating text input, and the picked
/// points of selected gradient meshes filled, as the tools that picked them show them.
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
if self.text_selection.options().get("editing").is_some_and(|v| !v.is_null()) { self.text_selection.overlays(cx) } else { vec![] }
let mut out =
if self.text_selection.options().get("editing").is_some_and(|v| !v.is_null()) { self.text_selection.overlays(cx) } else { vec![] };
out.extend(live_points(cx, &self.mesh_points).map(|(_, p)| Overlay::Anchor { p, color: crate::draw2::FEEDBACK, filled: true, size: 5.0 }));
out
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
@@ -607,6 +684,82 @@ mod tests {
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 400.0)).is_empty());
}
/// With points of a selected gradient mesh picked, a click on other art samples the color under
/// the cursor into those points as a fill, as a Shift-click does. Unselected, or with the picks
/// out of range, on a locked mesh, or on the mesh itself, the click copies the appearance as
/// before; Alt still applies in reverse.
#[test]
fn picked_mesh_points_take_the_color_a_click_samples() {
use vectorcraft_doc::{Document, GradientMesh};
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let mesh = d.alloc_id();
let grid = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE);
d.insert(Some(l), 0, Node::new(mesh, NodeKind::Mesh(grid))).unwrap();
let red = d.alloc_id();
let mut art = (*filled_rect(Rect::new(300.0, 100.0, 350.0, 150.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)))).clone();
art.id = red;
d.insert(Some(l), usize::MAX, art).unwrap();
let p = paint();
let mut s = Selection::default();
s.set([mesh]);
let mut t = EyedropperTool::default();
t.set_option("meshPoints", &json!([{"id": mesh.0, "index": 1}, {"id": "x"}, {"id": mesh.0, "index": 3}]));
assert_eq!(t.options()["meshPoints"], json!([{"id": mesh.0, "index": 1}, {"id": mesh.0, "index": 3}]), "malformed entries are left out");
// The picked points show filled while the mesh is selected.
let anchors: Vec<Point> = t
.overlays(&cx(&d, &s, &p))
.into_iter()
.filter_map(|o| match o {
Overlay::Anchor { p, filled: true, .. } => Some(p),
_ => None,
})
.collect();
assert_eq!(anchors, [Point::new(200.0, 100.0), Point::new(200.0, 200.0)]);
assert!(t.overlays(&cx(&d, &Selection::default(), &p)).is_empty());
let click = |t: &mut EyedropperTool, s: &Selection, m: Mods| {
t.pointer(&cx(&d, s, &p), &PointerEvent::new(PointerKind::Down, 325.0, 125.0).with_mods(m))
};
let sample = vec![Action::Exec(
"paint.sampleColor".into(),
json!({"color": color_json(&Color::rgb(1.0, 0.0, 0.0)), "stroke": false, "ids": [mesh.0]}),
)];
assert_eq!(click(&mut t, &s, Mods::default()), sample);
assert_eq!(click(&mut t, &s, Mods { shift: true, ..Default::default() }), sample);
// Other selected art does not take the sample.
let mut both = Selection::default();
both.set([mesh, red]);
assert_eq!(click(&mut t, &both, Mods::default()), sample, "only the picked mesh");
let alt = click(&mut t, &s, Mods { alt: true, ..Default::default() });
assert_eq!(alt, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": red.0, "reverse": true}))]);
// The mesh deselected, the picks stand for nothing.
let copy = vec![Action::Exec("appearance.copyFrom".into(), json!({"source": red.0}))];
assert_eq!(click(&mut t, &Selection::default(), Mods::default()), copy);
// Selected again, as Direct Selection keeps them, the picks take the sample again.
assert_eq!(click(&mut t, &s, Mods::default()), sample, "the mesh selected again");
// A click on the picked mesh itself (with no solid fill) copies its appearance as before, and
// a Shift-click samples into the active fill as before.
let mut unfilled = paint();
unfilled.fill = Paint::None;
let on_mesh =
|t: &mut EyedropperTool, m: Mods| t.pointer(&cx(&d, &s, &unfilled), &PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(m));
let own = vec![Action::Exec("appearance.copyFrom".into(), json!({"source": mesh.0}))];
assert_eq!(on_mesh(&mut t, Mods::default()), own, "a click on the mesh");
let shift = on_mesh(&mut t, Mods { shift: true, ..Default::default() });
assert_eq!(shift, vec![Action::Exec("paint.sampleColor".into(), json!({"color": color_json(&Color::WHITE)}))], "a Shift-click on the mesh");
// A locked mesh's picks stand for nothing.
let mut locked = d.clone();
locked.node_mut(mesh).unwrap().locked = true;
let a = t.pointer(&cx(&locked, &s, &p), &PointerEvent::new(PointerKind::Down, 325.0, 125.0));
assert_eq!(a, copy, "a locked mesh");
assert!(t.overlays(&cx(&locked, &s, &p)).is_empty());
t.set_option("meshPoints", &json!([{"id": mesh.0, "index": 4}]));
assert_eq!(click(&mut t, &s, Mods::default()), copy, "a point the mesh does not have");
t.set_option("meshPoints", &json!([]));
assert!(t.options().get("meshPoints").is_none());
assert_eq!(click(&mut t, &s, Mods::default()), copy);
}
/// On a clip group's mask edge, where the art it clips lies over it, the eyedropper copies the
/// art's appearance, not the unpainted clipping path's (the selection tools take the path there).
#[test]
@@ -1429,6 +1582,70 @@ mod tests {
assert_eq!(sampled_hex(&a), "#404040");
}
/// With a gradient mesh selected, a click on one of its points gives that point the fill color,
/// and a click inside a patch gives it to the patch's four points. Unselected, a click copies
/// the mesh's appearance as before, and Shift still samples.
#[test]
fn a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color() {
use vectorcraft_doc::{Document, GradientMesh};
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let mesh = GradientMesh::from_surface(2, 2, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE);
d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap();
let mut p = paint();
p.fill = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let red = color_json(&Color::rgb(1.0, 0.0, 0.0));
let set = |points: Value| {
vec![Action::Exec("object.mesh.setPointColor".into(), json!({"id": id.0, "points": points, "color": red, "keepModel": true}))]
};
let mut s = Selection::default();
let click = |s: &Selection, p: &crate::PaintDefaults, x: f64, y: f64, m: Mods| {
EyedropperTool::default().pointer(&cx(&d, s, p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(m))
};
let plain = Mods::default();
let a = click(&s, &p, 125.0, 125.0, plain);
assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": id.0}))], "an unselected mesh");
s.set([id]);
assert_eq!(click(&s, &p, 151.0, 149.0, plain), set(json!([4])), "the point near the click");
assert_eq!(click(&s, &p, 125.0, 125.0, plain), set(json!([0, 1, 3, 4])), "the patch's four points");
assert_eq!(click(&s, &p, 175.0, 175.0, plain), set(json!([4, 5, 7, 8])));
let shift = Mods { shift: true, ..Default::default() };
assert!(matches!(&click(&s, &p, 125.0, 125.0, shift)[0], Action::Exec(c, _) if c == "paint.sampleColor"));
let alt = Mods { alt: true, ..Default::default() };
assert!(matches!(&click(&s, &p, 125.0, 125.0, alt)[0], Action::Exec(c, v) if c == "appearance.copyFrom" && v["reverse"] == true));
// Off the mesh, or with a fill that is not a solid color, nothing goes to its points.
assert!(click(&s, &p, 400.0, 400.0, plain).is_empty());
p.fill = Paint::None;
assert!(matches!(&click(&s, &p, 125.0, 125.0, plain)[0], Action::Exec(c, _) if c == "appearance.copyFrom"));
}
/// An unselected object on top of a selected mesh's point keeps the click: it copies that
/// object's appearance, and the mesh's points keep their colors.
#[test]
fn a_click_on_an_object_over_a_selected_mesh_copies_that_object() {
use vectorcraft_doc::{Document, GradientMesh};
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let id = d.alloc_id();
let mesh = GradientMesh::from_surface(2, 2, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE);
d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap();
let top = d.alloc_id();
let mut cover = (*filled_rect(vectorcraft_geom::Rect::new(140.0, 140.0, 160.0, 160.0), Paint::solid(Color::BLACK))).clone();
cover.id = top;
d.insert(Some(l), usize::MAX, cover).unwrap();
let mut p = paint();
p.fill = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let mut s = Selection::default();
s.set([id]);
let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0));
assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": top.0}))]);
// Locked, it is still what the click samples.
d.node_mut(top).unwrap().locked = true;
let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0));
assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": top.0}))], "a locked object on top");
}
/// Finding the point in a mesh counts the points it looks at in every patch: a 20 × 20 mesh
/// takes more than a thousand units of work.
#[test]
+7
View File
@@ -165,6 +165,13 @@ impl Tool for LassoTool {
self.mesh.options()
}
/// Pick the gradient mesh points the Eyedropper held (`meshPoints`).
fn set_option(&mut self, key: &str, value: &Value) {
if key == "meshPoints" {
self.mesh.set_options(value);
}
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id));
if self.active && self.points.len() >= 2 {
+7 -3
View File
@@ -38,11 +38,12 @@ pub enum Palette {
#[serde(alias = "Limited")]
Limited,
/// As many colours as the image's tones need, up to [`FULL_TONE_MAX`] (photos, gradients):
/// `color_detail` sets how close two colours may be and stay apart.
/// `color_detail` sets how close two colours may be and stay apart. Before merging colors that
/// look alike, it splits to at least one color per step of `color_detail` where the image has that many.
#[serde(alias = "Full Tone")]
FullTone,
/// Flat art (a few colours cover nearly all of it) traces with exactly those colours, anything
/// else as Full Tone.
/// else with as many as its tones need, without Full Tone's least count and merging close RGB colors.
#[serde(alias = "Automatic")]
Automatic,
/// The most used colours of a swatch library ([`TraceParams::swatches`]), at most `colors` of
@@ -243,7 +244,10 @@ pub fn preset(name: &str) -> Option<TraceParams> {
// many as its tones need where it is not.
// (Color detail 85: a colour on a hundredth of the picture is still one of its colours.)
"auto color" => TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..color(6, 65.0, 60.0, 16, Method::Abutting) },
"high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping),
// A photo's tones: as many colors as they need (Full Tone), split until no color spans more
// than about 21 levels of a channel and into at least 85 (Color detail 85) before colors that
// look alike merge, as abutting shapes. VectorCraft's own values.
"high fidelity photo" => TraceParams { palette: Palette::FullTone, color_detail: 85.0, ..color(64, 50.0, 50.0, 5, Method::Abutting) },
"low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping),
"3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting),
"6 colors" => color(6, 50.0, 50.0, 8, Method::Abutting),
+86 -12
View File
@@ -93,7 +93,7 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized
let g = l.round().clamp(0.0, 255.0) as u8;
[g, g, g]
});
let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[]);
let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[], Alike::Rgb);
(if settles_wide(params) { settled_wide(q, img, &own, true) } else { settled(q, img, &own) }, vec![])
}
// Logo mode traces without quantising; asked directly, it quantises like Color.
@@ -175,12 +175,14 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized
img.rgba.as_chunks::<4>().0.iter().map(|p| if p[3] < 128 { TRANSPARENT } else { lut[hk.key(p[0], p[1], p[2])] }).collect();
let palette = centers.iter().map(|c| [c[0].round() as u8, c[1].round() as u8, c[2].round() as u8]).collect();
let q = compact(labels, palette);
// A swatch library's colours are used as they are.
// A swatch library's colours are used as they are. Full Tone's colors merge only when
// they look alike (see `Alike`).
if library {
return (q, false);
}
let alike = if params.palette == Palette::FullTone { Alike::Seen } else { Alike::Rgb };
let before = q.palette.len();
let q = merge_mixed(q, img.width as usize, img.height as usize, &rare);
let q = merge_mixed(q, img.width as usize, img.height as usize, &rare, alike);
let merged = q.palette.len() < before;
(q, merged)
};
@@ -309,16 +311,38 @@ pub(crate) fn tests_oklab(c: [u8; 3]) -> [f64; 3] {
oklab(c.map(f64::from))
}
/// Which colors [`merge_mixed`] takes for one color that noise split.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Alike {
/// Close in RGB: under 30 levels apart and thoroughly mixed, or under 12 and mixed in patches.
/// Used for Grayscale and for every Color palette but Full Tone (Automatic included).
Rgb,
/// Close to the eye: under [`FULL_TONE_ALIKE`] apart in Oklab and thoroughly mixed, or under
/// [`FULL_TONE_PATCHES`] and mixed in patches (compression blocks). Full Tone's neighboring tones
/// of a smooth photo are about as close in RGB as noise makes one color, and mixed along their
/// soft border, so the RGB test would take most of them for one color.
Seen,
}
/// How far apart (Oklab × 100) two thoroughly mixed Full Tone colors may lie and still be merged
/// as one color that noise split: a little more than the least difference one sees (see [`oklab`]).
const FULL_TONE_ALIKE: f64 = 5.0;
/// How far apart (Oklab × 100) two Full Tone colors mixed in patches may lie and still be merged:
/// the blocks of one flat color that compression shifted by a few levels each.
const FULL_TONE_PATCHES: f64 = 1.5;
/// `q` with the colours that noise made of one colour merged, largest mix first.
///
/// Asked for more colours than a picture has, k-means splits a flat colour along its noise, and
/// the two halves would trace as specks of one all over the other. Such halves are close (under 30
/// levels apart: noise is about as strong in a dark colour as in a light one, so the distance is
/// taken in RGB) and thoroughly mixed: the pixels of the lesser one have, on average, more than
/// half a neighbour of the other each; or they are closer still (under 12 levels) and mixed in
/// patches (compression blocks). The bands of a gradient are close too, but each keeps to itself
/// and they stay apart. The colours in `keep` merge with none.
fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized {
/// the two halves would trace as specks of one all over the other. Such halves are close and
/// thoroughly mixed: the pixels of the lesser one have, on average, more than half a neighbour of
/// the other each; or they are closer still and mixed in patches (compression blocks). The bands
/// of a gradient are close too, but each keeps to itself and they stay apart. The colours in
/// `keep` merge with none. Close is under 30 RGB levels apart for thoroughly mixed colours and
/// under 12 for patches with [`Alike::Rgb`], and in Oklab under [`FULL_TONE_ALIKE`] and
/// [`FULL_TONE_PATCHES`] with [`Alike::Seen`].
fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]], alike: Alike) -> Quantized {
let k = q.palette.len();
// A rare colour kept on purpose (see `rare_colours`) is distinct by choice: it merges with none.
let kept: Vec<bool> = q.palette.iter().map(|c| keep.contains(c)).collect();
@@ -340,6 +364,13 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized
}
}
let mut color: Vec<[f64; 3]> = q.palette.iter().map(|c| c.map(f64::from)).collect();
// Each colour in Oklab, for `Alike::Seen`, worked out once and again only for a colour that
// takes in another.
let mut lab: Vec<[f64; 3]> = if alike == Alike::Seen { color.iter().map(|&c| oklab(c)).collect() } else { vec![] };
let seen_apart = |lab: &[[f64; 3]], a: usize, b: usize| match (lab.get(a), lab.get(b)) {
(Some(la), Some(lb)) => (0..3).map(|c| (la[c] - lb[c]).powi(2)).sum::<f64>().sqrt(),
_ => f64::INFINITY,
};
// Which colour each has merged into (itself when none).
let mut into: Vec<usize> = (0..k).collect();
loop {
@@ -350,14 +381,30 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized
continue;
}
let mixed = touch[a * k + b] / count[a].min(count[b]);
let apart = (0..3).map(|c| (color[a][c] - color[b][c]).powi(2)).sum::<f64>().sqrt();
if (mixed > 0.5 && apart < 30.0 || mixed > 0.15 && apart < 12.0) && best.is_none_or(|x| mixed > x.0) {
// Two colours this little mixed merge under neither test.
if mixed <= 0.15 {
continue;
}
let merges = match alike {
Alike::Rgb => {
let apart = (0..3).map(|c| (color[a][c] - color[b][c]).powi(2)).sum::<f64>().sqrt();
mixed > 0.5 && apart < 30.0 || apart < 12.0
}
Alike::Seen => {
let apart = seen_apart(&lab, a, b);
mixed > 0.5 && apart < FULL_TONE_ALIKE || apart < FULL_TONE_PATCHES
}
};
if merges && best.is_none_or(|x| mixed > x.0) {
best = Some((mixed, a, b));
}
}
}
let Some((_, a, b)) = best else { break };
color[a] = [0, 1, 2].map(|c| (color[a][c] * count[a] + color[b][c] * count[b]) / (count[a] + count[b]));
if let Some(l) = lab.get_mut(a) {
*l = oklab(color[a]);
}
count[a] += count[b];
count[b] = 0.0;
into[b] = a;
@@ -410,6 +457,33 @@ mod tests {
assert!(own.iter().all(|o| *o == own[0]));
}
#[test]
fn full_tone_merges_only_mixed_colors_that_look_alike() {
// Two colors in a checkerboard: every pixel has four neighbors of the other color.
let mixed =
|a: [u8; 3], b: [u8; 3]| Quantized { labels: (0..16 * 16).map(|i| ((i % 16 + i / 16) % 2) as u16).collect(), palette: vec![a, b] };
let colors = |q: Quantized, alike: Alike| merge_mixed(q, 16, 16, &[], alike).palette.len();
// Gray and a greener gray, 22 levels apart (about 6.4 in Oklab): one color in RGB, two that look different.
let (gray, green) = ([128, 128, 128], [128, 150, 128]);
assert_eq!(colors(mixed(gray, green), Alike::Rgb), 1);
assert_eq!(colors(mixed(gray, green), Alike::Seen), 2);
// Two grays 3 levels apart (about 1 in Oklab): one color either way.
assert_eq!(colors(mixed(gray, [131; 3]), Alike::Rgb), 1);
assert_eq!(colors(mixed(gray, [131; 3]), Alike::Seen), 1);
// Side by side, not mixed: two colors either way.
let halves = Quantized { labels: (0..16 * 16).map(|i| u16::from(i % 16 >= 8)).collect(), palette: vec![[128; 3], [131; 3]] };
assert_eq!(colors(halves.clone(), Alike::Rgb), 2);
assert_eq!(colors(halves, Alike::Seen), 2);
// In 8 × 8 blocks, mixed in patches: grays 3 levels apart merge either way; grays 6 levels
// apart (about 10 in RGB, more than 1.5 in Oklab) merge only in RGB.
let blocks =
|b: [u8; 3]| Quantized { labels: (0..16 * 16).map(|i| ((i % 16 / 8 + i / 16 / 8) % 2) as u16).collect(), palette: vec![gray, b] };
assert_eq!(colors(blocks([131; 3]), Alike::Rgb), 1);
assert_eq!(colors(blocks([131; 3]), Alike::Seen), 1);
assert_eq!(colors(blocks([134; 3]), Alike::Rgb), 1);
assert_eq!(colors(blocks([134; 3]), Alike::Seen), 2);
}
#[test]
fn a_picture_with_no_pixels_is_not_shared_out() {
// No band for each of the rows of a picture with no columns, however many rows it has.
+75 -16
View File
@@ -138,6 +138,12 @@ pub(super) fn labs(colors: &[[f64; 3]]) -> Vec<[f64; 3]> {
/// The most colours Full Tone (and Automatic on continuous-tone images) makes.
pub const FULL_TONE_MAX: usize = 256;
/// The fewest colors Palette › Full Tone splits into, before merging, at Color detail `detail`
/// (0–1): one per step of Color detail, 85 at 85. Automatic does not use it.
pub(super) fn full_tone_least(detail: f64) -> usize {
(detail.clamp(0.0, 1.0) * 100.0).round() as usize
}
/// A histogram bin in use: its index, mean colour and pixel count.
pub(super) type Used = (usize, [f64; 3], f64);
@@ -152,11 +158,14 @@ pub(super) fn color_palette(used: &[Used], params: &TraceParams) -> Vec<[f64; 3]
// Full Tone: split until no colour box is wider than 96 (few colours) … 8 (many) levels per
// channel, which is one histogram bin.
let full_tone = || refine(used, centers(&median_cut(used, FULL_TONE_MAX, 96.0 - 88.0 * detail)));
// Palette › Full Tone also splits into at least one color per step of Color detail, where the
// picture has that many (see [`full_tone_least`]).
let full_tone_palette = || refine(used, centers(&median_cut_least(used, FULL_TONE_MAX, 96.0 - 88.0 * detail, full_tone_least(detail))));
// A Limited palette of 9 to 16 colors keeps a nearly flat dark ground in one color (see [`kmeans_rgb`]).
let limited = || kmeans_rgb(used, k, if FEW_COLORS.contains(&k) { LEAST_APART } else { 0.0 });
match params.palette {
Palette::Limited => limited(),
Palette::FullTone => full_tone(),
Palette::FullTone => full_tone_palette(),
Palette::Automatic => match flat_colors(used, detail) {
Some(n) => flat_palette(used, n),
None => full_tone(),
@@ -285,7 +294,7 @@ const GRAY: f64 = 3.0;
/// (see [`median_cut_apart`]). A large, nearly flat dark ground then keeps one color, and the
/// color it would have taken goes to another cut.
fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> {
refine(used, centers(&median_cut_apart(used, k, 0.0, apart)))
refine(used, centers(&median_cut_apart(used, k, 0.0, apart, 0)))
}
/// Divisive clustering in the manner of median cut, but each box is cut where that leaves its two
@@ -295,21 +304,34 @@ fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> {
/// and leaves two smaller colours in one box. Boxes are cut while there are fewer than `k` and
/// some box spans more than `spread` levels of a channel.
pub(super) fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox> {
median_cut_apart(used, k, spread, 0.0)
median_cut_apart(used, k, spread, 0.0, 0)
}
/// [`median_cut`], except when both sides of a cut have a dark gray mean color (see [`DARK`] and
/// [`GRAY`]) and the two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain
/// is scaled by (`d` / `apart`)². With `apart` 0 it is [`median_cut`].
fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<ColorBox> {
/// [`median_cut`], then, while there are fewer than `least` boxes, cutting the boxes no wider than
/// `spread` too, the one whose cut gains most first.
fn median_cut_least(used: &[Used], k: usize, spread: f64, least: usize) -> Vec<ColorBox> {
median_cut_apart(used, k, spread, 0.0, least)
}
/// [`median_cut`] with at least `least` boxes where the bins allow (see [`median_cut_least`]),
/// except when both sides of a cut have a dark gray mean color (see [`DARK`] and [`GRAY`]) and the
/// two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain is scaled by
/// (`d` / `apart`)². With `apart` 0 and `least` 0 it is [`median_cut`].
fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64, least: usize) -> Vec<ColorBox> {
if used.is_empty() {
return vec![ColorBox { mean: [255.0; 3], weight: 0.0, peak: 0.0 }];
}
/// A box's bins and its best cut: (gain, bins sorted along the cut's channel, bins on the first side).
/// A box's bins, its widest span over the channels, and its best cut: (gain, bins sorted along
/// the cut's channel, bins on the first side).
struct Cut {
bins: Vec<usize>,
widest: f64,
best: Option<(f64, Vec<usize>, usize)>,
}
// Boxes no wider than `spread` are cut only while there are fewer than `least` boxes. A box made
// when there are already `least` boxes or more is never cut unless it is wider, so its cut is
// not planned.
let narrowest = |boxes_after: usize| if boxes_after < least { 0.0 } else { spread.max(0.0) };
// How much of a cut's gain counts when its sides' mean colors are `a` and `b`: all of it when
// they look different or either is not a dark gray, less as two dark grays look more alike.
let dark_gray = |c: [f64; 3]| c[0] < DARK && c[1].hypot(c[2]) < GRAY;
@@ -320,7 +342,8 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col
}
((0..3).map(|q| (a[q] - b[q]).powi(2)).sum::<f64>() / (apart * apart)).min(1.0)
};
let plan = |bins: Vec<usize>| {
let plan = |bins: Vec<usize>, boxes_after: usize| {
let narrowest = narrowest(boxes_after);
let mut best: Option<(f64, Vec<usize>, usize)> = None;
let widest = (0..3)
.map(|ch| {
@@ -328,7 +351,7 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col
v.clone().fold(f64::NEG_INFINITY, f64::max) - v.fold(f64::INFINITY, f64::min)
})
.fold(0.0, f64::max);
if bins.len() >= 2 && widest > spread.max(0.0) {
if bins.len() >= 2 && widest > narrowest {
for ch in 0..3 {
let mut sorted = bins.clone();
sorted.sort_by(|x, y| used[*x].1[ch].total_cmp(&used[*y].1[ch]));
@@ -366,18 +389,26 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col
}
}
}
Cut { bins, best }
Cut { bins, widest, best }
};
let mut boxes = vec![plan((0..used.len()).collect())];
let mut boxes = vec![plan((0..used.len()).collect(), 1)];
while boxes.len() < k {
let gain = |c: &Cut| c.best.as_ref().map_or(f64::NEG_INFINITY, |b| b.0);
let Some(bi) = (0..boxes.len()).filter(|&i| boxes[i].best.is_some()).max_by(|&a, &b| gain(&boxes[a]).total_cmp(&gain(&boxes[b]))) else {
// The boxes wider than `spread` first; when none is left and there are fewer than `least`,
// any box with a cut.
let most = |wide: bool| {
(0..boxes.len())
.filter(|&i| boxes[i].best.is_some() && (!wide || boxes[i].widest > spread.max(0.0)))
.max_by(|&a, &b| gain(&boxes[a]).total_cmp(&gain(&boxes[b])))
};
let Some(bi) = most(true).or_else(|| if boxes.len() < least { most(false) } else { None }) else {
break;
};
let Some((_, mut sorted, at)) = boxes.swap_remove(bi).best else { break };
let tail = sorted.split_off(at);
boxes.push(plan(sorted));
boxes.push(plan(tail));
let after = boxes.len() + 2;
boxes.push(plan(sorted, after));
boxes.push(plan(tail, after));
}
boxes
.iter()
@@ -467,7 +498,9 @@ mod tests {
assert_eq!(palette(Palette::DocumentLibrary, colors), plain(colors as usize), "{colors} colors");
}
let detail = (TraceParams::default().color_detail / 100.0).clamp(0.0, 1.0);
assert_eq!(palette(Palette::FullTone, 16), refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail))));
// Full Tone's median cut makes at least one color per step of Color detail.
let full_tone = refine(&used, centers(&median_cut_least(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail, full_tone_least(detail))));
assert_eq!(palette(Palette::FullTone, 16), full_tone);
let automatic = match flat_colors(&used, detail) {
Some(n) => plain(n),
None => refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail))),
@@ -475,6 +508,32 @@ mod tests {
assert_eq!(palette(Palette::Automatic, 16), automatic);
}
#[test]
fn full_tone_makes_one_color_per_step_of_color_detail() {
// 256 grays, 1,200 pixels each: the width limit alone gives fewer colors than Color detail.
let ramp = bins((0..256).map(|g| ([f64::from(g); 3], 1200.0)));
let colors = |used: &[Used], color_detail: f64| {
color_palette(used, &TraceParams { palette: Palette::FullTone, color_detail, ..TraceParams::default() }).len()
};
assert!(median_cut(&ramp, FULL_TONE_MAX, 96.0 - 88.0 * 0.85).len() < 85);
assert_eq!(colors(&ramp, 85.0), 85);
assert_eq!(colors(&ramp, 40.0), 40);
// A picture of three colors keeps three.
let three = bins([([0.0; 3], 100.0), ([128.0; 3], 100.0), ([255.0; 3], 100.0)]);
assert_eq!(colors(&three, 85.0), 3);
// A large, finely shaded area does not take the count from a small pair of reds 40 levels
// apart, wider than one color may be at Color detail 85: the pair keeps two colors.
let shaded = bins((0..128).map(|g| ([f64::from(g); 3], 10_000.0)).chain([([200.0, 0.0, 0.0], 1.0), ([240.0, 0.0, 0.0], 1.0)]));
let reds = color_palette(&shaded, &TraceParams { palette: Palette::FullTone, color_detail: 85.0, ..TraceParams::default() });
assert!(reds.len() >= 85, "{} colors", reds.len());
for red in [200.0, 240.0] {
assert!(reds.iter().any(|c| (c[0] - red).abs() < 1.0 && c[1] < 1.0), "no color for red {red}: {reds:?}");
}
// Automatic's continuous-tone colors are not raised to the count.
let automatic = color_palette(&ramp, &TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..TraceParams::default() });
assert!(automatic.len() < 85, "{} colors with Automatic", automatic.len());
}
/// `colors`, each with `n` pixels, as histogram bins.
fn bins(colors: impl IntoIterator<Item = ([f64; 3], f64)>) -> Vec<Used> {
colors.into_iter().enumerate().map(|(i, (c, n))| (i, c, n)).collect()
+65 -3
View File
@@ -944,6 +944,16 @@ fn presets_have_their_paths_corners_and_noise() {
assert_eq!(colors, [64, 20, 3, 6, 16, 8]);
}
#[test]
fn high_fidelity_photo_traces_in_full_tone() {
// As many colors as the tones need, split until no color spans more than about 21 levels, as
// abutting shapes.
let p = preset("High Fidelity Photo").unwrap();
assert_eq!((p.palette, p.color_detail, p.method), (Palette::FullTone, 85.0, Method::Abutting));
// Low Fidelity Photo keeps its 20 colors.
assert_eq!(preset("Low Fidelity Photo").unwrap().palette, Palette::Limited);
}
#[test]
fn params_json_roundtrip_and_partial() {
let p = preset("6 Colors").unwrap();
@@ -1213,12 +1223,14 @@ fn full_tone_follows_the_tones_the_image_has() {
}
#[test]
fn automatic_traces_flat_art_with_its_colours_and_photos_in_full_tone() {
fn automatic_traces_flat_art_with_its_colours_and_photos_in_continuous_tone() {
let flat = palette(&flat_quads(), Palette::Automatic, 2, 50.0);
assert_eq!(flat.len(), 4, "the four flat colours, whatever `colors` says: {flat:?}");
assert!(flat.iter().any(|c| c[0] > 200 && c[1] < 60 && c[2] < 60), "red is one of them: {flat:?}");
let tone = palette(&gradient(), Palette::Automatic, 2, 50.0);
assert_eq!(tone.len(), palette(&gradient(), Palette::FullTone, 2, 50.0).len(), "continuous tone: as Full Tone");
// Continuous tone: as many colors as the tones need, without Full Tone's least count.
let full = palette(&gradient(), Palette::FullTone, 2, 50.0);
assert!(tone.len() > 4 && tone.len() <= full.len(), "{} colors, {} in Full Tone", tone.len(), full.len());
}
#[test]
@@ -1713,6 +1725,56 @@ fn jitter(x: u32, y: u32, salt: u32) -> f64 {
f64::from(v & 0xFFFF) / 32768.0 - 1.0
}
#[test]
fn full_tone_keeps_more_of_a_noisy_ramps_tones() {
// Gray to green with grain: Full Tone's neighboring tones are close in RGB and mixed along
// their borders, and still look different.
let img = Raster::from_fn(256, 96, |x, y| {
let v = |k: u32, base: f64, slope: f64| (base + slope * f64::from(x) + 8.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8;
[v(0, 100.0, 0.0), v(1, 40.0, 0.7), v(2, 100.0, 0.0), 255]
});
let params = TraceParams { mode: Mode::Color, palette: Palette::FullTone, color_detail: 85.0, ..TraceParams::default() };
// Median cut gives at least 85 (one per step of Color detail). Merging the ones that look alike
// leaves 6 (one per 30 or so levels of the ramp); merging close RGB colors would leave 4.
let n = quantize(&img, &params).palette.len();
assert!(n >= 6, "{n} tones");
// Automatic traces continuous tone without Full Tone's least count and keeps merging close RGB colors.
let automatic = quantize(&img, &TraceParams { palette: Palette::Automatic, ..params }).palette.len();
assert!(automatic < n, "{automatic} tones with Automatic, {n} with Full Tone");
}
#[test]
fn full_tone_traces_a_noisy_dark_ground_like_a_light_one() {
// A gray ground with up to 8 levels of grain a channel. The same grain lies farther apart in
// Oklab in a dark gray than in a light one; the dark ground still takes about as many colors
// and shapes as the light one (32 and 53 against 31 and 52 when measured).
let ground = |gray: f64| {
let img = Raster::from_fn(192, 128, |x, y| {
let c = |k: u32| (gray + 8.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8;
[c(0), c(1), c(2), 255]
});
trace(&img, &preset("High Fidelity Photo").unwrap())
};
let (dark, light) = (ground(28.0), ground(200.0));
assert!(dark.palette.len() <= light.palette.len() + 2, "{} colors dark, {} light", dark.palette.len(), light.palette.len());
assert!(dark.paths.len() <= light.paths.len() + 6, "{} shapes dark, {} light", dark.paths.len(), light.paths.len());
}
#[test]
fn full_tone_merges_a_flat_colors_compression_blocks() {
// Three flat colors stored in 8 × 8 blocks, each block off by up to 8 levels a channel, with a
// little grain: the blocks of one color look alike and are mixed in patches, so each flat
// color traces as one shape in Full Tone too, not as squares of near colors.
let bases = [[200.0, 150.0, 120.0], [70.0, 120.0, 190.0], [40.0, 90.0, 40.0]];
let img = Raster::from_fn(192, 128, |x, y| {
let base: [f64; 3] = bases[(x / 64) as usize];
let c = |k: u32| (base[k as usize] + 8.0 * jitter(x / 8, y / 8, k) + 1.5 * jitter(x, y, k + 7)).round().clamp(0.0, 255.0) as u8;
[c(0), c(1), c(2), 255]
});
let res = trace(&img, &preset("High Fidelity Photo").unwrap());
assert_eq!((res.palette.len(), res.paths.len()), (3, 3), "{:?}", res.palette);
}
/// Three flat colours (a navy field, a yellow disc, a green bar) drawn anti-aliased, with `noise`
/// levels of noise per channel.
fn three_colour_art(noise: f64) -> Raster {
@@ -2013,7 +2075,7 @@ fn a_nearly_flat_dark_ground_keeps_one_color() {
#[test]
fn a_noisy_gradient_keeps_its_tones_without_specks() {
// Tones 0–255 across with noise larger than High Fidelity Photo's 64 steps are apart.
// Tones 0–255 across with up to 5 levels of noise a channel.
let img = Raster::from_fn(256, 96, |x, y| {
let c = |k: u32| (f64::from(x) + 5.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8;
[c(0), c(1), c(2), 255]
+1 -1
View File
@@ -66,8 +66,8 @@ use overlays::selected_anchor;
use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay};
pub use panes::Panes;
pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area};
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
pub(crate) use raster::{color_image, color_image_owned, render_job};
pub use selection_marks::SelectionMarks;
#[cfg(test)]
pub(crate) use task_bar::chip_paints;
+36 -1
View File
@@ -50,7 +50,9 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf:
/// A panel drag ([`widgets::PanelDrag`]) dropped on art acts on the object under the pointer,
/// selected or not: a paint (swatches, a Fill/Stroke proxy, the Gradient panel's thumbnail) goes
/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it), the
/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it; a
/// solid fill color on a selected gradient mesh recolors the mesh point under the pointer, else the
/// four points of the patch there, with `object.mesh.setPointColor`), the
/// Appearance panel's thumbnail gives the object (the topmost one hit) the appearance it carries
/// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on
/// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary`
@@ -89,6 +91,21 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons
}
return;
}
// A solid fill color on a selected gradient mesh: the point under the pointer, else the four
// points around the patch there, take it. The selected meshes are looked at directly, so
// Object Selection by Path Only and the selection tolerance do not stop it.
if let widgets::PanelDrag::Paint { params, paint, .. } = &*d
&& !params.is_null()
&& let Some(color) = paint.color()
&& crate::panels::proxy_cmd(app, false) == "paint.setFill"
&& let Some((id, points)) = selected_mesh_drop(app, xf.to_doc(pos), xf.zoom)
{
let params = json!({"id": id.0, "points": points, "color": crate::panels::color_json(&color), "keepModel": true});
if let Err(e) = app.run("object.mesh.setPointColor", params) {
app.status(e);
}
return;
}
let hit = hit_at(app, xf.to_doc(pos), xf.zoom);
// A scatter, art or pattern brush from the Brushes panel dropped where there is no art: a copy
// of its art, centered where it is dropped, to edit and Alt-drag back onto the brush.
@@ -148,3 +165,21 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons
app.status(e);
}
}
/// The selected, editable gradient mesh and its points that a solid color dropped at document
/// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh
/// (fills count even with Object Selection by Path Only, and clipping applies), and the points are
/// its point within 5 screen pixels, else the four points around its patch under `p`.
fn selected_mesh_drop(app: &VectorcraftApp, p: vectorcraft_geom::Point, zoom: f64) -> Option<(vectorcraft_doc::NodeId, Vec<usize>)> {
let tol = 5.0 / zoom.max(1e-9);
let leaf = hit_with(app, p, zoom, |doc, p, opt| {
vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, tol: opt.tol.max(tol), ..opt })
})?
.leaf;
let st = app.session.active()?;
if !st.selection.contains(leaf) || !st.doc.editable()(leaf) {
return None;
}
let Some(vectorcraft_doc::NodeKind::Mesh(m)) = st.doc.node(leaf).map(|n| &n.kind) else { return None };
Some((leaf, vectorcraft_tools::meshedit::color_points(m, p, tol)?))
}
+226 -39
View File
@@ -2821,10 +2821,20 @@ fn the_art_renders_within_the_largest_texture_side() {
assert_eq!(pixel_region(&xf, 1024), None, "more than the display's largest texture");
}
/// Run a test that compares two renders with the color settings that are active when it starts.
/// A test on another thread can change the process's active settings; this thread keeps its own.
fn keeping_color_settings(test: fn()) {
vectorcraft_color::cms::with_active(vectorcraft_color::cms::active(), test);
}
/// A placed document's bitmap made in the background renders the canvas again only where the
/// objects showing its file are: both copies of the file are in the part rendered again.
#[test]
fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() {
keeping_color_settings(a_ready_placed_bitmap);
}
fn a_ready_placed_bitmap() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width":400,"height":300})).unwrap();
app.ui.task_bar = false;
@@ -2859,9 +2869,8 @@ fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() {
};
let (_, delta) = frame_output(&mut app, &ctx);
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it");
let t = std::time::Instant::now();
while vectorcraft_render::placed_document::busy() && t.elapsed().as_secs() < 20 {
std::thread::sleep(std::time::Duration::from_millis(5));
while vectorcraft_render::placed_document::busy() {
std::thread::yield_now();
}
let (_, delta) = frame_output(&mut app, &ctx);
let (pos, size) = canvas(&app, delta).expect("the bitmap shows");
@@ -3137,6 +3146,10 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on()
/// transparency grid renders the art again, and Outline converts the art alone.
#[test]
fn translucent_art_over_the_paper_is_blended_before_the_display_profile() {
keeping_color_settings(translucent_art_over_the_paper);
}
fn translucent_art_over_the_paper() {
use crate::display_profile::{Found, Reading};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
@@ -3490,12 +3503,42 @@ fn the_first_view_reports_the_plug_in_effects_it_deferred() {
}
}
/// The render worker's side of a controlled worker: the test thread renders the jobs the canvas
/// queues, with [`crate::render_worker::render`] and the worker's own renderer and last frame.
struct WorkerSide {
jobs: std::sync::mpsc::Receiver<crate::render_worker::Job>,
done: std::sync::mpsc::Sender<crate::render_worker::Done>,
renderer: vectorcraft_render::Renderer,
kept: Option<crate::canvas::KeptFrame>,
}
impl WorkerSide {
/// A controlled worker for the canvas, and its side.
fn start() -> (crate::render_worker::Worker, Self) {
let (worker, jobs, done) = crate::render_worker::Worker::test_channel();
(worker, Self { jobs, done, renderer: vectorcraft_render::Renderer::new(), kept: None })
}
/// Render the newest job queued, as the worker thread does, and send its frame with a time of
/// 50 ms: the canvas then keeps sending the document's frames to the worker. False when no job
/// is queued.
fn render(&mut self) -> bool {
let Some(job) = self.jobs.try_iter().last() else { return false };
let done = crate::render_worker::render(&mut self.renderer, &mut self.kept, job);
self.done.send(crate::render_worker::Done { ms: 50.0, ..done }).is_ok()
}
}
/// A drag of an object with raster effects (#1257): the drag's frames render while
/// interacting and draw the object's drop shadow and filtered content from the rasters of the
/// frame before; the frame after the drag renders without `interacting`, on the render worker,
/// and draws what a fresh renderer draws.
/// and draws what a fresh renderer draws. The worker is a controlled one ([`WorkerSide`]).
#[test]
fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() {
keeping_color_settings(dragging_with_raster_effects);
}
fn dragging_with_raster_effects() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true; // render on this thread
@@ -3528,17 +3571,13 @@ fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() {
}
// The frame after the drag runs the effects again: on the worker, while the canvas shows
// the drag's last frame.
app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone());
let (worker, mut side) = WorkerSide::start();
app.canvas.worker = Some(worker);
app.session.pointer(&PointerEvent::new(PointerKind::Up, 181.9, 131.3), view).unwrap();
assert!(upload(&mut app).is_none(), "not rendered on this thread");
assert!(app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| !k.interacting), "sent to the worker");
let until = std::time::Instant::now() + std::time::Duration::from_secs(60);
let mut after = None;
while after.is_none() && std::time::Instant::now() < until {
std::thread::sleep(std::time::Duration::from_millis(5));
after = upload(&mut app);
}
let after = after.expect("the worker's frame arrives");
assert!(side.render(), "the worker renders the frame");
let after = upload(&mut app).expect("the worker's frame arrives");
assert!(app.canvas.key.as_ref().is_some_and(|k| !k.interacting));
assert!(!app.canvas.moved);
app.canvas.worker = None;
@@ -3554,6 +3593,10 @@ fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() {
/// without a drag, renders without `dragging` and draws the same.
#[test]
fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() {
keeping_color_settings(a_drag_at_a_lower_resolution);
}
fn a_drag_at_a_lower_resolution() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true; // render on this thread
@@ -3609,9 +3652,13 @@ fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() {
/// the blur reaches far past the raster budget, so the still frame keeps the backdrop's raster
/// cropped to the view, and each frame of a Selection tool drag draws it from there instead of
/// previewing it at the drag's lower resolution: on this thread, and on the worker, where the
/// frames of a heavy document render.
/// frames of a heavy document render. The worker is a controlled one ([`WorkerSide`]).
#[test]
fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() {
keeping_color_settings(a_drag_over_a_wide_blur);
}
fn a_drag_over_a_wide_blur() {
for on_worker in [false, true] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 595, "height": 842})).unwrap();
@@ -3623,9 +3670,9 @@ fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() {
app.run("select.set", json!({"ids": [square]})).unwrap();
app.select_tool("selection");
let ctx = egui::Context::default();
// One headless frame with `events`, then, on the worker, frames until the frame it renders
// for them is shown.
let run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
// One headless frame with `events`, then, with a worker, its frames rendered and shown
// until none is pending.
let run = |app: &mut VectorcraftApp, side: &mut Option<WorkerSide>, events: Vec<egui::Event>| {
let frame = |app: &mut VectorcraftApp, events| {
let raw =
egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 870.0))), events, ..Default::default() };
@@ -3633,39 +3680,40 @@ fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() {
out.textures_delta.clear();
};
frame(app, events);
let until = std::time::Instant::now() + std::time::Duration::from_secs(60);
while app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) && std::time::Instant::now() < until {
std::thread::sleep(std::time::Duration::from_millis(5));
for _ in 0..8 {
if !side.as_mut().is_some_and(WorkerSide::render) {
break;
}
frame(app, vec![]);
}
assert!(app.canvas.worker.as_ref().is_none_or(|w| w.pending.is_none()), "the worker's frame is shown");
};
let moved = |app: &VectorcraftApp| if on_worker { app.canvas.moved } else { app.canvas.renderer.stats.moved > 0 };
run(&mut app, vec![]);
let mut side = None;
run(&mut app, &mut side, vec![]);
if let Some(vm) = app.view_mut() {
(vm.zoom, vm.center) = (2.0, Point::new(290.0, 410.0));
}
if on_worker {
app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone());
let (worker, worker_side) = WorkerSide::start();
app.canvas.worker = Some(worker);
app.canvas.last_ms = 50.0;
side = Some(worker_side);
}
run(&mut app, vec![]);
run(&mut app, &mut side, vec![]);
assert_eq!(app.canvas.from_worker, on_worker);
assert!(!moved(&app), "a still frame, on the worker: {on_worker}");
let at = app.canvas_rect.unwrap().center();
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(&mut app, vec![egui::Event::PointerMoved(at)]);
run(&mut app, vec![button(at, true)]);
run(&mut app, &mut side, vec![egui::Event::PointerMoved(at)]);
run(&mut app, &mut side, vec![button(at, true)]);
for step in [1.0, 2.0, 3.0] {
run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]);
run(&mut app, &mut side, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]);
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}, on the worker: {on_worker}");
assert_eq!(app.canvas.from_worker, on_worker, "step {step}");
assert!(
!moved(&app),
"the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker} ({} ms)",
app.perf.render_ms
);
assert!(!moved(&app), "the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker}");
}
run(&mut app, vec![button(at + vec2(39.0, 21.0), false)]);
run(&mut app, &mut side, vec![button(at + vec2(39.0, 21.0), false)]);
let info = app.run("document.inspect", json!({})).unwrap();
let children = info["layers"][0]["children"].as_array().unwrap().clone();
let x0 = |id: &serde_json::Value| children.iter().find(|c| c["id"] == *id).unwrap()["bounds"]["x"].as_f64().unwrap();
@@ -3706,6 +3754,10 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
/// leaves the document as it was (#1257): here a drag back to where it started.
#[test]
fn a_drag_back_to_its_start_renders_again_after_it() {
keeping_color_settings(a_drag_back_to_its_start);
}
fn a_drag_back_to_its_start() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true; // render on this thread
@@ -3772,6 +3824,10 @@ fn canvas_render_jobs_use_renderer_limited_dimensions() {
/// controlled worker cannot finish early, even if egui repeats a layout pass.
#[test]
fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() {
keeping_color_settings(cached_frames_keep_their_scale);
}
fn cached_frames_keep_their_scale() {
for (old_rot, new_rot, old_ppp, new_ppp, pixel, resize_only) in [
// Isolate the original panel/window resize: zoom, pan, rotation and DPI stay fixed.
(0.0, 0.0, 1.0, 1.0, false, true),
@@ -3867,9 +3923,13 @@ fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() {
/// a heavy document), the canvas draws the last frame turned until that frame arrives: each
/// corner goes where the new view puts the document point that the corner showed. The new frame
/// is then drawn unturned. In Pixel Preview the last frame's pixels stay over the document rect
/// they cover.
/// they cover. The worker is a controlled one ([`WorkerSide`]).
#[test]
fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() {
keeping_color_settings(a_turned_view);
}
fn a_turned_view() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap();
@@ -3890,7 +3950,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() {
})
};
// With a worker and a last frame that took 50 ms, the next frame renders on the worker.
app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone());
let (worker, mut side) = WorkerSide::start();
app.canvas.worker = Some(worker);
app.canvas.last_ms = 50.0;
app.run("view.rotateReset", json!({})).unwrap();
let mesh = art(&mut app).expect("the last frame, turned");
@@ -3908,11 +3969,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() {
let [a, b, _, d] = [0, 1, 2, 3].map(|i| mesh.vertices[i].pos);
assert!((a + (b - a) * uv.x + (d - a) * uv.y - new.to_screen(p)).length() < 0.01, "the rectangle's corner");
// The worker's frame at 0° then covers the canvas unturned.
let until = std::time::Instant::now() + std::time::Duration::from_secs(60);
while app.canvas.key.as_ref().is_some_and(|k| k.rot != 0.0) && std::time::Instant::now() < until {
std::thread::sleep(std::time::Duration::from_millis(5));
shapes(&mut app, &ctx);
}
assert!(side.render(), "the worker renders the frame at 0°");
shapes(&mut app, &ctx);
assert!(app.canvas.key.as_ref().is_some_and(|k| k.rot == 0.0), "the worker's frame arrives");
let b = art(&mut app).expect("the worker's frame").calc_bounds();
assert!((b.min - rect.min).length() < 0.01 && (b.max - rect.max).length() < 0.01, "{b:?} over {rect:?}");
@@ -3922,7 +3980,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() {
app.view_mut().unwrap().zoom = 8.0;
shapes(&mut app, &ctx);
let [x0, y0, ..] = app.canvas.key.as_ref().and_then(|k| k.pixel).expect("the pixels rendered");
app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone());
let (worker, _side) = WorkerSide::start();
app.canvas.worker = Some(worker);
app.canvas.last_ms = 50.0;
app.view_mut().unwrap().rotation = 30.0;
let mesh = art(&mut app).expect("the last frame's pixels");
@@ -3937,6 +3996,10 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() {
/// fill is dropped.
#[test]
fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() {
keeping_color_settings(a_pan_fills_the_area);
}
fn a_pan_fills_the_area() {
let ctx = egui::Context::default();
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
@@ -4062,6 +4125,10 @@ fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() {
/// before.
#[test]
fn without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still() {
keeping_color_settings(without_a_worker_a_heavy_canvas);
}
fn without_a_worker_a_heavy_canvas() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap();
@@ -4172,6 +4239,10 @@ fn the_canvas_waits_only_while_the_view_of_a_slow_frame_changes() {
/// worker's pixel copy ask for that.
#[test]
fn a_bitmap_made_for_another_documents_file_leaves_a_pan_waiting() {
keeping_color_settings(a_bitmap_for_another_documents_file);
}
fn a_bitmap_for_another_documents_file() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap();
@@ -9014,6 +9085,86 @@ fn swatches_and_proxy_paints_dropped_on_art_fill_the_object_hit() {
assert!(matches!(fill(&app), Paint::Gradient(g) if g.geom.is_none()));
}
#[test]
fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() {
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{GradientMesh, NodeId, NodeKind};
use widgets::PanelDrag;
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
let id = NodeId(id);
app.session.execute("object.mesh.create", &json!({"ids": [id.0], "rows": 2, "columns": 2})).unwrap();
app.session.execute("select.none", &json!({})).unwrap();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
let drop = |app: &mut VectorcraftApp, d: PanelDrag, at: Point| {
let at = xf.to_screen(at);
egui::DragAndDrop::set_payload(&ctx, d);
let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };
frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]);
};
let mesh = |app: &VectorcraftApp| -> GradientMesh {
match &app.session.active().unwrap().doc.node(id).unwrap().kind {
NodeKind::Mesh(m) => m.clone(),
_ => panic!("not a gradient mesh"),
}
};
let colors = |app: &VectorcraftApp| mesh(app).points.iter().map(|q| q.color).collect::<Vec<_>>();
let undo_len = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let before = colors(&app);
let m = mesh(&app);
let (center, patch) = (m.points[4].p, Point::new((m.points[0].p.x + m.points[4].p.x) / 2.0, (m.points[0].p.y + m.points[4].p.y) / 2.0));
let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0));
app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap();
// On a mesh point: that point alone.
drop(&mut app, PanelDrag::paint(Paint::solid(red)), center);
let after = colors(&app);
assert_eq!(after[4], red);
assert_eq!((0..9).filter(|i| after[*i] != before[*i]).count(), 1, "only the point under the pointer");
// Inside a patch: its four points.
drop(&mut app, PanelDrag::paint(Paint::solid(blue)), patch);
let after = colors(&app);
assert_eq!([0, 1, 3, 4].map(|i| after[i]), [blue; 4]);
assert_eq!([2, 5, 6, 7, 8].map(|i| after[i]), [2, 5, 6, 7, 8].map(|i| before[i]));
assert!(app.session.active().unwrap().selection.contains(id), "the selection stays");
// The same color again changes nothing and records no undo step.
let n = undo_len(&app);
drop(&mut app, PanelDrag::paint(Paint::solid(blue)), patch);
assert_eq!(undo_len(&app), n);
// With Object Selection by Path Only, a drop inside a patch still reaches its points, and a
// drop 4 screen pixels outside a corner point still reaches that point.
app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap();
let green = Color::rgb(0.0, 1.0, 0.0);
let far = Point::new((m.points[4].p.x + m.points[8].p.x) / 2.0, (m.points[4].p.y + m.points[8].p.y) / 2.0);
// Art below the patch, with its outline within the selection tolerance, is not taken for it.
let h = 1.0 / xf.zoom;
let below = app.session.execute("shape.rectangle", &json!({"x": far.x - h, "y": far.y - h, "width": 2.0 * h, "height": 2.0 * h})).unwrap()["id"]
.as_u64()
.unwrap();
app.session.execute("object.arrange.sendToBack", &json!({"ids": [below]})).unwrap();
app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap();
drop(&mut app, PanelDrag::paint(Paint::solid(green)), far);
assert_eq!([4, 5, 7, 8].map(|i| colors(&app)[i]), [green; 4]);
assert_ne!(app.session.active().unwrap().doc.node(NodeId(below)).unwrap().appearance.fill_paint(), Paint::solid(green));
let off = 4.0 / xf.zoom;
drop(&mut app, PanelDrag::paint(Paint::solid(red)), Point::new(m.points[0].p.x - off, m.points[0].p.y));
assert_eq!(colors(&app)[0], red, "the corner point within reach");
assert_eq!(colors(&app)[1], blue);
// An unselected object on top of the mesh takes the drop itself.
app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap();
let c = m.points[4].p;
let cover = app.session.execute("shape.rectangle", &json!({"x": c.x - 10.0, "y": c.y - 10.0, "width": 20, "height": 20})).unwrap()["id"]
.as_u64()
.unwrap();
app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let before = colors(&app);
drop(&mut app, PanelDrag::paint(Paint::solid(green)), c);
assert_eq!(colors(&app), before, "the mesh under it keeps its colors");
assert_eq!(app.session.active().unwrap().doc.node(NodeId(cover)).unwrap().appearance.fill_paint(), Paint::solid(green));
}
#[test]
fn dropping_the_appearance_thumbnail_on_art_copies_the_appearance() {
use vectorcraft_doc::NodeId;
@@ -13076,6 +13227,10 @@ fn pan_doc() -> (std::sync::Arc<vectorcraft_doc::Document>, CacheKey) {
/// put in that frame moves with the pan, and the frame matches a whole render where the mark is not.
#[test]
fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() {
keeping_color_settings(a_whole_pixel_pan);
}
fn a_whole_pixel_pan() {
let (doc, key) = pan_doc();
for pan in [(10.0, 0.0), (-10.0, 0.0), (0.0, 7.0), (0.0, -7.0), (-13.0, 5.0)] {
let mut r = vectorcraft_render::Renderer::new();
@@ -13103,6 +13258,10 @@ fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() {
/// plug-in registry, and the plug-in is removed after.
#[test]
fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() {
keeping_color_settings(a_plug_in_change);
}
fn a_plug_in_change() {
use vectorcraft_plugins::wat as tpl;
let id = "test.canvas.redraw";
let module = vectorcraft_format::base64_encode(&wat::parse_str(tpl::module(&tpl::manifest(id, "effect", "{}"), tpl::ECHO, "", 1)).unwrap());
@@ -13145,6 +13304,10 @@ fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() {
/// compares such frames with a fresh render pixel by pixel.
#[test]
fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() {
keeping_color_settings(a_frame_renders_whole);
}
fn a_frame_renders_whole() {
let (doc, key) = pan_doc();
let other_opts = |f: &dyn Fn(&mut vectorcraft_render::RenderOptions)| {
let mut job = pan_job(&doc, &key, (10.0, 0.0));
@@ -13222,6 +13385,10 @@ fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() {
/// not kept. A frame that may not copy can still be kept.
#[test]
fn the_render_worker_keeps_one_frame_up_to_its_limit() {
keeping_color_settings(the_render_worker_keeps_one_frame);
}
fn the_render_worker_keeps_one_frame() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 256, "height": 128})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 16, "y": 16, "width": 64, "height": 64})).unwrap()["id"].clone();
@@ -13268,6 +13435,10 @@ fn the_render_worker_keeps_one_frame_up_to_its_limit() {
/// worker renders whole matches a fresh render, and each copied frame is within one level of it.
#[test]
fn worker_frames_match_a_fresh_render_through_a_session() {
keeping_color_settings(worker_frames_match_a_fresh_render);
}
fn worker_frames_match_a_fresh_render() {
let (doc, key) = pan_doc();
let mut edited = (*doc).clone();
edited.layers.reverse();
@@ -13353,6 +13524,10 @@ fn worker_frames_match_a_fresh_render_through_a_session() {
/// not keep such a frame for the pan to copy from.
#[test]
fn a_pan_over_art_the_frame_size_decides_renders_whole() {
keeping_color_settings(a_pan_over_art);
}
fn a_pan_over_art() {
let (_, key) = pan_doc();
let effect = |effect: &str, params: serde_json::Value| {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
@@ -13408,6 +13583,10 @@ fn a_pan_over_art_the_frame_size_decides_renders_whole() {
/// before and only once.
#[test]
fn a_frame_with_copied_pixels_renders_whole_once_the_view_stops() {
keeping_color_settings(a_frame_with_copied_pixels);
}
fn a_frame_with_copied_pixels() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true;
@@ -13454,6 +13633,10 @@ fn a_frame_with_copied_pixels_renders_whole_once_the_view_stops() {
/// first step of the next pan copies from it. The jobs are the ones the canvas asks for.
#[test]
fn a_pan_after_the_settling_frame_copies() {
keeping_color_settings(a_pan_after_the_settling_frame);
}
fn a_pan_after_the_settling_frame() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true;
@@ -13552,6 +13735,10 @@ fn the_render_worker_thread_copies_a_pan() {
/// meanwhile, does not queue the frame again while it renders, and shows it once it lands.
#[test]
fn a_documents_first_frame_renders_on_the_worker() {
keeping_color_settings(a_documents_first_frame);
}
fn a_documents_first_frame() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true;
+45 -13
View File
@@ -142,17 +142,52 @@ fn every_tool_is_listed_once_under_a_heading() {
assert!(!heads.contains(&"More"), "every tool has a named heading: {heads:?}");
}
/// The Enclosing Lasso Tool is in the Lasso tool's flyout in both toolbars, right after the Lasso,
/// once in the All Tools drawer (under Select) and in Keyboard Shortcuts' list, with no shortcut;
/// Reset Toolbar keeps it there.
#[test]
fn enclosing_lasso_is_an_optional_addon_tool() {
fn enclosing_lasso_is_in_the_lasso_flyout() {
let mut app = app();
let id = vectorcraft_tools::addons::enclosing_lasso::ID;
assert_eq!(heading(id), "Enclosing Lasso");
assert!(slot_of(&app, id).is_none());
app.run("toolbar.addTool", json!({"tool": id})).unwrap();
assert!(slot_of(&app, id).is_some());
for advanced in [false, true] {
if advanced {
app.run("window.toolbarAdvanced", json!({})).unwrap();
}
let s = slots(&app);
let slot = slot_of(&app, "lasso").map(|i| s[i].clone()).expect("a Lasso slot");
let lasso = slot.iter().position(|t| *t == "lasso").expect("the Lasso");
assert_eq!(slot.get(lasso + 1), Some(&id), "advanced: {advanced}");
assert_eq!(s.iter().filter(|ids| ids.contains(&id)).count(), 1, "advanced: {advanced}");
}
assert_eq!(heading(id), "Select");
assert_eq!(sections().iter().flat_map(|(_, tools)| tools.iter()).filter(|t| t.id == id).count(), 1, "listed once in the drawer");
assert_eq!(vectorcraft_tools::catalog::all_tools().filter(|t| t.id == id).count(), 1, "listed once for Keyboard Shortcuts");
assert_eq!(vectorcraft_tools::tool_info(id).map(|t| (t.label, t.shortcut)), Some(("Enclosing Lasso Tool", None)));
app.run("tool.select", json!({"tool": id})).unwrap();
assert_eq!(app.session.tool_id(), id);
let shown = slot_of(&app, id).map(|i| crate::toolbar::shown_tool(&app, &slots(&app)[i]));
assert_eq!(shown, Some(id), "the slot's button shows the tool once chosen");
app.run("toolbar.removeTool", json!({"tool": id})).unwrap();
assert!(slot_of(&app, id).is_none(), "it can be taken out");
app.run("toolbar.reset", json!({})).unwrap();
let after_reset = slot_of(&app, "lasso").map(|i| slots(&app)[i].contains(&id));
assert_eq!(after_reset, Some(true), "Reset Toolbar puts it back");
}
/// A toolbar edited and saved before the Enclosing Lasso Tool joined the Lasso group keeps its
/// saved layout: the tool stays in the drawer until Reset Toolbar or a drag adds it.
#[test]
fn a_saved_toolbar_without_enclosing_lasso_keeps_its_layout() {
let mut app = app();
let id = vectorcraft_tools::addons::enclosing_lasso::ID;
let saved = ToolbarCategory { name: Some("Select".into()), slots: vec![["lasso", "magicWand"].iter().map(|t| t.to_string()).collect()] };
app.ui.toolbar_edits = ToolbarEdits { basic: Some(vec![saved]), advanced: None };
app.ui = std::mem::take(&mut app.ui).sanitized();
assert_eq!(slots(&app), [["lasso", "magicWand"]]);
assert!(slot_of(&app, id).is_none());
app.run("toolbar.reset", json!({})).unwrap();
let slot = slot_of(&app, "lasso").map(|i| slots(&app)[i].clone());
assert!(slot.is_some_and(|s| s.contains(&id)), "Reset Toolbar adds it");
}
#[test]
@@ -166,7 +201,7 @@ fn the_commands_add_move_remove_and_reset_tools() {
// Before the first slot, moved out of its group.
app.run("toolbar.addTool", json!({"tool": "magicWand", "slot": 0})).unwrap();
assert_eq!(&slots(&app)[..3], [&["magicWand"][..], &["selection"], &["directSelection", "groupSelection"]]);
assert_eq!(slots(&app)[3], ["lasso"]);
assert_eq!(slots(&app)[3], ["lasso", "enclosingLasso"]);
// After a slot, and into a group (last), moved out of the Rectangle group.
app.run("toolbar.addTool", json!({"tool": "slice", "slot": 1, "place": "after"})).unwrap();
assert_eq!(slots(&app)[2], ["slice"]);
@@ -359,7 +394,7 @@ fn tools_drag_between_the_drawer_and_the_toolbar() {
// Within the toolbar: Selection onto the divider over the Lasso.
let tools = crate::toolbar::tests::widget_rects(&ctx, BUTTON);
drag(&mut app, &ctx, 5.0, tools[0].center(), tools[2].center_top() + vec2(0.0, 3.0));
assert_eq!(&slots(&app)[..3], [&["directSelection", "groupSelection"][..], &["selection"], &["lasso", "magicWand"]]);
assert_eq!(&slots(&app)[..3], [&["directSelection", "groupSelection"][..], &["selection"], &["lasso", "enclosingLasso", "magicWand"]]);
// The drawer closed, the toolbar is locked: the same drag moves nothing.
app.run("window.editToolbar", json!({"open": false})).unwrap();
frame(&mut app, &ctx, 6.0, vec![]);
@@ -677,12 +712,11 @@ fn a_saved_toolbar_without_trim_at_crossings_keeps_its_layout() {
}
/// The add-ons' tools are in neither toolbar as they ship (the Trim at Crossings Tool, in the
/// Scissors tool's group, aside): the drawer lists them under their add-on's heading, and they can
/// be added from there.
/// Scissors tool's group, and the Enclosing Lasso Tool, in the Lasso tool's group, aside): the
/// drawer lists them under their add-on's heading, and they can be added from there.
#[test]
fn addon_tools_are_in_the_drawer_not_the_toolbars() {
let mut app = app();
let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID;
let contour = vectorcraft_tools::addons::contour::ID;
let box3d = vectorcraft_tools::addons::box3d::ID;
let polygonal = vectorcraft_tools::addons::polygonal_lasso::ID;
@@ -698,7 +732,6 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
"slideAnchor",
"sharedEdge",
"smartPen",
enclosing,
contour,
box3d,
polygonal
@@ -715,11 +748,10 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
};
assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec())));
assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"])));
assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing])));
assert_eq!(listed(contour), Some(("Contour", vec![contour])));
assert_eq!(listed(box3d), Some(("3D Box", vec![box3d])));
assert_eq!(listed(polygonal), Some(("Polygonal Lasso", vec![polygonal])));
for tool in ["extendPath", "smartPen", enclosing, contour, box3d, polygonal] {
for tool in ["extendPath", "smartPen", contour, box3d, polygonal] {
app.run("toolbar.addTool", json!({"tool": tool})).unwrap();
assert!(slot_of(&app, tool).is_some(), "{tool}");
}
+22 -2
View File
@@ -230,6 +230,17 @@ fn collect(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option<Vec<NodeId
}
}
/// Does the export of 3D asset `asset` draw a texture for the graphics mapped onto its faces
/// ([`vectorcraft_engine::cmd::fileio::draws_textures`])? Only objects whose 3D effects map graphics
/// are built to find out.
fn writes_textures(doc: &vectorcraft_doc::Document, asset: &ExportAsset) -> bool {
let maps = |e: &vectorcraft_doc::Effect| e.visible && !vectorcraft_render::effects::mapped_graphics(&e.params).is_empty();
let nodes: Vec<&Node> = asset.nodes.iter().filter_map(|id| doc.node(*id)).collect();
nodes.iter().any(|n| n.appearance.effects.iter().chain(n.appearance.items.iter().flat_map(|i| i.effects())).any(maps))
&& vectorcraft_render::effects::three_d_meshes_of_in(Some(doc), nodes.iter().copied())
.is_ok_and(|parts| vectorcraft_engine::cmd::fileio::draws_textures(doc, &parts))
}
/// Export assets `ids` (`files_each`: the files one asset makes) into a picked folder (without a
/// folder picker: the last folder Export for Screens used, else the Desktop); the web downloads
/// them, several as one zip.
@@ -240,11 +251,20 @@ fn export(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) {
fn export_now(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) {
// 3D assets are written as mesh files (`assets.export3D`), the others as pictures.
let web = io::is_web(app);
let Some(st) = app.session.active() else { return };
let format = |id: &u64| st.doc.asset(*id).and_then(|a| a.format_3d.clone());
let (three_d, ids): (Vec<u64>, Vec<u64>) = ids.into_iter().partition(|id| format(id).is_some());
// An OBJ is two files.
let mesh_files: usize = three_d.iter().map(|id| if format(id).as_deref() == Some("obj") { 2 } else { 1 }).sum();
// An OBJ is two files, and an OBJ or a USDA whose graphics draw a texture writes it beside
// them. Only the web, which zips several files, needs the count.
let mesh_files: usize = three_d
.iter()
.map(|id| {
let format = format(id);
let textures = web && matches!(format.as_deref(), Some("obj" | "usda")) && st.doc.asset(*id).is_some_and(|a| writes_textures(&st.doc, a));
usize::from(format.as_deref() == Some("obj")) + 1 + usize::from(textures)
})
.sum();
// Create Sub-folders as the panel menu checks it: on by default, and remembered folders (per
// row, format or item) are used as Export for Screens uses them (a remembered `subfolders`
// false beside them would alone put every file in the folder itself).
+10 -5
View File
@@ -52,6 +52,15 @@ pub struct Done {
pub reused: bool,
}
/// Render `job` as the worker thread does: inside the job's automation roots and deferred
/// effects, with the worker's renderer `r` and its last frame `kept`.
pub(crate) fn render(r: &mut Renderer, kept: &mut Option<crate::canvas::KeptFrame>, job: Job) -> Done {
let t0 = crate::now_ms();
let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(r, kept, &job)));
let ms = crate::now_ms() - t0;
Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused }
}
pub struct Worker {
tx: Sender<Job>,
rx: Receiver<Done>,
@@ -76,11 +85,7 @@ impl Worker {
while let Ok(newer) = jobs.try_recv() {
job = newer;
}
let t0 = crate::now_ms();
let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(&mut r, &mut kept, &job)));
let ms = crate::now_ms() - t0;
let done = Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused };
if done_tx.send(done).is_err() {
if done_tx.send(render(&mut r, &mut kept, job)).is_err() {
break;
}
ctx.request_repaint();
+1 -1
View File
@@ -33,7 +33,7 @@ const STRIP_BUTTON: egui::Vec2 = vec2(32.0, PITCH);
/// The Basic toolbar: (category, slots); each slot is a flyout group (first = default).
pub const BASIC: &[(&str, &[&[&str]])] = &[
("Select", &[&["selection"], &["directSelection", "groupSelection"], &["lasso", "magicWand"]]),
("Select", &[&["selection"], &["directSelection", "groupSelection"], &["lasso", "enclosingLasso", "magicWand"]]),
(
"Shapes",
&[
+1 -1
View File
@@ -102,7 +102,7 @@ fn the_tool_buttons_are_centred_in_the_panel() {
fn saved_flyout_choices_must_still_belong_to_the_slot() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
for (saved, shown) in [(vectorcraft_tools::addons::enclosing_lasso::ID, "lasso"), ("magicWand", "magicWand")] {
for (saved, shown) in [(vectorcraft_tools::addons::polygonal_lasso::ID, "lasso"), ("magicWand", "magicWand")] {
app.ui.slot_tool.insert("lasso".into(), saved.into());
let tree = tree(|ui| show(&mut app, ui));
assert_eq!(role_and_state(&tree, &tip(tool_info(shown).unwrap())), (Role::Button, Some(Toggled::False)));
+1 -1
View File
@@ -183,7 +183,7 @@ VectorCraft choices; an original approximation, never compared with another appl
| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, or ray tracing |
| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none |
| Turntable (30.0 beta) | none |
| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) |
| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) |
The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces;
the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering,
+10 -1
View File
@@ -323,7 +323,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's
| 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 |
| 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) | 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 | no | no | no open spec; DXF instead |
| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) |
| 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` |
| PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) |
| PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | |
| PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) |
@@ -345,6 +345,15 @@ Gradient meshes in the editing data keep each point's own color where a patch's
| Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) |
| Clipboard: PDF, SVG, PNG, EMF, text | yes | yes | yes | copied files paste as art; cells copied from a spreadsheet (tab-separated text) paste as a table of point type over gridlines, at most 1000 rows, 256 columns and 20,000 cells (#5296) |
Opaque CMYK PSD/PSB merged images preserve their 8-bit or 16-bit ink samples, CMYK ICC profile, resolution,
and clipping path through placement, relinking, updating, and embedding (#8316). VectorCraft stores these images
as CMYK TIFFs up to its native limit of 67,108,864 pixels and within its allocation allowance. Other CMYK composites
use the RGB import path, subject to its allocation limit; importing individual layers keeps its existing behavior.
Synthetic regressions in
`tests_psdread.rs` cover native samples, compression, metadata, and linked-image operations. The
[public PSD specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/index.html) defines
the CMYK planes and profile and resolution resources.
## PDF form gradients
PDF export's linear and radial gradients stay aligned inside transparency groups, opacity masks,
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more