Merge main into fix/smooth-fidelity-screen-pixels

This commit is contained in:
dotCooCoo committed 2026-11-13 08:44:25 -08:00
commit d92e63257b
76 files changed
+3926 -197

No files matched your search

+1 -1
View File
@@ -27,7 +27,7 @@ pub fn is_revolve(id: &str) -> bool {
/// Most bytes the copies of the object's paint in the faces may take together. Each face and the
/// seam stroke around it gets a copy of the paint, so a gradient of many stops times tens of
/// thousands of faces took gigabytes; past this the source path is drawn.
const MAX_PAINT_COPIES: usize = 256 << 20;
pub(crate) const MAX_PAINT_COPIES: usize = 256 << 20;
/// The most face and box tests a group's transparent members' faces take together to rejoin their
/// members' last runs; past them each starts a run of its own.
+583 -54
View File
@@ -5,8 +5,9 @@ use std::sync::Arc;
use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View};
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
use vectorcraft_pathops::BoolOp;
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, PlanarFace, View};
#[cfg(test)]
use vectorcraft_doc::color::Color;
@@ -678,7 +679,8 @@ fn built_solids<'a>(
/// What a face of one of the solids [`art_for`] draws in one order was built from: the facet's
/// depth, whether it is a side face and whether it is turned away from the viewer, the bounds of
/// its polygon, the index of its shape, and whether its solid is that shape's fill or one of its
/// strokes that covers the fill's whole edge.
/// strokes that covers the fill's whole edge. A face that [`convex_face`] takes also keeps its
/// polygon and plane, for [`local_order`]; every other face has an empty `outline` and no `plane`.
struct Placed {
depth: f64,
side: bool,
@@ -686,6 +688,8 @@ struct Placed {
bounds: Rect,
member: usize,
paints: Paints,
outline: Vec<Point>,
plane: Option<DepthPlane>,
}
/// The part of its shape a face's solid is built from ([`Placed`]).
@@ -694,13 +698,22 @@ enum Paints {
Fill,
/// A stroke whose solid holds the fill's whole edge and hides it: one with a width, without
/// dashes, a width profile or a brush, painted with a solid color or a gradient without
/// transparent stops, on a shape whose subpaths are all closed.
/// transparent stops, on a shape whose subpaths are all closed, extruded (an inflated fill can
/// rise in front of its stroke).
Stroke,
Other,
}
/// Can a stroke's solid on a shape with outline `path` hold the fill's edge ([`Paints::Stroke`])
/// under the effect `effect`? Only when the subpaths are all closed and the effect extrudes: an
/// inflated fill can rise in front of its stroke.
fn holds_edge(effect: &str, path: &PathData) -> bool {
effect != INFLATE && path.subpaths.iter().all(|p| p.closed)
}
impl Paints {
/// What `item` of a shape is, the shape's subpaths all closed when `closed`.
/// What `item` of a shape is, its stroke's solid able to hold the fill's edge when `closed`
/// ([`holds_edge`]).
fn of(item: &AppearanceItem, closed: bool) -> Self {
match item {
AppearanceItem::Fill(_) => Paints::Fill,
@@ -729,10 +742,446 @@ impl Placed {
fn of(f: &Facet, member: usize, paints: Paints) -> Self {
let mut points = f.contours.iter().flatten();
let bounds = points.next().map_or(Rect::ZERO, |p| points.fold(Rect::from_points(*p, *p), |r, q| r.union_pt(*q)));
Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints }
let local = convex_face(f).is_some();
let outline = f.contours.first().filter(|_| local).cloned().unwrap_or_default();
let plane = f.plane.filter(|_| local);
Placed { depth: f.depth, side: f.side, away: f.away, bounds, member, paints, outline, plane }
}
}
/// The most pairs of faces [`local_order`] compares, and the most [`cut_stroke_faces`] compares;
/// the pairs they have not reached by then keep the order of their depths.
const MAX_LOCAL_CHECKS: usize = 4_000_000;
/// The polygon of `f` and the sign of its turns, when `f` is a face turned toward the viewer other
/// than a planar end, with a plane and one convex contour: a face [`local_order`] and
/// [`cut_stroke_faces`] work on.
fn convex_face(f: &Facet) -> Option<(&[Point], f64)> {
if f.away || f.end.is_some() || f.plane.is_none() || f.contours.len() != 1 {
return None;
}
let c = f.contours.first()?;
Some((c, convex(c)?))
}
/// The bounds of polygon `p` (`Rect::ZERO` when it has no points).
fn polygon_bounds(p: &[Point]) -> Rect {
let mut points = p.iter();
points.next().map_or(Rect::ZERO, |q| points.fold(Rect::from_points(*q, *q), |r, q| r.union_pt(*q)))
}
/// Do rectangles `a` and `b` overlap (more than along an edge)?
fn rects_overlap(a: Rect, b: Rect) -> bool {
a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1
}
/// How many faces [`cut_stroke_faces`] may add to solids painted by `items` that hold `faces` faces
/// and whose paint copies take `paint_bytes` so far: as many as keep the faces within
/// [`MAX_OBJECT_FACES`] and the copies within the allowance, each added face counted as six copies
/// of the costliest stroke's paint.
fn cut_room<'a>(items: impl Iterator<Item = &'a AppearanceItem>, faces: usize, paint_bytes: usize) -> usize {
let per_face = items
.filter(|item| matches!(item, AppearanceItem::Stroke(_)))
.map(|item| {
let mut copies = 0usize;
crate::revolve::paint_copies_add(&mut copies, 6, paint_ref(item));
copies
})
.max()
.unwrap_or(0)
.max(1);
let affordable = crate::revolve::MAX_PAINT_COPIES.saturating_sub(paint_bytes) / per_face;
MAX_OBJECT_FACES.saturating_sub(faces).min(affordable)
}
/// In `solids`, each solid's part ([`Paints`]), its shape's index and its faces, cut each face of a
/// stroke that does not cover the fill's edge ([`Paints::Other`]) that passes through the plane of a
/// face of the same shape's fill, or of a face of another of the shape's strokes, where the two
/// overlap on the drawing ([`cut_through`]). Of two such strokes, the later one's faces are cut
/// against the earlier one's; a covering stroke's faces ([`Paints::Stroke`]) are never cut, and an
/// other stroke's faces are cut against them. At most `room` pieces are added, the object's solids
/// together.
fn cut_stroke_faces(solids: &mut [(Paints, usize, &mut Vec<Facet>)], mut room: usize) {
let mut checks = 0usize;
for k in 0..solids.len() {
let Some((Paints::Other, shape)) = solids.get(k).map(|(p, s, _)| (*p, *s)) else { continue };
let walls: Vec<usize> = (0..solids.len())
.filter(|&j| {
solids.get(j).is_some_and(|(p, s, _)| {
*s == shape
&& match p {
Paints::Fill | Paints::Stroke => true,
Paints::Other => j < k,
}
})
})
.collect();
for j in walls {
let (wall, stroke) = if j < k {
let (before, from) = solids.split_at_mut(k);
(&**before[j].2, &mut *from[0].2)
} else {
let (before, from) = solids.split_at_mut(j);
(&**from[0].2, &mut *before[k].2)
};
cut_through(wall, stroke, &mut room, &mut checks);
}
}
}
/// Cut each face of `stroke` that passes through the plane of a face of `solid` (the fill's or
/// another stroke's) where their polygons overlap on the drawing, along the line where their depths
/// meet, so that each piece is wholly in front of or behind that face there ([`local_order`] can
/// then order them). A dash's end, which crosses the edge of the fill it is drawn on, is cut into its
/// part outside the fill, in front of the fill's wall, and its part inside, behind it. A piece keeps
/// the part of the face's curved outline on its side of the cut. The first piece of a face takes its
/// place, the others go at the end. Each cut adds a face out of `room`, and each pair compared counts
/// in `checks` ([`MAX_LOCAL_CHECKS`]); cutting stops when either runs out.
fn cut_through(solid: &[Facet], stroke: &mut Vec<Facet>, room: &mut usize, checks: &mut usize) {
// The faces from left to right: a face is compared with those that start left of its end.
let mut walls: Vec<(&Facet, &[Point], f64, Rect)> =
solid.iter().filter_map(|f| convex_face(f).map(|(c, turn)| (f, c, turn, polygon_bounds(c)))).collect();
if walls.is_empty() {
return;
}
walls.sort_by(|a, b| a.3.x0.total_cmp(&b.3.x0));
let mut k = 0;
while k < stroke.len() {
let mut extent = stroke.get(k).and_then(convex_face).map(|(c, _)| polygon_bounds(c));
for &(wall, outline, turn, bounds) in &walls {
let Some(at) = extent.filter(|e| bounds.x0 < e.x1) else { break };
if *checks >= MAX_LOCAL_CHECKS || *room == 0 {
return;
}
*checks += 1;
if !rects_overlap(at, bounds) {
continue;
}
let Some(s) = stroke.get(k) else { break };
let Some((c, _)) = convex_face(s) else { break };
if let Some((near, far)) = cut(s, c, wall, outline, turn) {
*room -= 1;
extent = convex_face(&near).map(|(c, _)| polygon_bounds(c));
stroke[k] = near;
stroke.push(far);
}
}
k += 1;
}
}
/// Face `s` (polygon `c`) cut where its depth meets that of face `wall` (convex polygon `outline`,
/// turning with sign `turn`): its piece nearer the viewer than the wall's plane and its piece
/// farther. `None` when the two do not overlap on the drawing or `s` is on one side of the wall's
/// plane wherever they do.
fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Option<(Facet, Facet)> {
let ahead = |p: Point| Some(s.depth_at(p)? - wall.depth_at(p)?);
let overlap = clip_convex(c, outline, turn);
centroid(&overlap)?;
let tolerance = 1e-6;
let (mut nearer, mut farther) = (false, false);
for p in &overlap {
let d = ahead(*p)?;
nearer |= d > tolerance;
farther |= d < -tolerance;
}
if !(nearer && farther) {
return None;
}
let (a, b) = (s.plane?, wall.plane?);
let values: Vec<f64> = match (a.eye, b.eye) {
(Some(e), Some(f)) if e == f && a.center == b.center => {
// With perspective the depths themselves are not linear on the drawing, but where they
// meet is a line: (dA - aA e)(nzB - aB) = (dB - aB e)(nzA - aA), with aX = (nX · p) / e,
// whose difference is linear. Its sign is that of the depths' difference over the
// product of the two denominators, taken at the middle of the face.
let at = |p: Point| {
let (x, y) = (p.x - a.center.x, p.y - a.center.y);
let (aa, ab) = ((a.normal[0] * x + a.normal[1] * y) / e, (b.normal[0] * x + b.normal[1] * y) / e);
let (da, db) = (a.normal[2] - aa, b.normal[2] - ab);
((a.offset - aa * e) * db - (b.offset - ab * e) * da, da * db)
};
let sign = at(centroid(c)?).1.signum();
c.iter().map(|p| at(*p).0 * sign).collect()
}
_ => c.iter().map(|p| ahead(*p)).collect::<Option<_>>()?,
};
let piece = |sign: f64| {
let points = half(c, &values, sign);
let mid = centroid(&points)?;
let mut f = s.clone();
f.depth = s.depth_at(mid).unwrap_or(s.depth);
f.contours = vec![points];
f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign));
Some(f)
};
Some((piece(1.0)?, piece(-1.0)?))
}
/// Curved outline `outline` of a face with polygon `c`, cut along the line where `values` (one per
/// point of `c`, varying linearly along each edge) is 0, keeping the side where `sign` times them is
/// at least 0. `None` when the line does not cross `c` at two points or nothing is left.
fn clip_to_side(outline: &PathData, c: &[Point], values: &[f64], sign: f64) -> Option<PathData> {
let mut crossings = vec![];
for (j, (&a, &va)) in c.iter().zip(values).enumerate() {
let k = (j + 1) % c.len();
let (Some(&b), Some(&vb)) = (c.get(k), values.get(k)) else { continue };
if (va >= 0.0) != (vb >= 0.0) {
crossings.push(a.lerp(b, va / (va - vb)));
}
}
let &[q0, q1] = crossings.as_slice() else { return None };
let along = q1 - q0;
let length = along.hypot();
if length.is_nan() || length <= 1e-9 {
return None;
}
let along = along / length;
let (inside, _) = c.iter().zip(values).find(|(_, v)| **v * sign > 0.0)?;
let mut across = Vec2::new(-along.y, along.x);
if (*inside - q0).dot(across) < 0.0 {
across = -across;
}
let bounds = outline.bounds()?.union(polygon_bounds(c));
let reach = 2.0 * (bounds.width() + bounds.height() + (q0 - bounds.center()).hypot()) + 1.0;
let mut side = BezPath::new();
side.move_to(q0 - along * reach);
side.line_to(q0 + along * reach);
side.line_to(q0 + along * reach + across * reach);
side.line_to(q0 - along * reach + across * reach);
side.close_path();
let kept = vectorcraft_pathops::boolean(outline, FillRule::NonZero, &PathData::from_bezpath(&side), FillRule::NonZero, BoolOp::Intersect);
kept.bounds().is_some().then_some(kept)
}
/// The part of polygon `p` where `sign` times `values` (one per point, varying linearly along each
/// edge) is at least 0.
fn half(p: &[Point], values: &[f64], sign: f64) -> Vec<Point> {
let mut out = vec![];
for (j, (&a, &va)) in p.iter().zip(values).enumerate() {
let k = (j + 1) % p.len();
let (Some(&b), Some(&vb)) = (p.get(k), values.get(k)) else { continue };
let (sa, sb) = (va * sign, vb * sign);
if sa >= 0.0 {
out.push(a);
}
if (sa >= 0.0) != (sb >= 0.0) {
out.push(a.lerp(b, sa / (sa - sb)));
}
}
out
}
/// `order` (back to front), when it draws a face of one of a shape's strokes and an overlapping face
/// of the same shape's fill or strokes the wrong way round for their depths where they overlap on
/// the drawing, with every pair of overlapping faces that keep a polygon and a plane
/// ([`convex_face`]: turned toward the viewer, not a planar end), of any shape, put in the order of
/// their depths where they overlap: the face nearer the viewer there goes after the other. A fill
/// wall and a face of the same shape's covering stroke ([`Paints::Stroke`]) keep their order. Each
/// face otherwise keeps its place in `order`, so a fill wall in the gap between two dashes stays
/// where its depth puts it. A cycle of such pairs is broken at the face that comes first in `order`.
/// A face drawn last (a planar end turned toward the viewer, at depth `f64::MAX`) keeps its place:
/// no face moves across it. Otherwise `order` as it is.
fn local_order(faces: &[Placed], order: Vec<usize>) -> Vec<usize> {
use std::cmp::Reverse;
// The faces of each shape that take part, from left to right for a sweep along x.
let mut shapes: Vec<Vec<usize>> = vec![];
for (k, f) in faces.iter().enumerate() {
if f.outline.len() < 3 || f.plane.is_none() {
continue;
}
if shapes.len() <= f.member {
shapes.resize_with(f.member + 1, Vec::new);
}
shapes[f.member].push(k);
}
if !shapes.iter().any(|list| list.iter().any(|&k| faces[k].paints != Paints::Fill)) {
return order;
}
for list in &mut shapes {
list.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
}
// A fill wall and a face of the same shape's covering stroke keep the order [`draw_order`] gave
// them: the stroke's solid holds the wall, which never shows.
let covered = |f: &Placed, s: &Placed| f.paints == Paints::Fill && f.side && s.paints == Paints::Stroke && f.member == s.member;
// Is there a face of a shape's strokes and a face of the same shape's fill or strokes that the
// order of their depths draws the wrong way round where they overlap?
let mut position = vec![0usize; faces.len()];
for (at, &k) in order.iter().enumerate() {
position[k] = at;
}
let mut checks = 0usize;
let mut misordered = false;
'shapes: for list in &shapes {
for (i, &f) in list.iter().enumerate() {
let a = &faces[f];
for &s in list.iter().skip(i + 1).take_while(|&&s| faces[s].bounds.x0 < a.bounds.x1) {
if checks >= MAX_LOCAL_CHECKS {
break 'shapes;
}
checks += 1;
let b = &faces[s];
if (a.paints == Paints::Fill && b.paints == Paints::Fill) || covered(a, b) || covered(b, a) || !rects_overlap(a.bounds, b.bounds) {
continue;
}
if nearer_where_overlapping(a, b).is_some_and(|a_nearer| a_nearer != (position[f] > position[s])) {
misordered = true;
break 'shapes;
}
}
}
}
if !misordered {
return order;
}
// Moving those faces must not carry them past any other face they overlap, so every pair of
// faces with a polygon and a plane that overlap goes in the order of their depths there.
let mut sweep: Vec<usize> = (0..faces.len()).filter(|&k| faces[k].outline.len() >= 3 && faces[k].plane.is_some()).collect();
sweep.sort_by(|&a, &b| faces[a].bounds.x0.total_cmp(&faces[b].bounds.x0));
// For each face, the faces drawn after it, and for each, how many go before it.
let mut after: Vec<Vec<usize>> = vec![vec![]; faces.len()];
let mut waits = vec![0usize; faces.len()];
'pairs: for (i, &k) in sweep.iter().enumerate() {
let a = &faces[k];
for &j in sweep.iter().skip(i + 1).take_while(|&&j| faces[j].bounds.x0 < a.bounds.x1) {
if checks >= MAX_LOCAL_CHECKS {
break 'pairs;
}
checks += 1;
let b = &faces[j];
if !rects_overlap(a.bounds, b.bounds) {
continue;
}
let a_later = if covered(a, b) || covered(b, a) {
position[k] > position[j]
} else {
let Some(a_nearer) = nearer_where_overlapping(a, b) else { continue };
a_nearer
};
let (back, front) = if a_later { (j, k) } else { (k, j) };
after[back].push(front);
waits[front] += 1;
}
}
// Each step draws the face that comes first in `order` of those whose faces before are drawn.
let mut ready: std::collections::BinaryHeap<Reverse<(usize, usize)>> =
(0..faces.len()).filter(|&k| waits[k] == 0).map(|k| Reverse((position[k], k))).collect();
// The faces drawn last, in `order`: each goes only after every face before it in `order`.
let last: Vec<usize> = order.iter().copied().filter(|&k| faces[k].depth >= f64::MAX).collect();
let mut next_last = 0usize;
let mut drawn = vec![false; faces.len()];
let mut out = Vec::with_capacity(order.len());
let mut first = 0usize;
while out.len() < order.len() {
while last.get(next_last).is_some_and(|&k| drawn[k]) {
next_last += 1;
}
let limit = last.get(next_last).map_or(usize::MAX, |&k| position[k]);
let k = match ready.peek() {
Some(&Reverse((at, k))) if at < limit => {
ready.pop();
k
}
_ => {
// A cycle, or the faces left to draw before a face drawn last wait for faces after
// it: the first face in `order` not drawn yet goes next.
while order.get(first).is_some_and(|&k| drawn[k]) {
first += 1;
}
let Some(&k) = order.get(first) else { break };
k
}
};
if drawn[k] {
continue;
}
drawn[k] = true;
out.push(k);
for &j in &after[k] {
waits[j] = waits[j].saturating_sub(1);
if waits[j] == 0 && !drawn[j] {
ready.push(Reverse((position[j], j)));
}
}
}
out
}
/// Whether face `a` is nearer the viewer than face `b` where their polygons overlap on the drawing,
/// measured at the middle of the overlap. `None` when they do not overlap, when either polygon is
/// not convex, or when they are at the same depth there.
fn nearer_where_overlapping(a: &Placed, b: &Placed) -> Option<bool> {
let (pa, pb) = (a.plane?, b.plane?);
let turn = convex(&b.outline)?;
convex(&a.outline)?;
let overlap = clip_convex(&a.outline, &b.outline, turn);
let mid = centroid(&overlap)?;
let (da, db) = (pa.depth_at(mid)?, pb.depth_at(mid)?);
let tolerance = 1e-6 * (1.0 + da.abs().max(db.abs()));
((da - db).abs() > tolerance).then_some(da > db)
}
/// The sign of the turns of convex polygon `p` (`None` when it is not convex or has no area).
fn convex(p: &[Point]) -> Option<f64> {
let n = p.len();
let mut sign = 0.0;
for i in 0..n {
let (a, b, c) = (p[i], p[(i + 1) % n], p[(i + 2) % n]);
let cross = (b - a).cross(c - b);
if cross.abs() <= 1e-12 {
continue;
}
if sign == 0.0 {
sign = cross.signum();
} else if cross.signum() != sign {
return None;
}
}
(sign != 0.0).then_some(sign)
}
/// The part of polygon `subject` inside convex polygon `clip`, whose turns have sign `turn`
/// (Sutherland–Hodgman).
fn clip_convex(subject: &[Point], clip: &[Point], turn: f64) -> Vec<Point> {
let mut out = subject.to_vec();
for i in 0..clip.len() {
if out.is_empty() {
break;
}
let (e0, e1) = (clip[i], clip[(i + 1) % clip.len()]);
let side = |p: Point| (e1 - e0).cross(p - e0) * turn;
let input = std::mem::take(&mut out);
for j in 0..input.len() {
let (p, q) = (input[j], input[(j + 1) % input.len()]);
let (sp, sq) = (side(p), side(q));
if sp >= 0.0 {
out.push(p);
}
if (sp >= 0.0) != (sq >= 0.0) {
let t = sp / (sp - sq);
out.push(p.lerp(q, t));
}
}
}
out
}
/// The centroid of polygon `p`, `None` when it has (almost) no area. It is measured from the
/// polygon's first point, so a small polygon far from the origin keeps its area.
fn centroid(p: &[Point]) -> Option<Point> {
let origin = *p.first()?;
let n = p.len();
let (mut area, mut cx, mut cy) = (0.0, 0.0, 0.0);
for i in 0..n {
let (a, b) = (p[i] - origin, p[(i + 1) % n] - origin);
let cross = a.x * b.y - b.x * a.y;
area += cross;
cx += (a.x + b.x) * cross;
cy += (a.y + b.y) * cross;
}
(area.abs() > 1e-9).then(|| origin + Vec2::new(cx / (3.0 * area), cy / (3.0 * area)))
}
/// The most bounds comparisons [`draw_order`] makes; the fill walls it has not reached by then keep
/// their depths.
const MAX_OVERLAP_CHECKS: usize = 4_000_000;
@@ -742,7 +1191,8 @@ const MAX_OVERLAP_CHECKS: usize = 4_000_000;
/// of a shape's fill turned toward the viewer is drawn before each face of the same shape's
/// covering strokes ([`Paints::Stroke`]), turned toward the viewer, whose bounds overlap its own.
/// Such a stroke's closed solid holds the fill's walls, so they never show and can be drawn under
/// any other face.
/// any other face. A shape's fill faces and the faces of its other strokes then go in the order of
/// their depths where they overlap ([`local_order`]).
fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
// Each face's depth to sort by, and whether it was moved before a stroke face at that depth.
let mut keys: Vec<(f64, bool)> = faces.iter().map(|f| (f.depth, false)).collect();
@@ -781,7 +1231,7 @@ fn draw_order(faces: &[Placed], sealed: bool) -> Vec<usize> {
// A stable sort: faces at the same depth keep the order of the appearance, and a fill's side
// face moved to a stroke face's depth goes before it.
order.sort_by(|&a, &b| keys[a].0.total_cmp(&keys[b].0).then(keys[b].1.cmp(&keys[a].1)));
order
local_order(faces, order)
}
/// `shapes`, the members of group or layer `n`, reshaped by the visible geometry effects `before`
@@ -806,7 +1256,9 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as
/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's
/// fill walls before the faces of its covering strokes that overlap them: [`draw_order`]), the
/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and
/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the
/// order of their depths where they overlap: [`draw_order`]), the
/// faces of a solid in a gradient with transparent stops in runs that carry its opacity mask
/// ([`in_runs`]);
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
@@ -995,18 +1447,22 @@ type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>
/// [`with_graphics`] of built surfaces, each drawn whole.
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts)
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), 0, arts)
}
/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each
/// right after its surface, with that surface's scopes and its opacity mask (a gradient's
/// transparency), so a graphic is hidden where its cap is.
fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc<Node>)>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
/// `surfaces` (those from index `first`) drawn whole, each with its scopes, and the graphics `arts`
/// ([`placed_graphics`]) of those surfaces each right after its surface, with that surface's scopes
/// and its opacity mask (a gradient's transparency), so a graphic is hidden where its cap is.
fn with_graphics<'s>(
surfaces: Vec<(&'s [Scope], Arc<Node>)>,
first: usize,
arts: &[(usize, PlanarFace, Arc<Node>)],
) -> Vec<(&'s [Scope], Arc<Node>)> {
let mut out = Vec::with_capacity(surfaces.len() + arts.len());
for (k, (scopes, s)) in surfaces.into_iter().enumerate() {
let mask = s.extras().mask.clone();
out.push((scopes, s));
out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| {
out.extend(arts.iter().filter(|(at, ..)| *at == first + k).map(|(.., art)| {
let mut art = art.clone();
if let Some(mask) = &mask {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
@@ -1058,7 +1514,7 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
}
}
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
let out = with_graphics(out, &arts);
let out = with_graphics(out, 0, &arts);
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
}
let (parts, bounds) = solid_parts(shapes, b);
@@ -1085,6 +1541,43 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
let (_, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal
});
let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path));
// A solid whose surface is one composite of all its facets ([`surface`]: a solid color under
// colored lights with smooth shading) has no faces to order.
let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some());
// The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under
// a member's opacity mask or blending, each member's faces go in one order of their own when its
// fills and strokes are opaque, blend normally, carry no opacity mask and are not composites.
let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f));
let shape_order: Vec<bool> = (0..shapes.len())
.map(|shape| {
solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| {
let (paint, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f)
})
})
.collect();
let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order };
if solids.iter().any(|s| ordered(s.4)) {
// A stroke face that passes through a fill wall or another stroke's face is cut where it
// does. The pieces count against the limits as the faces did: cutting stops before the
// faces pass MAX_OBJECT_FACES or their paint copies pass the allowance, so an effect that
// draws uncut still draws.
let counts: Vec<usize> = solids.iter().map(|(.., f, _)| f.len()).collect();
let room = cut_room(solids.iter().map(|(item, ..)| *item), counts.iter().sum(), paint_bytes);
let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids
.iter_mut()
.filter(|(.., shape)| ordered(*shape))
.map(|(item, _, _, f, shape)| (Paints::of(item, closed(*shape)), *shape, f))
.collect();
cut_stroke_faces(&mut cuts, room);
for ((item, _, _, f, _), before) in solids.iter().zip(counts) {
let added = f.get(before..).unwrap_or_default();
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(added, paint_ref(item), colored), paint_ref(item)) {
return None;
}
}
}
let arts = if !graphics_on {
vec![]
} else {
@@ -1100,11 +1593,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
.collect();
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
};
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
.map(|(item, member, scopes, f, shape)| {
let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed));
let paints = Paints::of(item, closed);
let paints = Paints::of(item, closed(shape));
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
@@ -1112,50 +1605,86 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
(depths, art, scopes, ends)
})
.collect();
if masks {
return Some(masked(n.id, whole_surfaces(surfaces, &arts)));
}
// One order takes a plain group of faces from each solid, one face for each facet. With
// colored lights a surface can instead be one clipped composite of all its facets. A composite
// has no faces to order, so when any surface is one, every surface of the solid, masked ones
// included, draws whole in member order.
let plain =
surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
// A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs
// ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole,
// each graphic right after its surface.
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
let masked_faces = masks.iter().any(Option::is_some);
if !opaque || !plain || (masked_faces && !arts.is_empty()) {
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
}
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
if let NodeKind::Group { children, .. } = s.kind {
placed.extend(depths);
faces.extend(children.into_iter().map(|face| Some((surface, face))));
ends.extend(e);
}
}
let sealed = match fx.id.as_str() {
INFLATE => inflate_options(&p).cap,
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
_ => extrude_options(&p).cap,
};
// One order takes a plain group of faces from each solid, one face for each facet. With
// colored lights a surface can instead be one clipped composite of all its facets. A composite
// has no faces to order, so it draws whole.
let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len());
if masks {
// Each member's surfaces, in the scopes of its opacity mask or blending: its faces in one
// order when it is opaque and plain, otherwise each surface whole.
let mut out = vec![];
let mut surfaces = surfaces.into_iter().zip(members).enumerate().peekable();
while let Some((first, (s, member))) = surfaces.next() {
let mut run = vec![s];
while let Some((_, (s, _))) = surfaces.next_if(|(_, (_, m))| *m == member) {
run.push(s);
}
let flat = run.iter().all(|s| plain(s) && s.1.opacity >= 1.0 && s.1.blend == BlendMode::Normal && s.1.extras().mask.is_none());
if ordered(member) && flat {
let scopes = run.first().map_or(&[][..], |s| s.2);
out.push((scopes, Arc::new(Node::group(n.id, in_one_order(n.id, run, first, &arts, sealed)))));
} else {
out.extend(with_graphics(run.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), first, &arts));
}
}
return Some(masked(n.id, out));
}
if !opaque || !surfaces.iter().all(plain) {
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
}
Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed)))])
}
/// The faces of `surfaces` (plain groups of their faces, [`surfaces_for`]'s from index `first`) in
/// one order ([`draw_order`], `sealed` for solids with caps), each of the graphics `arts` of those
/// surfaces right after the last face it is drawn on, of the surfaces that share it. A surface in a gradient with transparent stops
/// carries an opacity mask: its faces go in runs ([`in_runs`]), each carrying the mask, and each of
/// its graphics carries the mask too ([`with_graphics`]), so a graphic is hidden where its cap is.
fn in_one_order(id: NodeId, surfaces: Vec<BuiltSurface<'_>>, first: usize, arts: &[(usize, PlanarFace, Arc<Node>)], sealed: bool) -> Vec<Arc<Node>> {
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
let arts: Vec<&(usize, PlanarFace, Arc<Node>)> = arts.iter().filter(|(at, ..)| (first..first + surfaces.len()).contains(at)).collect();
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
if let NodeKind::Group { children, .. } = s.kind {
placed.extend(depths);
faces.extend(children.into_iter().map(|face| Some((surface, face))));
ends.extend(e.into_iter().map(|end| end.map(|end| (surface, end))));
}
}
let order = draw_order(&placed, sealed);
if masked_faces {
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]);
}
// Each face's graphics go right after the last of the faces they are drawn on.
let last: Vec<Option<usize>> =
arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect();
let mut children = Vec::with_capacity(order.len() + arts.len());
// Each graphic goes right after the last of the faces it is drawn on, among the surfaces that
// share it ([`placed_graphics`]): a masked surface's own, or else the run of surfaces without a
// mask that ends at its surface.
let last: Vec<Option<usize>> = arts
.iter()
.map(|(at, face, _)| {
let at = at - first;
let from = if masks.get(at).is_some_and(Option::is_some) {
at
} else {
masks.get(..at).and_then(|before| before.iter().rposition(Option::is_some)).map_or(0, |k| k + 1)
};
order.iter().rposition(|k| ends.get(*k).copied().flatten().is_some_and(|(surface, end)| end == *face && (from..=at).contains(&surface)))
})
.collect();
let mut drawn: Vec<(usize, Arc<Node>)> = Vec::with_capacity(order.len() + arts.len());
for (at, k) in order.into_iter().enumerate() {
children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face));
children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone()));
drawn.extend(faces.get_mut(k).and_then(Option::take));
drawn.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (surface, .., art))| {
let mut art = art.clone();
if let Some(mask) = masks.get(surface - first).cloned().flatten() {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask);
}
// An index past the surfaces: the graphic goes in a run of its own, with its own mask.
(masks.len(), art)
}));
}
Some(vec![Arc::new(Node::group(n.id, children))])
if masks.iter().any(Option::is_some) { in_runs(id, drawn, &masks) } else { drawn.into_iter().map(|(_, face)| face).collect() }
}
/// `faces` in their back-to-front order, each with the index of its surface, where some surfaces
+467
View File
@@ -253,6 +253,468 @@ fn a_fills_walls_are_drawn_before_the_stroke_faces_over_them() {
}
}
/// The faces of the solids effect `id` with `params` builds for `n`, in the order they are drawn,
/// as [`surfaces_for`] orders them, each with the index of the part ([`solid_parts`]) it was built
/// from and whether it is a stroke's.
fn drawn_parts(n: &Node, id: &str, params: &Value) -> Vec<(Facet, usize, bool)> {
let (path, rule) = profile(n).unwrap();
let shapes = [Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }];
let p = crate::merged_params(id, params);
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let mut solids = vec![];
for (part, ((item, _, _, _, _, member), f)) in parts.iter().zip(built_solids(id, &p, &parts, bounds, MAX_OBJECT_FACES)).enumerate() {
let Some(f) = f.unwrap() else { continue };
let closed = holds_edge(id, &shapes[*member].path);
solids.push((Paints::of(item, closed), *member, f, part, matches!(item, AppearanceItem::Stroke(_))));
}
let mut cuts: Vec<(Paints, usize, &mut Vec<Facet>)> = solids.iter_mut().map(|(paints, member, f, _, _)| (*paints, *member, f)).collect();
cut_stroke_faces(&mut cuts, MAX_OBJECT_FACES);
let (mut placed, mut all) = (vec![], vec![]);
for (paints, member, f, part, stroke) in solids {
for facet in f {
placed.push(Placed::of(&facet, member, paints));
all.push((facet, part, stroke));
}
}
let sealed = match id {
INFLATE => inflate_options(&p).cap,
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
_ => extrude_options(&p).cap,
};
draw_order(&placed, sealed).into_iter().map(|k| all[k].clone()).collect()
}
/// Is `p` inside the polygon of `f` (nonzero winding)?
fn facet_contains(f: &Facet, p: Point) -> bool {
let mut winding = 0i32;
for c in &f.contours {
for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) {
let cross = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
if a.y <= p.y && b.y > p.y && cross > 0.0 {
winding += 1;
} else if a.y > p.y && b.y <= p.y && cross < 0.0 {
winding -= 1;
}
}
}
winding != 0
}
/// The points of a 1 pt grid over `faces` (drawn in that order, each with whether it is a stroke's)
/// where the face drawn on top is the fill's while a face of the stroke turned toward the viewer is
/// nearer the viewer there by more than 0.5 pt, or the other way round. Points within 0.3 pt of an
/// edge are left out.
fn wrong_on_top(faces: &[(Facet, bool)]) -> Vec<Point> {
let polygons: Vec<&Facet> = faces.iter().map(|(f, _)| f).collect();
let extent =
polygons.iter().flat_map(|f| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p));
let mut wrong = vec![];
let mut y = extent.y0.floor() + 0.5;
while y < extent.y1 {
let mut x = extent.x0.floor() + 0.5;
while x < extent.x1 {
let p = Point::new(x, y);
let well_inside = |f: &Facet| {
[(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy)))
};
let top = faces.iter().rposition(|(f, _)| facet_contains(f, p));
if let Some((f, stroke)) = top.and_then(|k| faces.get(k)).filter(|(f, _)| !f.away && well_inside(f)) {
let nearest = |of_stroke: bool| {
faces.iter().filter(|(g, s)| *s == of_stroke && !g.away && well_inside(g)).filter_map(|(g, _)| g.depth_at(p)).reduce(f64::max)
};
if let (Some(ds), Some(df)) = (nearest(true), nearest(false))
&& (ds - df).abs() > 0.5
&& (ds > df) != *stroke
&& f.depth_at(p).is_some()
{
wrong.push(p);
}
}
x += 1.0;
}
y += 1.0;
}
wrong
}
/// The points of a 1 pt grid over `faces` (drawn in that order) where the face drawn on top is
/// farther from the viewer than another face turned toward the viewer, of any part, by more than
/// 0.5 pt. Points within 0.3 pt of an edge, and faces without a plane, are left out.
fn misdrawn(faces: &[(Facet, usize, bool)]) -> Vec<Point> {
let extent =
faces.iter().flat_map(|(f, ..)| f.contours.iter().flatten()).fold(Rect::new(f64::MAX, f64::MAX, f64::MIN, f64::MIN), |r, p| r.union_pt(*p));
let mut wrong = vec![];
let mut y = extent.y0.floor() + 0.5;
while y < extent.y1 {
let mut x = extent.x0.floor() + 0.5;
while x < extent.x1 {
let p = Point::new(x, y);
let well_inside = |f: &Facet| {
[(-0.3, -0.3), (0.3, -0.3), (-0.3, 0.3), (0.3, 0.3), (0.0, 0.0)].iter().all(|(dx, dy)| facet_contains(f, Point::new(x + dx, y + dy)))
};
let top = faces.iter().rposition(|(f, ..)| facet_contains(f, p)).and_then(|k| faces.get(k)).filter(|(f, ..)| !f.away && well_inside(f));
if let Some(on_top) = top.and_then(|(f, ..)| f.depth_at(p)) {
let nearest = faces.iter().filter(|(g, ..)| !g.away && well_inside(g)).filter_map(|(g, ..)| g.depth_at(p)).reduce(f64::max);
if nearest.is_some_and(|d| d - on_top > 0.5) {
wrong.push(p);
}
}
x += 1.0;
}
y += 1.0;
}
wrong
}
/// The faces of a shape's fill and strokes are drawn in the order of their depths where they
/// overlap: on a turned C, with or without perspective, under a stroke that does not cover the
/// fill's whole edge (dashed, with a width profile, or with a brush), under a plain stroke and
/// under two strokes whose faces pass through each other, no point shows a face farther from the
/// viewer than another, in Extrude & Bevel and Extrude & Bevel (Classic), and only a few in
/// Inflate, where curved puffs cross.
#[test]
fn fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap() {
use vectorcraft_doc::{Dash, WidthProfile};
let views = [
json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}),
json!({"rotationX": 25, "rotationY": -55, "rotationZ": 10}),
json!({"rotationX": -30, "rotationY": 50, "rotationZ": 5, "perspectiveAngle": 40}),
json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}),
];
type Style<'a> = (&'a str, &'a dyn Fn(&mut Node));
let first = |n: &mut Node, set: &dyn Fn(&mut StrokeLayer)| {
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
set(s);
}
};
let dash = |pattern: Vec<f64>, offset: f64| Some(Dash { pattern, offset, align_corners: false });
let styles: [Style; 6] = [
("plain", &|_| {}),
("dashed", &|n| first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0))),
("profiled", &|n| first(n, &|s| s.profile = Some(WidthProfile::lens()))),
("brushed", &|n| first(n, &|s| s.brush = Some("brush".into()))),
("dashed with perspective", &|n| first(n, &|s| s.dash = dash(vec![20.0, 6.0], 3.0))),
("two strokes", &|n| {
first(n, &|s| s.dash = dash(vec![12.0, 12.0], 0.0));
let mut wide = StrokeLayer::new(Paint::solid(RED), 14.0);
wide.profile = Some(WidthProfile::lens());
n.appearance.items.push(AppearanceItem::Stroke(wide));
}),
];
for id in [EXTRUDE, CLASSIC_EXTRUDE, INFLATE] {
for (v, view) in views.iter().enumerate() {
for (style, set) in &styles {
// The last two views, for the plain and the two strokes only.
if v >= 2 && !["plain", "two strokes"].contains(style) {
continue;
}
let mut params = view.clone();
params["depth"] = json!(60);
if style.contains("perspective") {
params["perspectiveAngle"] = json!(40);
}
let mut n = stroked(&letter_c());
set(&mut n);
let parts = drawn_parts(&n, id, &params);
let faces: Vec<(Facet, bool)> = parts.iter().map(|(f, _, s)| (f.clone(), *s)).collect();
assert!(faces.iter().any(|(_, s)| *s) && faces.iter().any(|(_, s)| !*s), "{id} {view} {style}: faces of both");
// Inflate's curved puffs cross each other along curves its flat facets only follow
// roughly: a few points next to those crossings may still show the farther face.
let allowed = if id == INFLATE { 5 } else { 0 };
let wrong = wrong_on_top(&faces);
assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points drawn in the wrong paint, first {:?}", wrong.len(), wrong.first());
let wrong = misdrawn(&parts);
assert!(wrong.len() <= allowed, "{id} {view} {style}: {} points show a farther face, first {:?}", wrong.len(), wrong.first());
}
}
}
}
/// The paths of `art`'s faces in drawing order, leaving out the graphics (clip groups).
fn face_paths(art: &Node) -> Vec<PathData> {
fn walk(n: &Node, out: &mut Vec<PathData>) {
match &n.kind {
NodeKind::Group { clip: true, .. } => {}
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ => out.extend(n.path_data().cloned()),
}
}
let mut out = vec![];
walk(art, &mut out);
out
}
/// A member of a 3D group with an opacity mask or a blending mode of its own draws its fill's and
/// its strokes' faces in one order inside that mask, the order the same member draws them in
/// without it, its dashes cut where they pass through the fill's walls. A member whose stroke is
/// translucent still draws each surface whole.
#[test]
fn a_masked_members_fill_and_stroke_faces_go_in_one_order() {
let mut member = stroked(&letter_c());
if let Some(AppearanceItem::Stroke(s)) = member.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
}
let solid = |member: Node| {
let mut g = Node::group(NodeId(2), vec![Arc::new(member)]);
g.appearance.effects.push(fx(EXTRUDE, json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})));
solid_art(&g).unwrap()
};
let cover = Node::path(
NodeId(900),
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)),
Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0),
);
let mut masked = member.clone();
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true)));
let mut multiplied = member.clone();
multiplied.blend = BlendMode::Multiply;
let unmasked = face_paths(&solid(member.clone()));
for (what, scoped) in [("masked", masked.clone()), ("multiplied", multiplied)] {
let art = solid(scoped);
let mut scopes = 0;
art.walk(&mut |n| scopes += usize::from(n.extras().mask.is_some() || n.blend == BlendMode::Multiply));
assert!(scopes > 0, "{what}: drawn in its scope");
assert_eq!(face_paths(&art), unmasked, "{what}: the faces in the member's one order");
}
// A translucent stroke keeps its surface whole: the fill's faces, then the stroke's.
if let Some(AppearanceItem::Stroke(s)) = masked.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
s.opacity = 0.5;
}
let art = solid(masked);
let mut groups = vec![];
art.walk(&mut |n| {
if n.opacity == 0.5 {
groups.push(n.children().map_or(0, Vec::len));
}
});
assert_eq!(groups.len(), 1, "the stroke's surface is one translucent group");
}
/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the
/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color,
/// drawn as one composite of each surface's facets, still draws each surface whole.
#[test]
fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let gradient = |c: Color| {
Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(
GradientKind::Linear,
vec![GradientStop::new(0.0, c), GradientStop::new(1.0, Color::WHITE)],
))))
};
let mut n = stroked(&letter_c());
for item in &mut n.appearance.items {
match item {
AppearanceItem::Fill(f) => f.paint = gradient(RED),
AppearanceItem::Stroke(s) => {
s.paint = gradient(BLUE);
s.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
}
}
}
// How many surfaces the art draws, and how many faces the first holds.
let drawn = |n: &Node, lights: Option<Value>| {
let mut n = n.clone();
let mut p = json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60});
if let Some(lights) = lights {
p["lights"] = lights;
}
n.appearance.effects.push(fx(INFLATE, p));
let art = solid_art(&n).unwrap();
let surfaces = art.children().unwrap();
(surfaces.len(), surfaces[0].children().map_or(0, Vec::len))
};
let colored = json!([{"color": "#ff8080"}]);
let white = drawn(&n, None);
assert_eq!(white.0, 1, "one order");
let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len();
assert_eq!(white.1, cut, "the white light's faces, cut");
assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light");
// A solid color under the colored light: a composite for each of the fill and the stroke.
let solid = stroked(&letter_c());
assert_eq!(drawn(&solid, Some(colored)).0, 2);
}
/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they
/// overlap is cut along the line where their depths meet, into the piece in front of the wall and
/// the piece behind it; a face on one side of the wall, another shape's stroke, a covering stroke
/// and a cut past the room left are left whole.
#[test]
fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
let facet = |x: f64, normal: [f64; 3], offset: f64| Facet {
contours: vec![vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]],
depth: 0.0,
brightness: 1.0,
illumination: [1.0; 3],
normal,
rgb_gradient: None,
outline: None,
side: true,
away: false,
end: None,
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
};
let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0);
// z = x - 8: behind the wall left of x = 8, in front of it right of it.
let r = std::f64::consts::FRAC_1_SQRT_2;
let mut through = facet(5.0, [-r, 0.0, r], -8.0 * r);
// Its curved outline: the top edge bows up to y = -2.
let mut curved = BezPath::new();
curved.move_to((5.0, 0.0));
curved.curve_to((8.0, -8.0 / 3.0), (12.0, -8.0 / 3.0), (15.0, 0.0));
curved.line_to((15.0, 10.0));
curved.line_to((5.0, 10.0));
curved.close_path();
through.outline = Some(PathData::from_bezpath(&curved));
let extent = |f: &Facet| polygon_bounds(&f.contours[0]);
let cut_with = |paints: Paints, member: usize, room: usize| {
let (mut fill, mut stroke) = (vec![wall.clone()], vec![through.clone()]);
let mut solids: Vec<(Paints, usize, &mut Vec<Facet>)> = vec![(Paints::Fill, 0, &mut fill), (paints, member, &mut stroke)];
cut_stroke_faces(&mut solids, room);
stroke
};
let pieces = cut_with(Paints::Other, 0, 10);
assert_eq!(pieces.len(), 2);
let (near, far) = (extent(&pieces[0]), extent(&pieces[1]));
assert!((near.x0 - 8.0).abs() < 1e-9 && near.x1 == 15.0 && far.x0 == 5.0 && (far.x1 - 8.0).abs() < 1e-9, "{near:?} {far:?}");
assert!(pieces[0].depth > 0.0 && pieces[1].depth < 0.0);
// Each piece keeps its side of the curved outline, the bowed edge included.
let curve = |f: &Facet| f.outline.as_ref().and_then(PathData::bounds).unwrap();
let (near, far) = (curve(&pieces[0]), curve(&pieces[1]));
assert!((near.x0 - 8.0).abs() < 1e-6 && (near.x1 - 15.0).abs() < 1e-6 && near.y0 < -1.5, "{near:?}");
assert!((far.x0 - 5.0).abs() < 1e-6 && (far.x1 - 8.0).abs() < 1e-6 && far.y0 < -1.5, "{far:?}");
let whole = std::slice::from_ref(&through);
assert_eq!(cut_with(Paints::Other, 1, 10), whole, "another shape's stroke");
assert_eq!(cut_with(Paints::Stroke, 0, 10), whole, "a covering stroke");
assert_eq!(cut_with(Paints::Other, 0, 0), whole, "no room");
let (mut fill, mut stroke) = (vec![wall.clone()], vec![facet(5.0, [0.0, 0.0, 1.0], 1.0)]);
cut_stroke_faces(&mut [(Paints::Fill, 0, &mut fill), (Paints::Other, 0, &mut stroke)], 10);
assert_eq!(stroke.len(), 1, "in front of the wall wherever they overlap");
// Of two of a shape's strokes whose faces pass through each other, the later stroke's face is
// cut against the earlier one's; a covering stroke's face is never cut, and the other stroke's
// face is cut against it. Two shapes' strokes are left whole.
for (case, (first, second, cut_first)) in
[(Paints::Other, Paints::Other, false), (Paints::Stroke, Paints::Other, false), (Paints::Other, Paints::Stroke, true)].into_iter().enumerate()
{
let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]);
cut_stroke_faces(&mut [(first, 0, &mut a), (second, 0, &mut b)], 10);
assert_eq!((a.len(), b.len()), if cut_first { (2, 1) } else { (1, 2) }, "case {case}");
}
let (mut a, mut b) = (vec![wall.clone()], vec![through.clone()]);
cut_stroke_faces(&mut [(Paints::Other, 0, &mut a), (Paints::Other, 1, &mut b)], 10);
assert_eq!((a.len(), b.len()), (1, 1), "two shapes");
}
/// A small polygon far from the origin keeps its area and centroid.
#[test]
fn a_small_polygon_far_away_has_a_centroid() {
let far = 100_000_000.0;
let square = [Point::new(far, far), Point::new(far + 1.0, far), Point::new(far + 1.0, far + 1.0), Point::new(far, far + 1.0)];
let c = centroid(&square).unwrap();
assert!((c.x - far - 0.5).abs() < 1e-6 && (c.y - far - 0.5).abs() < 1e-6, "{c:?}");
assert!(centroid(&[]).is_none() && centroid(&square[..2]).is_none());
}
/// Cutting adds no more faces than the object's face limit and the paint-copy allowance leave room
/// for, so an effect that draws with its faces uncut still draws.
#[test]
fn cutting_stays_within_the_face_limit_and_the_paint_allowance() {
let items = stroked(&letter_c()).appearance.items.clone();
let stroke = items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).unwrap();
let mut one = 0usize;
crate::revolve::paint_copies_add(&mut one, 6, paint_ref(stroke));
let max = crate::revolve::MAX_PAINT_COPIES;
assert_eq!(cut_room(items.iter(), 10, 0), (MAX_OBJECT_FACES - 10).min(max / one));
assert_eq!(cut_room(items.iter(), MAX_OBJECT_FACES + 5, 0), 0);
assert_eq!(cut_room(items.iter(), 10, max - 3 * one), 3);
assert_eq!(cut_room(items.iter(), 10, max + 1), 0);
}
/// Where a shape's fill wall and a face of its stroke that leaves gaps overlap, the one nearer the
/// viewer there is drawn after the other, whichever their depths put first; a stroke face that
/// overlaps no fill wall keeps its place.
#[test]
fn local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order() {
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
let at = |depth: f64, x: f64, z: f64, paints: Paints| Placed {
depth,
side: true,
away: false,
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
member: 0,
paints,
outline: square(x),
plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: z, center: Point::ZERO, eye: None }),
};
// 0 a fill wall at z 0; 1 a stroke face over half of it, nearer, sorted before it; 2 a stroke
// face elsewhere; 3 a stroke face over it, farther, sorted after it.
let faces =
[at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 1.0, Paints::Other), at(1.0, 20.0, 1.0, Paints::Other), at(6.0, 2.0, -1.0, Paints::Other)];
assert_eq!(draw_order(&faces, true), [2, 3, 0, 1]);
assert_eq!(draw_order(&faces, false), [2, 3, 0, 1]);
// A covering stroke's faces keep the wall's own rule.
let covering: Vec<Placed> = faces
.iter()
.map(|f| Placed { paints: if f.paints == Paints::Other { Paints::Stroke } else { f.paints }, outline: vec![], plane: None, ..*f })
.collect();
assert_eq!(draw_order(&covering, false), [2, 1, 0, 3]);
// Another shape's stroke, and a stroke face at the same depth where they overlap, move nothing.
let other_shape: Vec<Placed> =
faces[..3].iter().map(|f| Placed { member: usize::from(f.paints == Paints::Other), outline: f.outline.clone(), ..*f }).collect();
assert_eq!(draw_order(&other_shape, true), [2, 1, 0]);
let level = [at(5.0, 0.0, 0.0, Paints::Fill), at(2.0, 5.0, 0.0, Paints::Other)];
assert_eq!(draw_order(&level, true), [1, 0]);
// A stroke face moved after its fill's wall does not pass a nearer face of another shape that
// it overlaps: 0 a stroke face, 1 another shape's face in front of both, 2 the fill's wall.
let in_front = Placed { member: 1, ..at(2.0, 5.0, 2.0, Paints::Fill) };
let shapes = [at(1.0, 5.0, 1.0, Paints::Other), in_front, at(3.0, 0.0, 0.0, Paints::Fill)];
assert_eq!(draw_order(&shapes, true), [2, 0, 1]);
// A shape with a covering stroke as well keeps its fill wall before the covering stroke's face,
// even where that face is the farther: 0 the fill's wall, 1 the covering stroke's face behind
// it, 2 the other stroke's face in front.
let both = [at(3.0, 0.0, 0.0, Paints::Fill), at(3.0, 0.0, -1.0, Paints::Stroke), at(2.0, 5.0, 1.0, Paints::Other)];
assert_eq!(draw_order(&both, true), [0, 1, 2]);
// Faces of a shape's strokes go in the order of their depths where they overlap too, with no
// fill face among them: 1 is nearer than 0 there, though sorted before it.
for (case, (back, front)) in
[(Paints::Other, Paints::Other), (Paints::Stroke, Paints::Other), (Paints::Stroke, Paints::Stroke)].into_iter().enumerate()
{
let strokes = [at(5.0, 0.0, 0.0, back), at(2.0, 5.0, 1.0, front)];
assert_eq!(draw_order(&strokes, true), [0, 1], "case {case}");
}
}
/// A cycle of overlapping stroke faces is broken at the face that comes first by depth, and a cap
/// drawn last stays after every wall: 0 at x 0 to 10, flat at z 0; 1 at x 4 to 14, z = x - 8; 2 at
/// x 8 to 18, flat at z 1. Where they overlap, 0 is nearer than 1, 1 nearer than 2 and 2 nearer
/// than 0. 3 is the cap.
#[test]
fn a_depth_cycle_keeps_the_cap_last() {
let square = |x: f64| vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)];
let at = |depth: f64, x: f64, normal: [f64; 3], offset: f64| Placed {
depth,
side: true,
away: false,
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
member: 0,
paints: Paints::Other,
outline: square(x),
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
};
let cap = Placed {
depth: f64::MAX,
side: false,
away: false,
bounds: Rect::new(0.0, 0.0, 18.0, 10.0),
member: 0,
paints: Paints::Other,
outline: vec![],
plane: None,
};
let faces = [at(1.0, 0.0, [0.0, 0.0, 1.0], 0.0), at(2.0, 4.0, [-1.0, 0.0, 1.0], -8.0), at(3.0, 8.0, [0.0, 0.0, 1.0], 1.0), cap];
assert_eq!(draw_order(&faces, true), [0, 2, 1, 3]);
}
/// The order keeps depths except where a shape's fill wall turned toward the viewer overlaps a
/// face of the same shape's stroke drawn before it: the wall then goes just before that face. A
/// cap, a face turned away, another shape's stroke, a stroke face the wall does not overlap and an
@@ -266,6 +728,8 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() {
bounds: Rect::new(x, 0.0, x + 10.0, 10.0),
member,
paints,
outline: vec![],
plane: None,
};
// 0 the fill's wall; 1 the stroke's wall over it; 2 another shape's stroke over it; 3 a stroke
// wall elsewhere; 4 a stroke face turned away; 5 a fill cap; 6 the stroke's cap, nearer; 7 a
@@ -292,6 +756,9 @@ fn the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps() {
};
assert!(Paints::of(&stroke(&|_| {}), true) == Paints::Stroke);
assert!(Paints::of(&stroke(&|_| {}), false) == Paints::Other, "an open shape");
let closed = profile(&stroked(&letter_c())).unwrap().0;
assert!(holds_edge(EXTRUDE, &closed) && holds_edge(CLASSIC_EXTRUDE, &closed));
assert!(!holds_edge(INFLATE, &closed), "an inflated fill can rise in front of its stroke");
assert!(Paints::of(&stroke(&|s| s.width = 0.0), true) == Paints::Other, "no width");
let dash = vectorcraft_doc::Dash { pattern: vec![4.0, 4.0], offset: 0.0, align_corners: false };
assert!(Paints::of(&stroke(&|s| s.dash = Some(dash.clone())), true) == Paints::Other, "dashes");
+104
View File
@@ -620,6 +620,110 @@ fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
}
/// The paths of `art`'s faces in drawing order (a face lit by a colored light is a clip group: its
/// clipping path), leaving out the graphics (clip groups of solid-color paths).
fn face_paths(art: &Node) -> Vec<PathData> {
fn walk(n: &Node, out: &mut Vec<PathData>) {
match &n.kind {
NodeKind::Group { children, clip: true } => {
let graphic = children.get(1).is_some_and(|inner| match &inner.kind {
NodeKind::Group { children: paths, clip: false } => paths.iter().all(|p| {
p.path_data().is_some()
&& p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.paint.color().is_some()))
}),
_ => false,
});
if !graphic {
out.extend(children.first().and_then(|c| c.path_data()).cloned());
}
}
NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, out)),
_ => out.extend(n.path_data().cloned()),
}
}
let mut out = vec![];
walk(art, &mut out);
out
}
/// A turned solid in a gradient with transparent stops under a colored light, with a dashed stroke
/// and a graphic, draws its fill's and its stroke's faces in the one order it draws them in without
/// the graphic, and the graphic keeps the cap's mask and goes after the fill's cap, not the stroke's.
#[test]
fn a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
let solid = |graphics: Value| {
let mut n = object(
EXTRUDE,
json!({"rotationX": -20.0, "rotationY": -40.0, "depth": 60.0, "shade": true, "lights": [{"color": "#ff8080"}], "graphics": graphics}),
);
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient.clone()));
}
// A gradient stroke: a solid color under the colored light would be one composite.
let blues = Gradient::new(
GradientKind::Linear,
vec![GradientStop::new(0.0, Color::rgb(0.0, 0.0, 1.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 0.5))],
);
let mut stroke = StrokeLayer::new(Paint::Gradient(Box::new(GradientPaint::new(blues))), 6.0);
stroke.dash = Some(vectorcraft_doc::Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false });
n.appearance.items.push(AppearanceItem::Stroke(stroke));
solid_art_in(Some(&d), &n).unwrap()
};
let with = solid(json!([{"symbol": "Mark"}]));
let without = solid(json!([]));
assert!(face_paths(&without).len() > 20, "the faces are found");
assert_eq!(face_paths(&with), face_paths(&without), "the faces in one order");
// The graphic is drawn on the fill's cap and on the stroke's (the clip groups holding the
// symbol's red square); the fill's, whose surface carries the mask, carries it too.
let mut masked = vec![];
with.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& let [_, inner] = children.as_slice()
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
&& paths.iter().any(|p| {
p.appearance.items.iter().any(|i| match i {
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3),
AppearanceItem::Stroke(_) => false,
})
})
{
masked.push(c.extras().mask.is_some());
}
});
masked.sort_unstable();
assert_eq!(masked, [false, true], "the fill's graphic carries the cap's mask");
// The fill's graphic goes right after the fill's cap, so the dashes on the cap's edge, drawn
// after it, cover it. Drawn in order: the fill's graphic (the masked clip group), and each face,
// the fill's or the stroke's by its gradient's first stop (red or blue), with its bounds.
let mut drawn: Vec<(&str, Rect)> = vec![];
with.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& c.extras().mask.is_some()
&& let Some(bounds) = children.first().and_then(|clip| clip.path_data()).and_then(PathData::bounds)
{
drawn.push(("graphic", bounds));
}
let first_stop = c.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) => match &f.paint {
Paint::Gradient(g) => g.gradient.stops.first().map(|s| s.color.to_rgb()),
_ => None,
},
AppearanceItem::Stroke(_) => None,
});
if let (Some(rgb), Some(bounds)) = (first_stop, c.path_data().and_then(PathData::bounds)) {
drawn.push((if rgb[0] > rgb[2] { "fill" } else { "stroke" }, bounds));
}
});
let graphic = drawn.iter().position(|(kind, _)| *kind == "graphic").unwrap();
let covering = |(kind, b): &(&str, Rect)| *kind == "stroke" && b.intersect(drawn[graphic].1).area() > 0.0;
assert!(drawn[graphic..].iter().any(covering), "a dash on the cap's edge is drawn over the fill's graphic");
}
#[test]
fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() {
let d = document();
+2
View File
@@ -778,6 +778,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
+17 -13
View File
@@ -527,8 +527,9 @@ fn color_groups(cmd: &str, d: &mut Document, items: Vec<Arc<Node>>) -> Result<Ve
}
/// What a trace depends on: the object traced (an image, or an Image Trace object traced again),
/// its image, and the settings it is traced with. The tracer makes the same paths of the same
/// inputs, so a trace made away from the command ([`TraceRun`]) stands in for the command's own.
/// its image, the image's encoded bytes, and the settings it is traced with. The tracer makes the
/// same paths of the same inputs, so a trace made away from the command ([`TraceRun`]) stands in
/// for the command's own.
#[derive(Clone, Debug, PartialEq)]
struct TraceInputs {
target: NodeId,
@@ -538,6 +539,9 @@ struct TraceInputs {
/// Document Library: the library's colours, which the JSON leaves out
/// ([`tr::TraceParams::swatches`]).
swatches: Vec<[u8; 3]>,
/// The encoded image the tracer decodes: the blob under the image's key, shared with the
/// document. Two blobs are equal when they are the same allocation or hold the same bytes.
bytes: Arc<Vec<u8>>,
}
/// What `imageTrace.make` and `imageTrace.makeAndExpand` take from the session before they trace.
@@ -549,7 +553,6 @@ struct Prepared {
params_json: Value,
preset_label: String,
library: Vec<([u8; 3], Paint)>,
bytes: Arc<Vec<u8>>,
}
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
@@ -597,8 +600,8 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
let bytes = Arc::clone(&blob.bytes);
let library = trace_library(c, s, &mut params)?;
let traced_with = serde_json::to_value(&params).map_err(|e| EngineError::Other(e.to_string()))?;
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone() };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library, bytes })
let inputs = TraceInputs { target, image, params: traced_with, swatches: params.swatches.clone(), bytes };
Ok(Prepared { inputs, trace: params, view, params_json, preset_label, library })
}
/// What a trace made of an image: the size in pixels it was decoded at, and the paths.
@@ -616,11 +619,11 @@ impl Traced {
}
}
/// Decode the image `bytes` and trace it with `params`, telling `steps` how far it has got
/// ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, bytes: &[u8], steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
/// Decode the image bytes of `inputs` and trace them with `params`, telling `steps` how far it has
/// got ([`tr::trace_watched`]); [`EngineError::Cancelled`] once `steps` answers `false`.
fn trace_now(inputs: &TraceInputs, params: &tr::TraceParams, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
// An image over the tracer's size is traced scaled down (the paths are scaled back).
let raster = tr::Raster::decode_to_fit(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
let raster = tr::Raster::decode_to_fit(&inputs.bytes).map_err(|e| EngineError::Other(e.to_string()))?;
if !steps(0, 0) {
return Err(EngineError::Cancelled);
}
@@ -682,7 +685,8 @@ impl TraceRun {
(self.prepared.inputs.image.width, self.prepared.inputs.image.height)
}
/// Does it still apply: would the command trace the same object, image and settings now?
/// Does it still apply: would the command trace the same object, image, pixels and settings
/// now?
pub fn current(&self, s: &Session) -> bool {
prepare(s, self.command, &self.params).is_ok_and(|now| now.inputs == self.prepared.inputs)
}
@@ -691,13 +695,13 @@ impl TraceRun {
/// failed or stopped ([`EngineError::Cancelled`] once `steps` answers `false`). It touches no
/// document, so it can run on any thread.
pub fn run(&self, steps: &(dyn Fn(u64, u64) -> bool + Sync)) -> Result<Traced> {
trace_now(&self.prepared.inputs, &self.prepared.trace, &self.prepared.bytes, steps)
trace_now(&self.prepared.inputs, &self.prepared.trace, steps)
}
}
pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Value> {
let c = if expand { "imageTrace.makeAndExpand" } else { "imageTrace.make" };
let Prepared { inputs, trace, view, params_json, preset_label, library, bytes } = prepare(s, c, p)?;
let Prepared { inputs, trace, view, params_json, preset_label, library } = prepare(s, c, p)?;
let group_by_color = expand && by_color_param(c, p)?;
// A saved preset's settings join the journal entry, so a replay traces as this run did after
// the preset is changed, renamed or deleted.
@@ -709,7 +713,7 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
// A trace handed in for these very inputs ([`TraceRun`]), else one made now.
let Traced { raster, res, .. } = match s.trace_hand_off.take() {
Some(traced) if traced.inputs == inputs => traced,
_ => trace_now(&inputs, &trace, &bytes, &|_, _| true)?,
_ => trace_now(&inputs, &trace, &|_, _| true)?,
};
let TraceInputs { target, image: img, .. } = inputs;
let mut warnings = keep_warnings(&trace, &res);
+1 -1
View File
@@ -52,7 +52,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
];
/// The object counts of `document.info` and their labels.
const OBJECT_LABELS: [(&str, &str); 19] = [
pub const OBJECT_LABELS: [(&str, &str); 19] = [
("paths", "Paths"),
("compoundPaths", "Compound Paths"),
("groups", "Groups"),
+21 -4
View File
@@ -78,8 +78,11 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
/// several artboards selected, pastes on those. A step that resizes the active artboard
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
/// several artboards selected, pastes on those. A Fit to Artwork Bounds step that names neither
/// `index` nor `indices`, while the Artboard tool is chosen with several artboards selected when the
/// step runs, gets those as its `indices`, which its journal entry records. Otherwise a step that
/// resizes the active artboard ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` (nor
/// `indices`, for Fit to Artwork Bounds) gets that artboard as its `index`.
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
fn run_steps(
s: &mut Session,
@@ -110,9 +113,22 @@ fn run_steps(
// Artboard tool is chosen with several artboards selected, pastes on those.
let names_artboards = id.starts_with("edit.pasteIn")
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard
// tool is chosen with several artboards selected, fits those, as the command does on its own.
let fit_picks = if id == "artboard.fitToArt" && params.get("index").is_none() && params.get("indices").is_none() {
crate::cmd::edit::artboard_tool_picks(s)
} else {
Vec::new()
};
if !fit_picks.is_empty()
&& let Some(o) = params.as_object_mut()
{
o.insert("indices".into(), json!(fit_picks));
}
if let Some(a) = artboard
&& let Some(key) = key
&& params.get(key).is_none()
&& !(id == "artboard.fitToArt" && params.get("indices").is_some())
&& !names_artboards
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
&& let Some(o) = params.as_object_mut()
@@ -129,8 +145,9 @@ fn run_steps(
}
grouped.push(step_groups(s, start, &held));
// The step's journal entry records what it took from the preferences or the clock (a
// save's date, a new document's), as a command of its own would.
if noted != params
// save's date, a new document's), as a command of its own would, and the artboards a Fit to
// Artwork Bounds step took from the Artboard tool.
if (noted != params || !fit_picks.is_empty())
&& let Some(c) = c.as_object_mut()
{
c.insert("params".into(), noted);
+1 -1
View File
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch",
[],
None,
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
"{label?, commands: [{command, params}], artboard?: index (the active artboard; the app passes it: each edit.pasteInPlace, edit.pasteInFront, edit.pasteInBack, object.align, object.distribute, object.distributeSpacing, select.allOnArtboard or symbol.edit step that names none gets it, and each artboard.fitToArt or artboard.fitToSelection step that names no index gets it as index, or the last artboard of a document with fewer; an artboard.fitToArt step that names neither index nor indices, while the Artboard tool is chosen with several artboards selected when the step runs, gets those as indices instead, and the journal records them)} run several commands as ONE undo step (one in each document they edit: steps may open, switch, close or revert documents); stops at the first error and rolls everything back, documents included",
has_doc,
batch::batch
),
+207 -8
View File
@@ -481,6 +481,12 @@ fn join_point(sp: &mut SubPath, ai: usize, smooth: bool) {
}
}
#[cfg(test)]
thread_local! {
/// Anchors that [`merge_coincident`] moved to a lower index of their vector on this thread.
static ANCHOR_MOVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Merge each run of `picked` neighbours of `sp` that lie on one another into one anchor, which
/// keeps the first one's incoming handle and the last one's outgoing handle. Returns how many
/// anchors went.
@@ -501,23 +507,68 @@ fn merge_coincident(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind:
join_point(sp, 0, smooth);
}
}
// Back to front, so the indices `picked` knows stay true for the anchors still to visit.
for i in (1..sp.anchors.len()).rev() {
// Back to front, so the indices `picked` knows stay true for the anchors still to visit. A
// merged anchor is only marked here; the marked anchors are removed in one pass at the end.
let closed = sp.closed;
let anchors = &mut sp.anchors;
let len = anchors.len();
let mut gone = vec![false; len];
// The anchor after `i` that is still on the path, and the last one still on it.
let mut next = None;
let mut last = len.saturating_sub(1);
for i in (1..len).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
&& let Some([a, b]) = anchors.get_mut(i - 1..=i)
&& same(a, b)
{
a.h_out = b.h_out;
sp.anchors.remove(i);
if let Some(smooth) = join_kind {
join_point(sp, i - 1, smooth);
if let Some(slot) = gone.get_mut(i) {
*slot = true;
}
if next.is_none() {
last = i - 1;
}
if let Some(smooth) = join_kind {
// The neighbors the anchor has on the path as it now stands, as `join_point` sees them.
let prev = if i > 1 { Some(i - 2) } else { closed.then_some(last) };
let after = next.or(closed.then_some(0));
join_point_between(anchors, i - 1, prev, after, smooth);
}
} else {
next = Some(i);
}
}
#[cfg(test)]
if let Some(first) = gone.iter().position(|&g| g) {
// `retain` moves each anchor it keeps after the first one it drops.
let dropped = gone.iter().filter(|&&g| g).count();
ANCHOR_MOVES.set(ANCHOR_MOVES.get() + (len - first - dropped));
}
if gone.contains(&true) {
let mut k = 0;
anchors.retain(|_| {
let keep = !gone.get(k).copied().unwrap_or(false);
k += 1;
keep
});
}
before - sp.anchors.len()
}
/// [`join_point`] on anchor `ai` of `anchors` with its neighbors given by index.
fn join_point_between(anchors: &mut [Anchor], ai: usize, prev: Option<usize>, next: Option<usize>, smooth: bool) {
let at = |j: Option<usize>| j.and_then(|j| anchors.get(j)).map(|a| a.p);
let (prev, next) = (at(prev), at(next));
if let Some(a) = anchors.get_mut(ai) {
if smooth {
a.smooth_between(prev, next);
} else {
a.retract();
}
}
}
/// Close subpath `si` of path `id`, merging coincident endpoints if present.
fn close_subpath_in_node(d: &mut Document, id: NodeId, si: usize, join_kind: Option<bool>) -> Result<()> {
let path = path_mut(d, id)?;
@@ -751,8 +802,19 @@ pub(super) fn join(s: &mut Session, p: &Value) -> Result<Value> {
let mut merged = vec![];
for (id, picked) in &st.selection.anchors {
let Some(mut path) = st.doc.node(*id).and_then(|n| n.path_data()).cloned() else { continue };
let n: usize =
path.subpaths.iter_mut().enumerate().map(|(si, sp)| merge_coincident(sp, |ai| picked.contains(&(si, ai)), join_kind)).sum();
// One flag per anchor; references past the end of a subpath or to a missing one pick nothing.
let mut masks: Vec<Vec<bool>> = path.subpaths.iter().map(|sp| vec![false; sp.anchors.len()]).collect();
for &(si, ai) in picked {
if let Some(flag) = masks.get_mut(si).and_then(|m| m.get_mut(ai)) {
*flag = true;
}
}
let n: usize = path
.subpaths
.iter_mut()
.zip(&masks)
.map(|(sp, mask)| merge_coincident(sp, |ai| mask.get(ai).copied().unwrap_or(false), join_kind))
.sum();
if n > 0 {
merged.push((*id, path));
}
@@ -1769,3 +1831,140 @@ fn cut_at_anchors(s: &mut Session, _: &Value) -> Result<Value> {
})?;
Ok(super::draw2::ids_json(&ids))
}
#[cfg(test)]
mod tests {
use super::*;
/// `merge_coincident` removing each merged anchor from the vector straight away, kept as the
/// reference the one-pass version must match.
fn merge_coincident_by_removal(sp: &mut SubPath, picked: impl Fn(usize) -> bool, join_kind: Option<bool>) -> usize {
let same = |a: &Anchor, b: &Anchor| a.p.distance(b.p) < 1e-6;
let before = sp.anchors.len();
if sp.closed
&& before > 2
&& picked(0)
&& picked(before - 1)
&& let [first, .., last] = sp.anchors.as_mut_slice()
&& same(first, last)
{
first.h_in = last.h_in;
sp.anchors.pop();
if let Some(smooth) = join_kind {
join_point(sp, 0, smooth);
}
}
for i in (1..sp.anchors.len()).rev() {
if picked(i - 1)
&& picked(i)
&& let Some([a, b]) = sp.anchors.get_mut(i - 1..=i)
&& same(a, b)
{
a.h_out = b.h_out;
sp.anchors.remove(i);
if let Some(smooth) = join_kind {
join_point(sp, i - 1, smooth);
}
}
}
before - sp.anchors.len()
}
/// Every field of every anchor, bit for bit.
fn bits(sp: &SubPath) -> (Vec<[u64; 6]>, Vec<AnchorKind>, bool) {
let b = |p: Point| [p.x.to_bits(), p.y.to_bits()];
let fields = sp.anchors.iter().map(|a| [b(a.p), b(a.h_in), b(a.h_out)].concat().try_into().unwrap()).collect();
(fields, sp.anchors.iter().map(|a| a.kind).collect(), sp.closed)
}
/// A small linear congruential generator, so the cases are the same on every run.
struct Lcg(u64);
impl Lcg {
fn below(&mut self, n: u64) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(self.0 >> 33) % n
}
}
fn same_as_removal(sp: &SubPath, picked: &dyn Fn(usize) -> bool, join_kind: Option<bool>) {
let (mut ours, mut theirs) = (sp.clone(), sp.clone());
let n = merge_coincident(&mut ours, picked, join_kind);
let m = merge_coincident_by_removal(&mut theirs, picked, join_kind);
assert_eq!(n, m, "{sp:?} {join_kind:?}");
assert_eq!(bits(&ours), bits(&theirs), "{sp:?} {join_kind:?}");
}
/// Short paths with points on, near and just past the merge distance, selections with stale
/// indices, every anchor kind and every join kind give the same anchors, bit for bit, as
/// removing each merged anchor straight away.
#[test]
fn merging_coincident_anchors_matches_removing_them_one_by_one() {
let spots = [(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (5e-7, 0.0), (0.0, 1.5e-6), (10.0, 0.0), (5.0, 5.0), (10.0, 0.0)];
let mut rng = Lcg(7);
for _ in 0..30_000 {
let n = rng.below(9) as usize;
let anchors = (0..n)
.map(|_| {
let (x, y) = spots[rng.below(spots.len() as u64) as usize];
let p = Point::new(x, y);
let handle = |rng: &mut Lcg| match rng.below(3) {
0 => p,
_ => p + Vec2::new(rng.below(7) as f64 - 3.0, rng.below(7) as f64 - 3.0),
};
let (h_in, h_out) = (handle(&mut rng), handle(&mut rng));
let kind = if rng.below(2) == 0 { AnchorKind::Corner } else { AnchorKind::Smooth };
Anchor { p, h_in, h_out, kind }
})
.collect();
let sp = SubPath::new(anchors, rng.below(2) == 0);
let picks: Vec<bool> = (0..n + 2).map(|_| rng.below(4) != 0).collect();
let join_kind = [None, Some(false), Some(true)][rng.below(3) as usize];
same_as_removal(&sp, &|i| picks.get(i).copied().unwrap_or(false), join_kind);
}
}
/// A smooth join of three anchors on one another takes the outgoing handle the middle anchor
/// was given when it joined the right one: an already smooth left anchor keeps that handle.
#[test]
fn a_smooth_join_of_three_anchors_keeps_the_handle_the_middle_one_got() {
let o = Point::ZERO;
let left = Anchor { p: o, h_in: Point::new(-2.0, 0.0), h_out: o, kind: AnchorKind::Smooth };
let right = Anchor { p: o, h_in: o, h_out: Point::new(0.0, 5.0), kind: AnchorKind::Corner };
let mut sp = SubPath::new(vec![left, Anchor::corner(o), right, Anchor::corner(Point::new(10.0, 0.0))], false);
assert_eq!(merge_coincident(&mut sp, |i| i < 3, Some(true)), 2);
let a = sp.anchors[0];
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(-2.0, 0.0), Point::new(10.0 / 3.0, 0.0), AnchorKind::Smooth));
assert_eq!(sp.anchors.len(), 2);
}
/// One long run of selected anchors on one another, open or closed, becomes one anchor.
#[test]
fn a_long_run_of_anchors_on_one_another_becomes_one() {
for closed in [false, true] {
for join_kind in [None, Some(false), Some(true)] {
let anchors = (0..50_000).map(|i| Anchor::smooth(Point::ZERO, Point::new(1.0, i as f64))).collect();
let sp = SubPath::new(anchors, closed);
same_as_removal(&sp, &|_| true, join_kind);
let mut ours = sp.clone();
assert_eq!(merge_coincident(&mut ours, |_| true, join_kind), 49_999);
assert_eq!((ours.anchors.len(), ours.closed), (1, closed));
}
}
}
/// A long selected run at the start of a path followed by as many anchors that stay: each
/// anchor after the run moves once, not once per merged anchor.
#[test]
fn a_long_run_before_many_other_anchors_merges_in_one_pass() {
let run = 300_000;
let anchors = (0..run).map(|_| Anchor::corner(Point::ZERO)).chain((1..=run).map(|i| Anchor::corner(Point::new(i as f64, 1.0)))).collect();
let mut sp = SubPath::new(anchors, false);
ANCHOR_MOVES.set(0);
assert_eq!(merge_coincident(&mut sp, |i| i < run, Some(false)), run - 1);
assert_eq!(ANCHOR_MOVES.get(), run);
assert_eq!(sp.anchors.len(), run + 1);
assert_eq!(sp.anchors[0].p, Point::ZERO);
assert_eq!(sp.anchors[1].p, Point::new(1.0, 1.0));
assert_eq!(sp.anchors[run].p, Point::new(run as f64, 1.0));
}
}
+3 -1
View File
@@ -19,7 +19,9 @@ pub const ON_ACTIVE_ARTBOARD: [&str; 8] = [
/// The commands that resize the artboards the app passes (Object › Artboards): the app passes the
/// selected artboards to Fit to Artwork Bounds as its `indices`, and the active artboard to Fit to
/// Selected Art as its `index`. A `command.batch` given `artboard` passes it on, as `index`, to
/// each of their steps that names none.
/// each of their steps that names none; a Fit to Artwork Bounds step that names neither `index` nor
/// `indices`, while the Artboard tool is chosen with several artboards selected, gets those as its
/// `indices` instead.
pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitToSelection"];
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
+97
View File
@@ -3788,6 +3788,103 @@ fn a_trace_run_needs_the_library_colours_it_traced_with() {
assert!(!run.current(&s), "{name} changed");
}
/// `image_doc`'s image with its disc 20 px to the left: the same size, other pixels.
fn moved_disc_png() -> Vec<u8> {
vectorcraft_trace::Raster::from_fn(100, 100, |x, y| {
let (dx, dy) = (x as f64 + 0.5 - 30.0, y as f64 + 0.5 - 50.0);
if dx * dx + dy * dy <= 900.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }
})
.encode_png()
}
/// Puts `bytes` under the image key `key`, or takes the key's image data away (`None`).
fn set_image_data(s: &mut Session, key: &str, bytes: Option<Vec<u8>>) {
s.edit("image data", |d, _| {
match bytes {
Some(b) => d.images.insert(key.into(), ImageBlob::new("image/png", b)),
None => d.images.remove(key),
};
Ok(())
})
.unwrap();
}
/// The middle of the first traced path of the Image Trace object the reply `r` names, in x.
fn traced_center_x(s: &Session, r: &Value) -> f64 {
outline(&traced_paths(&node(s, NodeId(r["id"].as_u64().unwrap())))[0]).0.bounds().unwrap().center().x
}
/// A trace made away from its command no longer applies once the pixels under its image's key
/// change, though the object, its image record and the settings stay as they were; both commands
/// then trace the pixels there now. The same bytes in another allocation still apply.
#[test]
fn a_trace_run_needs_the_pixels_it_traced() {
let p = json!({"params": {"ignoreWhite": true}});
for command in ["imageTrace.make", "imageTrace.makeAndExpand"] {
let mut s = session();
image_doc(&mut s);
let run = cmd::TraceRun::prepare(&s, command, &p).unwrap();
let traced = run.run(&|_, _| true).unwrap();
// The same bytes, allocated anew: still current.
let same = s.doc().unwrap().doc.images["img1"].bytes.to_vec();
set_image_data(&mut s, "img1", Some(same));
assert!(run.current(&s), "{command}: equal bytes");
// Other pixels under the same key: no longer current, and the hand-off is dropped.
set_image_data(&mut s, "img1", Some(moved_disc_png()));
assert!(!run.current(&s), "{command}: other pixels");
traced.hand_in(&mut s);
let r = s.execute(command, run.params()).unwrap();
assert!(s.trace_hand_off.is_none(), "{command}: dropped");
// The disc is now at image x 30, which the ×2 placement at 50 puts at 110.
let x = traced_center_x(&s, &r);
assert!((x - 110.0).abs() < 1.5, "{command}: traced the pixels there now, at {x}");
}
}
/// Image data that is missing or empty: a run made before it went no longer applies, the run's
/// command gives the error it gives without a run, and nothing panics.
#[test]
fn a_trace_run_of_missing_or_empty_image_data() {
let p = json!({"params": {"ignoreWhite": true}});
let mut s = session();
image_doc(&mut s);
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
let traced = run.run(&|_, _| true).unwrap();
set_image_data(&mut s, "img1", None);
assert!(!run.current(&s), "missing");
traced.hand_in(&mut s);
let e = s.execute(run.command(), run.params()).unwrap_err().to_string();
assert!(e.contains("image data `img1` is missing"), "{e}");
set_image_data(&mut s, "img1", Some(vec![]));
assert!(!run.current(&s), "empty");
let empty = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
assert!(empty.current(&s), "two empty blobs are equal");
assert!(matches!(empty.run(&|_, _| true), Err(EngineError::Other(_))));
assert!(matches!(s.execute(run.command(), run.params()), Err(EngineError::Other(_))));
}
/// Tracing an Image Trace object again follows the same rule: once the pixels of the image it
/// holds change, a run made before no longer applies, and the command traces the pixels there now.
#[test]
fn a_trace_run_of_an_image_trace_object_needs_its_pixels() {
let p = json!({"params": {"ignoreWhite": true}});
let mut s = session();
image_doc(&mut s);
let g = s.execute("imageTrace.make", &p).unwrap()["id"].as_u64().unwrap();
let again = json!({"id": g, "params": {"ignoreWhite": true}});
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &again).unwrap();
assert_eq!(run.target(), NodeId(g));
let traced = run.run(&|_, _| true).unwrap();
assert!(run.current(&s));
set_image_data(&mut s, "img1", Some(moved_disc_png()));
assert!(!run.current(&s));
traced.hand_in(&mut s);
let r = s.execute(run.command(), run.params()).unwrap();
assert!(s.trace_hand_off.is_none(), "dropped");
let x = traced_center_x(&s, &r);
assert!((x - 110.0).abs() < 1.5, "traced the pixels there now, at {x}");
}
/// Shapes: the disc of the test image comes out as a live ellipse where the image lies, the same
/// circle as its traced path; without the option it is a plain path.
#[test]
+31
View File
@@ -1393,6 +1393,37 @@ fn smooth_region_refits_at_the_tolerance_sent_at_any_zoom() {
}
}
/// A drag of the Smooth tool along a line jagged by up to 6 pt leaves no corner between a curve and
/// a line: every anchor between the path's ends turns by at most 1°.
#[test]
fn smooth_tool_leaves_no_corner_where_a_curve_meets_a_line() {
let mut s = session();
let mut seed = 7u64;
let anchors: Vec<_> = (0..=60)
.map(|i| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let noise = ((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0;
json!({"x": 100.0 + f64::from(i) * 5.0, "y": 200.0 + 6.0 * noise})
})
.collect();
let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
let drag_points: Vec<(f64, f64)> = (0..=64).map(|i| (90.0 + f64::from(i) * 5.0, 200.0)).collect();
drag(&mut s, "smooth", &drag_points, Mods::default());
let p = path(&s, id);
let sp = &p.subpaths[0];
assert!(sp.anchors.len() < 61, "the path is smoothed: {}", sp.anchors.len());
let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord);
for i in 1..sp.segment_count() {
let (prev, next) = (sp.segment(i - 1), sp.segment(i));
let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0);
let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0);
let turn = arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees();
let kinds = (sp.segment_is_line(i - 1), sp.segment_is_line(i));
assert!(turn <= 1.0, "anchor {i} turns {turn}° (lines before and after: {kinds:?}): {:?}", sp.anchors[i]);
}
}
/// Smoothing a path with direct-selected anchors leaves the path selected whole: the selection no
/// longer names anchors by indices into the anchors the smooth replaced. A selected path the drag
/// does not reach keeps its anchors selected, and undo brings the old selection back.
+81
View File
@@ -192,6 +192,87 @@ fn fit_steps_take_the_batchs_artboard_and_actions_leave_out_their_index() {
assert_eq!(action, [fit("artboard.fitToArt"), fit("artboard.fitToArt"), fit("artboard.fitToSelection")]);
}
/// A document of three artboards with art of its own on each → its artboards before any fit.
fn three_artboards_with_art(s: &mut Session) -> Vec<vectorcraft_geom::Rect> {
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3, "created": null})).unwrap();
for (x, h) in [(10, 30), (130, 20), (250, 40)] {
s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap();
}
s.execute("select.all", &json!({})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect()
}
/// The artboards of [`three_artboards_with_art`], each fitted to its art.
fn three_fitted_artboards() -> [vectorcraft_geom::Rect; 3] {
let rect = vectorcraft_geom::Rect::new;
[rect(10.0, 10.0, 30.0, 40.0), rect(130.0, 10.0, 150.0, 30.0), rect(250.0, 10.0, 270.0, 50.0)]
}
/// A Fit to Artwork Bounds step that names neither `index` nor `indices`, while the Artboard tool
/// is chosen with several artboards selected, fits each of those (not the batch's artboard), as the
/// command does on its own; a step's own `index` or `indices` wins, and with one artboard or none
/// selected the step takes the batch's artboard.
#[test]
fn a_batch_fit_step_uses_the_artboard_tool_selection() {
let fitted = three_fitted_artboards();
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let fit = |params: Value| json!({"artboard": 1, "commands": [{"command": "artboard.fitToArt", "params": params}]});
let session = |picks: &Value| {
let mut s = Session::new();
let was = three_artboards_with_art(&mut s);
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", picks);
(s, was)
};
let (mut s, was) = session(&json!([2, 0]));
s.execute("command.batch", &fit(json!({}))).unwrap();
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]], "artboards 1 and 3, the selected ones, and not the batch's artboard 2");
let (mut s, was) = session(&json!([2, 0]));
s.execute("command.batch", &fit(json!({"index": 1}))).unwrap();
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "a step's own index");
let (mut s, was) = session(&json!([2, 0]));
s.execute("command.batch", &fit(json!({"indices": [1, 2]}))).unwrap();
assert_eq!(boards(&s), [was[0], fitted[1], fitted[2]], "a step's own indices");
for picks in [json!([2]), json!([])] {
let (mut s, was) = session(&picks);
s.execute("command.batch", &fit(json!({}))).unwrap();
assert_eq!(boards(&s), [was[0], fitted[1], was[2]], "the batch's artboard with {picks} selected");
}
}
/// The journal records the artboards a batch's Fit to Artwork Bounds step took from the Artboard
/// tool, so a replay in a new session fits the same ones; an action leaves them out and fits the
/// artboards selected when it plays.
#[test]
fn a_batch_fit_selection_replays_but_an_action_uses_the_current_selection() {
let fitted = three_fitted_artboards();
let boards = |s: &Session| s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let mut s = Session::new();
let was = three_artboards_with_art(&mut s);
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([0, 2]));
let start = s.journal.len();
let steps = json!([{"command": "artboard.fitToArt", "params": {}}]);
s.execute("command.batch", &json!({"artboard": 1, "commands": steps})).unwrap();
assert_eq!(boards(&s), [fitted[0], was[1], fitted[2]]);
let (id, p) = s.journal.last().unwrap().clone();
assert_eq!((id.as_str(), &p["commands"][0]["params"]), ("command.batch", &json!({"indices": [0, 2]})));
let r = replayed(&s);
assert_ne!(r.tool_id(), "artboard", "the new session's tool selects no artboards");
assert_eq!(boards(&r), boards(&s), "the replay fits the recorded artboards");
let action = s.journal_for_action(start);
assert_eq!(action, [("command.batch".to_string(), json!({"commands": steps}))]);
// Played on a fresh copy of the document with other artboards selected.
let mut a = Session::new();
three_artboards_with_art(&mut a);
a.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
a.set_tool_option("selected", &json!([1, 2]));
a.execute("command.batch", &json!({"artboard": 0, "commands": action[0].1["commands"]})).unwrap();
assert_eq!(boards(&a), [was[0], fitted[1], fitted[2]], "the action fits the artboards selected when it plays");
}
#[test]
fn a_save_records_its_date_and_replays_it() {
let path = vectorcraft_testkit::temp_dir("journal-save").join("a.vectorcraft").to_string_lossy().into_owned();
+3
View File
@@ -753,6 +753,9 @@ fn precise_cursors_replace_every_pen_state() {
Cursor::ShapeBuilderErase,
Cursor::AnchorPoint,
Cursor::Curvature,
Cursor::LivePaintBucket,
Cursor::LivePaintBucketFace,
Cursor::LivePaintBucketEdge,
] {
assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}");
}
+21 -15
View File
@@ -165,6 +165,26 @@ impl Anchor {
pub fn reversed(&self) -> Self {
Self { p: self.p, h_in: self.h_out, h_out: self.h_in, kind: self.kind }
}
/// Make the anchor smooth between the points `prev` and `next` (its own point for a missing
/// one): handles in line with them, each a third of the way to that side's point. A smooth
/// anchor with both handles keeps them. False, with no change, when the two points give no
/// direction. [`SubPath::smooth_anchor`] calls it with the anchor's neighbors.
pub fn smooth_between(&mut self, prev: Option<Point>, next: Option<Point>) -> bool {
if self.kind == AnchorKind::Smooth && self.has_in() && self.has_out() {
return true;
}
let (pp, nn) = (prev.unwrap_or(self.p), next.unwrap_or(self.p));
let dir = nn - pp;
let l = dir.hypot();
if l <= 1e-9 {
return false;
}
let u = dir / l;
self.h_in = self.p - u * (self.p.distance(pp) / 3.0);
self.h_out = self.p + u * (self.p.distance(nn) / 3.0);
self.kind = AnchorKind::Smooth;
true
}
/// Remove both handles (convert to a sharp corner).
pub fn retract(&mut self) {
self.h_in = self.p;
@@ -398,21 +418,7 @@ impl SubPath {
};
let at = |j: Option<usize>| j.and_then(|j| self.anchors.get(j)).map(|a| a.p);
let (prev, next) = (at(prev), at(next));
let Some(a) = self.anchors.get_mut(i) else { return false };
if a.kind == AnchorKind::Smooth && a.has_in() && a.has_out() {
return true;
}
let (pp, nn) = (prev.unwrap_or(a.p), next.unwrap_or(a.p));
let dir = nn - pp;
let l = dir.hypot();
if l <= 1e-9 {
return false;
}
let u = dir / l;
a.h_in = a.p - u * (a.p.distance(pp) / 3.0);
a.h_out = a.p + u * (a.p.distance(nn) / 3.0);
a.kind = AnchorKind::Smooth;
true
self.anchors.get_mut(i).is_some_and(|a| a.smooth_between(prev, next))
}
/// Cut at the anchors `at`: each becomes the end of one open piece and the start of the next,
/// its handle off each piece retracted (the shape doesn't change). A closed subpath opens at
+18 -1
View File
@@ -563,7 +563,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{name: string} delete the toolbar made with New Toolbar called `name`, and the groups torn off it, from the current workspace, as Manage Toolbars' trash can does",
),
("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"),
(
"window.toolbar.dock",
"Dock Toolbar",
"",
"{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}",
),
(
"window.toolbar.float",
"Float Toolbar",
"",
"{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}",
),
(
"window.toolbar.list",
"List Toolbars",
"",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)",
),
("window.taskBar", "Contextual Task Bar", "", "{}"),
(
"window.pathfinder.compoundShapes",
+28 -3
View File
@@ -348,14 +348,39 @@ fn refit_part(part: &[(&Seg, usize)], opts: &SimplifyOptions, tol: f64, mut ends
}
// The fit may be `tol * 0.98` from the lines between the samples, those lines may be
// `SAMPLE_GAP` of `tol` from the path, and the curve the test below turns into a line moves by up
// to 1.5% of `tol`: 3/4 of how far its handles may be from the line.
// to 1.5% of `tol`: 3/4 of how far its handles may be from the line. The fitted curves join
// smoothly, so a curve becomes a line only when the line keeps both of its joins smooth. The last
// curve of a loop fitted across its start leaves along the loop's first segment.
let (t0, t1) = ends.map_or((start_tangent(&first.c), end_tangent(&last.c)), |d| (d, d));
for c in fit_cubics(&pts, t0, t1, tol * 0.98) {
let line = is_straight(&c, tol * 0.02);
let fitted = fit_cubics(&pts, t0, t1, tol * 0.98);
let from = result.len();
let mut arrive = t0;
for (k, &c) in fitted.iter().enumerate() {
let leave = match fitted.get(k + 1) {
Some(next) => start_tangent(next),
None if ends.is_some() => result.get(from).map_or(t1, |s| start_tangent(&s.c)),
None => t1,
};
let line = is_straight(&c, tol * 0.02) && line_keeps_joins(&c, arrive, leave);
arrive = if line { unit(c.p3 - c.p0).unwrap_or(arrive) } else { end_tangent(&c) };
result.push(if line { Seg::line(c.p0, c.p3) } else { Seg { c, line } });
}
}
/// Most degrees between the line from a refitted curve's start to its end and the directions the
/// path arrives and leaves along, for the curve to become that line: so every join next to such a
/// line turns by at most this much. VectorCraft's own value.
const LINE_JOIN_DEG: f64 = 0.5;
/// Whether the line from `c.p0` to `c.p3` is within [`LINE_JOIN_DEG`] of `arrive`, the direction the
/// path arrives at `c.p0` along, and of `leave`, the direction it leaves `c.p3` along. A curve whose
/// ends are at one point, or a direction of no length, gives `false`.
fn line_keeps_joins(c: &CubicBez, arrive: Vec2, leave: Vec2) -> bool {
let (Some(dir), Some(arrive), Some(leave)) = (unit(c.p3 - c.p0), unit(arrive), unit(leave)) else { return false };
let min = LINE_JOIN_DEG.to_radians().cos();
dir.dot(arrive) >= min && dir.dot(leave) >= min
}
/// `pts` (a run's samples, in order) smoothed along the path: each point becomes the Gaussian-weighted
/// mean of the points around it, `sigma` points of arc length wide, the window narrowing towards the
/// ends so that the first and last points stay where they are. Consecutive samples within
+71
View File
@@ -417,6 +417,77 @@ fn simplify_keeps_square_corners() {
assert!(!has_curves(&s));
}
/// The largest turn, in degrees, at an anchor of `sp` that is not an end of an open subpath: the
/// angle between the direction a segment arrives along and the one the next leaves along.
fn largest_join_turn(sp: &SubPath) -> f64 {
let dir = |v: kurbo::Vec2, w: kurbo::Vec2, chord: kurbo::Vec2| [v, w, chord].into_iter().find(|d| d.hypot() > 1e-9).unwrap_or(chord);
let n = sp.segment_count();
let first = usize::from(!sp.closed);
(first..n)
.map(|i| {
let (prev, next) = (sp.segment((i + n - 1) % n), sp.segment(i));
let arrive = dir(prev.p3 - prev.p2, prev.p3 - prev.p1, prev.p3 - prev.p0);
let leave = dir(next.p1 - next.p0, next.p2 - next.p0, next.p3 - next.p0);
arrive.cross(leave).atan2(arrive.dot(leave)).abs().to_degrees()
})
.fold(0.0, f64::max)
}
/// A refitted curve becomes a line only when the line keeps the smooth joins on both sides of it:
/// with no corners kept, the refit of a jagged line or of an arc running into a line turns by at most
/// 0.5° at every anchor. Points that all lie on one line still become one line.
#[test]
fn simplify_turns_a_curve_into_a_line_only_where_the_joins_stay_smooth() {
let mut seed = 7u64;
let mut noise = || {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
((seed >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
};
let jagged: Vec<Point> = (0..=60).map(|i| Point::new(100.0 + f64::from(i) * 5.0, 200.0 + 6.0 * noise())).collect();
let mut arc_into_line: Vec<Point> =
(0..=40).map(|i| Point::new(50.0 * (f64::from(i) / 80.0 * PI).cos(), 50.0 * (f64::from(i) / 80.0 * PI).sin())).collect();
arc_into_line.extend((1..=20).map(|i| Point::new(-f64::from(i) * 2.0, 50.0)));
for pts in [&jagged, &arc_into_line] {
let path = PathData::single(SubPath::polyline(pts, false));
for tolerance in [1.0, 2.5, 5.0] {
let s = simplify_with(&path, &SimplifyOptions { tolerance, corner_angle_deg: 179.0, ..Default::default() });
let turn = largest_join_turn(&s.subpaths[0]);
assert!(turn <= 0.5 + 1e-9, "{tolerance} pt: an anchor turns {turn}°: {s:?}");
assert!(max_deviation(&path, &s) <= tolerance + 1e-6, "{tolerance} pt: {}", max_deviation(&path, &s));
}
}
let in_line: Vec<Point> = [0.0, 3.0, 10.0, 11.0, 40.0, 41.5, 90.0, 100.0].map(|x| Point::new(x, 0.5 * x)).to_vec();
let s = simplify_with(&PathData::single(SubPath::polyline(&in_line, false)), &SimplifyOptions { tolerance: 1.0, ..Default::default() });
assert_eq!(s.anchor_count(), 2, "{s:?}");
assert!(!has_curves(&s), "{s:?}");
}
/// A smoothed loop with no corner is fitted across its start, and the join there also turns by at
/// most 0.5°. Each loop is a flat side that bends by 0.6° at the loop's start, closed by an arc of
/// `n` lines `height` tall, with `inner` anchors along each half of the side.
#[test]
fn simplify_keeps_the_join_at_the_start_of_a_smoothed_loop_smooth() {
for (half, height, n, inner, tolerance, smooth) in
[(40.0, 20.0, 8, 3, 2.5, 2.0), (80.0, 60.0, 8, 3, 5.0, 0.5), (160.0, 200.0, 24, 3, 10.0, 2.0), (160.0, 20.0, 24, 8, 10.0, 5.0)]
{
let rise = half * 0.3f64.to_radians().tan();
let along = |i: i32| Point::new(half * f64::from(i) / f64::from(inner), -rise * f64::from(i.abs()) / f64::from(inner));
let mut pts: Vec<Point> = (0..=inner).map(along).collect();
pts.extend((1..n).map(|i| {
let a = f64::from(i) / f64::from(n) * PI;
Point::new(half * a.cos(), -rise - height * a.sin())
}));
pts.extend((-inner..0).map(along));
let path = PathData::single(SubPath::polyline(&pts, true));
let s = simplify_with(&path, &SimplifyOptions { tolerance, corner_angle_deg: 179.0, smooth, ..Default::default() });
let sp = &s.subpaths[0];
assert!(sp.closed && sp.anchors.len() < pts.len(), "{tolerance} pt: {s:?}");
assert!(sp.segment_is_line(0), "{tolerance} pt: the first segment is a curve: {s:?}");
let turn = largest_join_turn(sp);
assert!(turn <= 0.5 + 1e-9, "{tolerance} pt: an anchor turns {turn}°: {s:?}");
}
}
#[test]
fn simplify_straight_lines_option() {
let c = dense_circle(50.0, 200);
+2 -2
View File
@@ -9,8 +9,8 @@
mod solid;
mod visibility;
pub use solid::{
Bevel, BevelShape, 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, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate,
inflate_each, inflate_together, plane, plane_face_map,
};
pub use visibility::{VisibleFace, visible_faces};
mod shading;
+42
View File
@@ -292,12 +292,53 @@ pub struct Facet {
/// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane
/// (its front). `None` for every other facet.
pub end: Option<PlanarFace>,
/// The face's plane in view space and the projection it was drawn with, for its depth at a
/// point of the drawing ([`Facet::depth_at`]). `None` for Revolve's faces and for a face whose
/// corners lie more than 0.001 pt off one plane (a piece of a twisted wall).
pub plane: Option<DepthPlane>,
/// The contours in view space, before projection, for tests that measure depths.
#[cfg(test)]
view: Vec<Vec<V3>>,
}
/// A facet's plane in view space (x right, y down, z toward the viewer): the points `v` with
/// `normal · v = offset`, drawn by a projection about `center` with the eye `eye` in front of the
/// object's center plane (`None` without perspective).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DepthPlane {
pub normal: [f64; 3],
pub offset: f64,
pub center: Point,
pub eye: Option<f64>,
}
impl DepthPlane {
/// The view-space depth (larger is nearer the viewer) of the point of the plane that projects
/// to `p`, a point of the drawing. `None` when the plane is seen edge-on there or the point is
/// not in front of the eye.
pub fn depth_at(&self, p: Point) -> Option<f64> {
let [nx, ny, nz] = self.normal;
let (x, y) = (p.x - self.center.x, p.y - self.center.y);
let z = match self.eye {
None => (nz.abs() > 1e-9).then(|| (self.offset - nx * x - ny * y) / nz)?,
Some(e) => {
// On the ray through `p`, the point at depth z is at (x, y) × (e - z) / e.
let a = (nx * x + ny * y) / e;
let den = nz - a;
let z = (den.abs() > 1e-9).then(|| (self.offset - a * e) / den)?;
(z < e).then_some(z)?
}
};
z.is_finite().then_some(z)
}
}
impl Facet {
/// The view-space depth of the facet at `p`, a point of the drawing ([`DepthPlane::depth_at`]).
pub fn depth_at(&self, p: Point) -> Option<f64> {
self.plane.as_ref()?.depth_at(p)
}
/// About how thick the facet is across: twice its area over its perimeter (a w × l rectangle
/// long against its width gives about w).
pub fn thickness(&self) -> f64 {
@@ -339,6 +380,7 @@ impl Facet {
// A revolved cap is not one of the planar faces graphics map onto.
end: None,
away: false,
plane: None,
#[cfg(test)]
view: vec![],
}
+11 -2
View File
@@ -6,8 +6,8 @@ use super::rings::{
solid_rings_traced,
};
use super::{
Bevel, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, eye_distance,
perspective_scale,
Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View,
eye_distance, perspective_scale,
};
use crate::shadow::Projection;
@@ -129,6 +129,14 @@ impl Builder<'_> {
} else {
(V3(-n.0, -n.1, -n.2), false)
};
// A face whose corners lie off one plane (a piece of a twisted wall bent into a saddle) has
// no plane to measure its depth on. Nor has a face with a corner at or past the eye: the
// projection holds that corner just in front of the eye, so the drawing no longer matches
// the plane's projection there.
let offset = n.dot(centre);
let held = self.camera.eye.is_some_and(|e| contours.iter().flatten().any(|v| e - v.2 < e * 1e-3));
let flat = !held && contours.iter().flatten().all(|v| (n.dot(*v) - offset).abs() <= 1e-3);
let plane = flat.then_some(DepthPlane { normal: [n.0, n.1, n.2], offset, center: self.camera.origin, eye: self.camera.eye });
#[cfg(test)]
let view = contours.clone();
let contours: Vec<Vec<Point>> = contours.iter().map(|c| c.iter().map(|v| self.camera.project(*v)).collect()).collect();
@@ -156,6 +164,7 @@ impl Builder<'_> {
side: false,
away: behind,
end: None,
plane,
#[cfg(test)]
view,
});
+40
View File
@@ -154,6 +154,46 @@ fn taper_shrinks_the_back_and_twist_turns_it() {
assert!(open.len() > 2 * 8, "{}", open.len());
}
/// A flat facet carries its plane: the depth it gives at each corner of its drawing is the corner's
/// view-space depth, with and without perspective. A piece of a twisted wall whose corners lie off
/// one plane has none.
#[test]
fn a_flat_facet_measures_its_depth_on_its_plane() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
let o = Extrude { depth: 60.0, cap: true, ..Extrude::default() };
for perspective in [0.0, 50.0] {
let view = View { rotation_x: -20.0, rotation_y: 30.0, perspective, ..front() };
let flat = extrude(&p, FillRule::EvenOdd, b, o, view).unwrap();
assert!(!flat.is_empty());
for f in &flat {
assert!(f.plane.is_some(), "{perspective}");
for (q, v) in f.contours.iter().flatten().zip(f.view.iter().flatten()) {
let d = f.depth_at(*q);
assert!(d.is_some_and(|d| close(d, v.2, 1e-6)), "{perspective}: {d:?} against {}", v.2);
}
}
let twisted = extrude(&p, FillRule::EvenOdd, b, Extrude { twist: 90.0, ..o }, view).unwrap();
assert!(twisted.iter().any(|f| f.side && f.plane.is_none()), "{perspective}");
}
}
/// A flat face with a corner at or past the eye, which the projection holds just in front of the
/// eye, has no plane: its drawing no longer matches the plane's projection there.
#[test]
fn a_face_reaching_past_the_eye_has_no_plane() {
use super::build::{Builder, Order};
let (_, b) = shape(&square(0.0, 0.0, 100.0));
let camera = Camera::new(View { perspective: 50.0, ..front() }, b, 0.0);
let eye = camera.center_and_eye().1.unwrap();
for (far, has_plane) in [(eye / 2.0, true), (2.0 * eye, false)] {
let mut builder = Builder { camera: &camera, closed: false, hidden: false, facets: vec![], mesh: None };
let corners = vec![V3(-10.0, -10.0, 0.0), V3(10.0, -10.0, 0.0), V3(0.0, 10.0, far)];
builder.face(vec![corners], V3(0.0, -far, 20.0), Order::Depth).unwrap();
assert_eq!(builder.facets.len(), 1, "{far}");
assert_eq!(builder.facets[0].plane.is_some(), has_plane, "{far}");
}
}
#[test]
fn a_bevel_inside_shrinks_the_cap_and_outside_grows_the_walls() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
+112 -20
View File
@@ -49,6 +49,42 @@ fn lp_part_at<'a>(doc: &'a Document, p: Point, tol: f64, edge: bool, takes: &dyn
best.map(|(_, g, e)| (g, Some(e)))
}
/// The face and edge of a Live Paint group at `p`, among the groups `takes` takes, by the rules of
/// [`lp_part_at`], in one walk of the document. Inside a visible face of a group, the face is the
/// front-most such group's visible face under `p`, and with `edge` the edge is that group's visible
/// edge nearest `p` within `tol`. Outside every visible face there is no face, and with `edge` the
/// edge is the visible edge nearest `p` within `tol` among the groups (the front-most group's on a
/// tie).
fn lp_face_and_edge<'a>(
doc: &'a Document,
p: Point,
tol: f64,
edge: bool,
takes: &dyn Fn(NodeId) -> bool,
) -> (Option<&'a Arc<Node>>, Option<&'a Arc<Node>>) {
let mut in_face: Option<(&Arc<Node>, Option<&Arc<Node>>)> = None;
let mut best: Option<(f64, &Arc<Node>)> = None;
doc.walk(|n| {
if !is_live_paint(n) || !takes(n.id) {
return;
}
let near = if edge { visible_edge_near(n, p, tol) } else { None };
if let Some(f) = visible_face_at(n, p) {
in_face = Some((f, near));
}
if let Some(e) = near
&& let Some((.., d)) = e.path_data().and_then(|pd| pd.nearest(p))
&& best.is_none_or(|b| d <= b.0)
{
best = Some((d, e));
}
});
match in_face {
Some((f, e)) => (Some(f), e),
None => (None, best.map(|b| b.1)),
}
}
/// Whether the Live Paint Bucket takes Live Paint group `id`: it is visible, with every layer and
/// group around it.
fn lp_visible(cx: &ToolContext, id: NodeId) -> bool {
@@ -62,17 +98,25 @@ fn lp_selectable(cx: &ToolContext, id: NodeId) -> bool {
cx.doc.is_editable(id) && crate::direct::in_scope(cx.doc, cx.isolation, id)
}
/// Whether every selected object is a Live Paint group (true with nothing selected). A selection
/// that also holds other paths has regions outside its groups' faces that a click fills, making
/// one Live Paint group of the selection.
fn lp_sel_all_live(cx: &ToolContext) -> bool {
cx.selection.objects.iter().all(|id| cx.doc.node(*id).is_some_and(is_live_paint))
}
/// What the Live Paint tools highlight at `p`: the part of a Live Paint group ([`lp_part_at`], among
/// the groups `takes` takes), else with `cache` the region of the selection under `p`. A large
/// selection's regions are found on another thread ([`RegionCache::ready`]), and until they are, no
/// region is highlighted.
/// the groups `takes` takes), else with `cache` the region of the selection under `p` when the
/// selection is not only Live Paint groups ([`lp_sel_all_live`]). A large selection's regions are
/// found on another thread ([`RegionCache::ready`]), and until they are, no region is highlighted.
fn lp_hover(cx: &ToolContext, cache: Option<&mut RegionCache>, p: Point, edge: bool, takes: &dyn Fn(NodeId) -> bool) -> LpHover {
if let Some((_, part)) = lp_part_at(cx.doc, p, cx.tol(4.0), edge, takes) {
let path = part.and_then(|n| n.path_data()).map(|pd| pd.to_bezpath());
return path.map(|bp| if edge { LpHover::Edge(bp) } else { LpHover::Part(bp) }).unwrap_or_default();
}
let sel_is_live = cx.selection.objects.iter().any(|id| cx.doc.node(*id).is_some_and(is_live_paint));
if !sel_is_live && let Some(i) = cache.and_then(|c| c.ready(cx, true)).and_then(|m| m.region_at(p)) {
if !lp_sel_all_live(cx)
&& let Some(i) = cache.and_then(|c| c.ready(cx, true)).and_then(|m| m.region_at(p))
{
return LpHover::Region(i);
}
LpHover::None
@@ -125,7 +169,8 @@ enum LpPaint {
/// Shift-click fills the face. With both on, a click paints the edge nearest the pointer when one
/// is within 4 pixels, else it fills the face, and Shift-click fills the face. With both off, a
/// click paints nothing. With Highlight off, the face or edge under the pointer is not
/// highlighted.
/// highlighted. The cursor is a filled bucket where a click fills a face, a brush where it paints
/// an edge and an empty bucket where it paints nothing; with Alt it is the Eyedropper.
pub struct LivePaintBucketTool {
pub(super) cache: RegionCache,
pub(super) hover: LpHover,
@@ -202,21 +247,68 @@ impl LivePaintBucketTool {
}
/// The highlight at `p` for a pointer with Shift and Alt held as given: none with Alt or with
/// Highlight off, else the face or edge a click there paints.
/// Highlight off, else the face or edge a click there paints. With Highlight off the selection's
/// map is still made, for the cursor ([`Self::paints_at`]).
fn hover_at(&mut self, cx: &ToolContext, p: Point, shift: bool, alt: bool) -> LpHover {
if alt || !self.highlight {
if alt {
return LpHover::None;
}
let takes = |id| lp_visible(cx, id);
match self.paints(shift) {
LpPaint::Nothing => LpHover::None,
LpPaint::Fills => lp_hover(cx, Some(&mut self.cache), p, false, &takes),
// A click paints no region of the selection, so none is highlighted.
LpPaint::Strokes => lp_hover(cx, None, p, true, &takes),
LpPaint::Both => match lp_part_at(cx.doc, p, cx.tol(4.0), true, &takes) {
Some((_, Some(e))) => e.path_data().map(|pd| LpHover::Edge(pd.to_bezpath())).unwrap_or_default(),
_ => lp_hover(cx, Some(&mut self.cache), p, false, &takes),
},
let target = self.target_at(cx, p, shift);
if self.highlight { target } else { LpHover::None }
}
/// What a click at `p` reaches, Shift held or not: whether it fills a face and paints an edge,
/// with the face and the edge of a Live Paint group there ([`lp_face_and_edge`]). The document
/// is walked once: the highlight and the cursor are asked for on every pointer update.
fn parts_at<'a>(&self, cx: &ToolContext<'a>, p: Point, shift: bool) -> (bool, Option<&'a Arc<Node>>, Option<&'a Arc<Node>>) {
let (wants_face, wants_edge) = match self.paints(shift) {
LpPaint::Nothing => return (false, None, None),
LpPaint::Fills => (true, false),
LpPaint::Strokes => (false, true),
LpPaint::Both => (true, true),
};
let (face, edge) = lp_face_and_edge(cx.doc, p, cx.tol(4.0), wants_edge, &|id| lp_visible(cx, id));
(wants_face, face, edge)
}
/// The face or edge a click at `p` paints, Shift held or not. With Paint Strokes alone, a click
/// paints no region of the selection, so none is highlighted.
fn target_at(&mut self, cx: &ToolContext, p: Point, shift: bool) -> LpHover {
let (wants_face, face, edge) = self.parts_at(cx, p, shift);
let path = |n: &Arc<Node>| n.path_data().map(|pd| pd.to_bezpath());
if let Some(e) = edge {
return path(e).map(LpHover::Edge).unwrap_or_default();
}
if !wants_face {
return LpHover::None;
}
if let Some(f) = face {
return path(f).map(LpHover::Part).unwrap_or_default();
}
if !lp_sel_all_live(cx)
&& let Some(i) = self.cache.ready(cx, true).and_then(|m| m.region_at(p))
{
return LpHover::Region(i);
}
LpHover::None
}
/// The cursor for a click at `p`, Shift held or not: [`Cursor::LivePaintBucketEdge`] where it
/// paints an edge of a Live Paint group, [`Cursor::LivePaintBucketFace`] where it fills a face
/// of one or a region of the selected paths, else [`Cursor::LivePaintBucket`]. A region counts
/// once the selection's map is made (the pointer moving over it makes it), as it is highlighted.
fn paints_at(&self, cx: &ToolContext, p: Point, shift: bool) -> Cursor {
let (wants_face, face, edge) = self.parts_at(cx, p, shift);
let edge = edge.is_some();
let region =
|| !lp_sel_all_live(cx) && self.cache.key.as_ref() == Some(&RegionCache::key_for(cx, true)) && self.cache.map.region_at(p).is_some();
let face = wants_face && !edge && (face.is_some() || region());
if edge {
Cursor::LivePaintBucketEdge
} else if face {
Cursor::LivePaintBucketFace
} else {
Cursor::LivePaintBucket
}
}
}
@@ -315,8 +407,8 @@ impl Tool for LivePaintBucketTool {
lp_overlays(&self.hover, &self.cache, self.color, self.width as f32, (self.width * LP_BUCKET_EDGE_FRACTION) as f32)
}
fn cursor(&self, _cx: &ToolContext, _p: Point, m: Mods) -> Cursor {
if m.alt { Cursor::Eyedropper } else { Cursor::LivePaintBucket }
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
if m.alt { Cursor::Eyedropper } else { self.paints_at(cx, p, m.shift) }
}
fn options(&self) -> Value {
+99 -2
View File
@@ -1140,6 +1140,103 @@ fn bucket_options_choose_what_a_click_paints() {
assert_eq!(t.options()["paintFills"], false);
}
/// The cursor says what a click paints: a filled bucket over a face it fills, a brush over an
/// edge it paints, an empty bucket where it paints nothing, under each Paint Fills / Paint Strokes
/// setting and Shift; Alt keeps the Eyedropper, and Use Precise Cursors turns each into the
/// crosshair.
#[test]
fn bucket_cursor_shows_what_a_click_paints() {
let (d, ..) = live_group_doc();
let s = Selection::default();
let p = paint();
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Default::default() };
let alt = Mods { alt: true, ..Default::default() };
let at = |t: &LivePaintBucketTool, x: f64, m: Mods| t.cursor(&cx, Point::new(x, 25.0), m);
let (face, edge, none) = (Cursor::LivePaintBucketFace, Cursor::LivePaintBucketEdge, Cursor::LivePaintBucket);
let mut t = LivePaintBucketTool::default();
// Paint Fills alone: the face, and with Shift the edge in reach.
assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default()), at(&t, 400.0, Mods::default())], [face, face, none]);
assert_eq!([at(&t, 51.0, shift), at(&t, 75.0, shift)], [edge, none]);
assert_eq!([at(&t, 51.0, alt), at(&t, 400.0, alt)], [Cursor::Eyedropper, Cursor::Eyedropper]);
// Paint Strokes alone: the edge in reach, nothing farther away; Shift fills the face.
t.set_option("paintFills", &json!(false));
t.set_option("paintStrokes", &json!(true));
assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default())], [edge, none]);
assert_eq!([at(&t, 51.0, shift), at(&t, 75.0, shift)], [face, face]);
// Both: the edge in reach, else the face; Shift fills the face.
t.set_option("paintFills", &json!(true));
assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, Mods::default()), at(&t, 400.0, Mods::default())], [edge, face, none]);
assert_eq!(at(&t, 51.0, shift), face);
// Both off: a click paints nothing.
t.set_option("paintFills", &json!(false));
t.set_option("paintStrokes", &json!(false));
assert_eq!([at(&t, 51.0, Mods::default()), at(&t, 75.0, shift)], [none, none]);
// Highlight off: the cursor still says what a click paints.
let mut t = LivePaintBucketTool::default();
t.set_option("highlight", &json!(false));
assert_eq!([at(&t, 75.0, Mods::default()), at(&t, 51.0, shift)], [face, edge]);
for c in [face, edge, none] {
assert_eq!(c.precise(), Cursor::Crosshair, "{c:?}");
assert_eq!(c.stand_in(), None, "{c:?} is drawn");
}
}
/// Over a region of selected ordinary paths the cursor is the filled bucket once the pointer has
/// moved there (the move makes the selection's map), with Highlight on or off; with Paint Strokes
/// alone, a click there paints nothing and the bucket stays empty.
#[test]
fn bucket_cursor_fills_a_region_of_the_selected_paths() {
let (d, a, b) = two_rects();
let mut s = Selection::default();
s.set([a, b]);
let p = paint();
let cx = cx(&d, &s, &p);
let pos = Point::new(75.0, 50.0);
for highlight in [true, false] {
let mut t = LivePaintBucketTool::default();
t.set_option("highlight", &json!(highlight));
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket, "no map yet, highlight {highlight}");
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 50.0));
t.poll(&cx, true);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace, "highlight {highlight}");
assert_eq!(t.cursor(&cx, Point::new(400.0, 400.0), Mods::default()), Cursor::LivePaintBucket, "highlight {highlight}");
t.set_option("paintFills", &json!(false));
t.set_option("paintStrokes", &json!(true));
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket, "highlight {highlight}");
assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty());
}
}
/// With a Live Paint group and ordinary paths selected, a region of the paths outside the group
/// is highlighted and shows the filled bucket, as a click there fills it; with only the group
/// selected, the same point shows the empty bucket.
#[test]
fn bucket_fills_a_region_of_a_selection_that_mixes_a_group_and_paths() {
let (mut d, a, b) = two_rects_at(200.0);
let (g, _) = live_square(&mut d, Rect::new(0.0, 0.0, 50.0, 50.0));
let p = paint();
let pos = Point::new(275.0, 50.0);
let mut s = Selection::default();
s.set([g, a, b]);
let mixed = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.pointer(&mixed, &ev(PointerKind::Move, pos.x, pos.y));
t.poll(&mixed, true);
assert!(!t.overlays(&mixed).is_empty(), "the region is highlighted");
assert_eq!(t.cursor(&mixed, pos, Mods::default()), Cursor::LivePaintBucketFace);
let acts = t.pointer(&mixed, &ev(PointerKind::Down, pos.x, pos.y));
assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, v)] if id == "livePaint.fill" && v.get("ids").is_some()), "{acts:?}");
let mut s = Selection::default();
s.set([g]);
let live = cx(&d, &s, &p);
let mut t = LivePaintBucketTool::default();
t.pointer(&live, &ev(PointerKind::Move, pos.x, pos.y));
t.poll(&live, true);
assert!(t.overlays(&live).is_empty());
assert_eq!(t.cursor(&live, pos, Mods::default()), Cursor::LivePaintBucket);
}
#[test]
fn bucket_strokes_alone_paints_and_highlights_no_region_of_the_selection() {
let (d, a, b) = two_rects();
@@ -1269,7 +1366,7 @@ fn bucket_alt_shift_samples_only_solid_color_and_restores_hover() {
let alt = Mods { alt: true, ..Default::default() };
let both = Mods { alt: true, shift: true, ..Default::default() };
let pos = Point::new(75.0, 25.0);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace);
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
assert!(!t.overlays(&cx).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0).with_mods(alt));
@@ -1282,7 +1379,7 @@ fn bucket_alt_shift_samples_only_solid_color_and_restores_hover() {
);
assert!(t.pointer(&cx, &ev(PointerKind::Down, 400.0, 400.0).with_mods(both)).is_empty());
t.pointer(&cx, &ev(PointerKind::Move, 75.0, 25.0));
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucket);
assert_eq!(t.cursor(&cx, pos, Mods::default()), Cursor::LivePaintBucketFace);
assert!(!t.overlays(&cx).is_empty());
}
+8 -2
View File
@@ -141,8 +141,13 @@ pub enum Cursor {
Knife,
/// The Shaper tool.
Shaper,
/// The Live Paint Bucket.
/// The Live Paint Bucket where a click paints nothing: an empty paint bucket.
LivePaintBucket,
/// The Live Paint Bucket where a click fills a face (of a Live Paint group, or a region of
/// the selected paths): a filled paint bucket.
LivePaintBucketFace,
/// The Live Paint Bucket where a click paints an edge of a Live Paint group: a brush.
LivePaintBucketEdge,
/// The Measure tool.
Measure,
/// The Print Tiling tool.
@@ -280,6 +285,8 @@ impl Cursor {
| Cursor::Knife
| Cursor::Shaper
| Cursor::LivePaintBucket
| Cursor::LivePaintBucketFace
| Cursor::LivePaintBucketEdge
| Cursor::Measure
| Cursor::PrintTiling
| Cursor::SymbolSprayer
@@ -320,7 +327,6 @@ impl Cursor {
| Cursor::Join
| Cursor::Knife
| Cursor::Shaper
| Cursor::LivePaintBucket
| Cursor::Measure
| Cursor::ObjectsOnPath
| Cursor::PrintTiling
+30 -3
View File
@@ -439,7 +439,10 @@ designer = false
[[cursor]]
id = "Eyedropper"
group = "Colour and gradient"
shown_when = ["The Eyedropper tool, whatever the modifier keys. With Use Precise Cursors on, the crosshair shows instead."]
shown_when = [
"The Eyedropper tool, whatever the modifier keys. With Use Precise Cursors on, the crosshair shows instead.",
"The Live Paint Bucket with Alt held (a click samples paint).",
]
hotspot = "The pipette's tip."
look = "A pipette."
@@ -475,8 +478,32 @@ hotspot = "Where the mesh point goes."
[[cursor]]
id = "LivePaintBucket"
group = "Colour and gradient"
shown_when = ["The Live Paint Bucket: a click fills a face (or an edge) of a Live Paint group."]
hotspot = "Where the paint pours out."
shown_when = [
"The Live Paint Bucket where a click paints nothing: away from Live Paint groups and the selected paths' regions, or over a part the Paint Fills and Paint Strokes options (and Shift) leave unpainted.",
"With Use Precise Cursors on, the crosshair shows instead.",
]
hotspot = "The drop the paint pours onto."
look = "An empty paint bucket tipped toward the hotspot, a small drop on it. LivePaintBucketFace is the same bucket filled."
[[cursor]]
id = "LivePaintBucketFace"
group = "Colour and gradient"
shown_when = [
"The Live Paint Bucket over a face of a Live Paint group, or a region of the selected paths, that a click fills.",
"With Use Precise Cursors on, the crosshair shows instead.",
]
hotspot = "The drop the paint pours onto."
look = "LivePaintBucket filled, with a larger drop on the hotspot."
[[cursor]]
id = "LivePaintBucketEdge"
group = "Colour and gradient"
shown_when = [
"The Live Paint Bucket over an edge of a Live Paint group that a click paints with the stroke.",
"With Use Precise Cursors on, the crosshair shows instead.",
]
hotspot = "The brush's tip."
look = "A brush pointing down-left: bristles at the hotspot, then a white ferrule and a dark handle."
# ── Width, blend, slice and shape builder ─────────────────────────────────────────────────────────
+3 -2
View File
@@ -641,10 +641,11 @@ mod cursor_tests {
] {
assert_eq!(cursor_at(id, &d, away), c, "{id}");
assert_eq!(c.precise(), Cursor::Crosshair, "{id}");
// The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it.
// The Blob Brush's and the Eraser's dot is drawn: their tip outline goes round it. The
// Live Paint Bucket's bucket is drawn.
let stand_in = match id {
"mesh" => Some(Cursor::PenAdd),
"blobBrush" | "eraser" => None,
"blobBrush" | "eraser" | "livePaintBucket" => None,
_ => Some(Cursor::Crosshair),
};
assert_eq!(c.stand_in(), stand_in, "{id}");
+2
View File
@@ -599,6 +599,8 @@ impl VectorcraftApp {
// Toolbar too.
toolbar::show_custom(self, ui.ctx());
}
// The lanes along the window's edges where toolbars made with New Toolbar dock.
crate::custom_toolbars::lanes(self, ui);
panels::library_panel::tidy(self);
// The canvas and the panels: one docking layout. Tab hides the panels but not the canvas.
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui));
+1
View File
@@ -16,6 +16,7 @@ impl VectorcraftApp {
native_menu::run(self, ctx);
if self.fonts_ready {
tools_float::cancel_move_on_escape(self, ctx);
crate::custom_toolbars::cancel_move_on_escape(self, ctx);
shortcuts::handle(self, ctx);
}
// A Copy taken in this UI phase (an egui copy event, or a command it runs) is published in
+1 -1
View File
@@ -123,6 +123,7 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon {
Cursor::TypeArea | Cursor::TypeOnPath => C::Text,
// The system has no tip outline to go round: its crosshair aims as well.
Cursor::BlobBrush | Cursor::Eraser => C::Crosshair,
Cursor::LivePaintBucket | Cursor::LivePaintBucketFace | Cursor::LivePaintBucketEdge => C::Crosshair,
// Not drawn yet: the cursor each borrows.
Cursor::Lasso
| Cursor::MagicWand
@@ -133,7 +134,6 @@ pub(super) fn cursor_icon(c: Cursor) -> egui::CursorIcon {
| Cursor::Join
| Cursor::Knife
| Cursor::Shaper
| Cursor::LivePaintBucket
| Cursor::Measure
| Cursor::PrintTiling
| Cursor::SymbolSprayer
+3
View File
@@ -184,6 +184,9 @@ fn system_cursors_show_the_same_crosshair_with_precise_cursors_on_or_off() {
Cursor::PencilNew,
Cursor::PencilStraight,
Cursor::PencilContinue,
Cursor::LivePaintBucket,
Cursor::LivePaintBucketFace,
Cursor::LivePaintBucketEdge,
] {
assert_eq!(cursor_icon(c), egui::CursorIcon::Crosshair, "{c:?}");
assert_eq!(cursor_icon(c), cursor_icon(c.precise()), "{c:?}");
+42 -1
View File
@@ -432,6 +432,42 @@ fn shape_builder(p: &mut Ink, o: Pos2, erase: bool) {
}
}
/// The Live Paint Bucket: a paint bucket tipped toward the hotspot at its lower left, its mouth
/// down-left with a rim across it, and a drop on the hotspot. Empty (white) with a small drop where
/// a click paints nothing; filled, with a larger drop, where a click fills a face.
fn paint_bucket(p: &mut Ink, o: Pos2, filled: bool) {
// `u` runs from the hotspot up-right into the bucket, `v` across it.
let (d, n) = (vec2(1.0, -1.0).normalized(), vec2(1.0, 1.0).normalized());
let at = |u: f32, v: f32| o + u * d + v * n;
poly(p, vec![at(5.5, -6.0), at(16.5, -4.5), at(16.5, 4.5), at(5.5, 6.0)], if filled { INK } else { HALO }, INK);
poly(p, vec![at(4.5, -7.0), at(6.5, -7.0), at(6.5, 7.0), at(4.5, 7.0)], INK, INK);
if filled {
p.circle_filled(o, 3.5, HALO);
p.circle_filled(o, 2.2, INK);
} else {
p.circle_filled(o, 2.5, HALO);
p.circle_filled(o, 1.25, INK);
}
}
/// The Live Paint Bucket over an edge it paints: a brush, its bristles' tip on the hotspot, the
/// white ferrule and the black handle running up-right.
fn paint_brush(p: &mut Ink, o: Pos2) {
let (d, n) = (vec2(1.0, -1.0).normalized(), vec2(1.0, 1.0).normalized());
let at = |u: f32, v: f32| o + u * d + v * n;
let bristles = vec![at(0.0, 0.0), at(4.0, -2.2), at(6.0, -2.2), at(6.0, 2.2), at(4.0, 2.2)];
let ferrule = vec![at(6.0, -2.0), at(9.0, -2.0), at(9.0, 2.0), at(6.0, 2.0)];
let handle = vec![at(9.0, -1.5), at(19.0, -1.2), at(19.0, 1.2), at(9.0, 1.5)];
// Every halo first, so no part's halo covers another's outline.
for part in [&bristles, &ferrule, &handle] {
p.add(Shape::closed_line(part.clone(), Stroke::new(3.0, HALO)));
}
for (part, fill) in [(bristles, INK), (ferrule, HALO), (handle, INK)] {
p.add(Shape::convex_polygon(part.clone(), fill, Stroke::NONE));
p.add(Shape::closed_line(part, Stroke::new(1.0, INK)));
}
}
/// The Hand tool and Space: an open hand (palm and four fingers, thumb to the left), or the same
/// hand closed while it drags the view. Windows has no system hand that isn't a pointing finger
/// (winit maps egui's Grab and Grabbing to the four-headed move cursor), so it is drawn like the
@@ -480,7 +516,7 @@ fn magnifier(p: &mut Ink, o: Pos2, out: bool) {
/// Every cursor with a glyph: its own, drawn here, or the one it borrows.
#[cfg(test)]
const GLYPHS: [Cursor; 93] = [
const GLYPHS: [Cursor; 95] = [
Cursor::Hand,
Cursor::HandGrab,
Cursor::ZoomIn,
@@ -548,6 +584,8 @@ const GLYPHS: [Cursor; 93] = [
Cursor::Knife,
Cursor::Shaper,
Cursor::LivePaintBucket,
Cursor::LivePaintBucketFace,
Cursor::LivePaintBucketEdge,
Cursor::Measure,
Cursor::PrintTiling,
Cursor::SymbolSprayer,
@@ -669,6 +707,9 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
Cursor::LoadedText => loaded_text(ink, p),
Cursor::ShapeBuilder => shape_builder(ink, p, false),
Cursor::ShapeBuilderErase => shape_builder(ink, p, true),
Cursor::LivePaintBucket => paint_bucket(ink, p, false),
Cursor::LivePaintBucketFace => paint_bucket(ink, p, true),
Cursor::LivePaintBucketEdge => paint_brush(ink, p),
Cursor::Hand => hand(ink, p, false),
Cursor::HandGrab => hand(ink, p, true),
Cursor::ZoomIn => magnifier(ink, p, false),
+39
View File
@@ -292,6 +292,45 @@ fn the_pencil_continuation_cursor_is_the_straight_line_cursor_with_an_end_point(
}
}
/// The Live Paint Bucket's cursors are drawn, not the crosshair: an empty bucket where a click
/// paints nothing, a filled bucket with a larger drop on the hotspot where it fills a face, and a
/// brush with its tip on the hotspot where it paints an edge.
#[test]
fn the_live_paint_bucket_shows_a_bucket_or_a_brush() {
for ppp in [1.0f32, 2.0] {
let img = |c| rasterize(c, ppp).unwrap_or_else(|| panic!("{c:?} at {ppp}"));
let (cross, empty, filled, brush) =
(img(Cursor::Crosshair), img(Cursor::LivePaintBucket), img(Cursor::LivePaintBucketFace), img(Cursor::LivePaintBucketEdge));
// The pixel nearest the point `u` points up-right of the hotspot and `v` down-right across.
let at = |img: &CustomCursorImage, u: f32, v: f32| {
let s = std::f32::consts::FRAC_1_SQRT_2;
let [hx, hy] = img.hotspot.map(f32::from);
let (x, y) = ((hx + (u + v) * s * ppp - 0.5).round(), (hy + (v - u) * s * ppp - 0.5).round());
let inside = x >= 0.0 && y >= 0.0 && x < f32::from(img.size[0]) && y < f32::from(img.size[1]);
if inside { pixel(img, x as usize, y as usize) } else { [0; 4] }
};
let inked = |p: [u8; 4]| p[3] > 200 && p[0] < 64;
let white = |p: [u8; 4]| p[3] > 200 && p[0] > 192;
assert!(white(at(&empty, 11.0, 2.0)), "the empty bucket's body is white at {ppp}");
assert!(inked(at(&filled, 11.0, 2.0)), "the filled bucket's body is ink at {ppp}");
assert!(at(&empty, 0.0, 0.0)[3] > 0 && inked(at(&filled, 0.0, 0.0)), "a drop on the hotspot at {ppp}");
if ppp == 2.0 {
assert!(inked(at(&filled, 1.4, 0.0)) && !inked(at(&empty, 2.0, 0.0)), "the filled bucket's drop is larger");
}
assert!(inked(at(&brush, 3.0, 0.0)), "the bristles by the hotspot at {ppp}");
assert!(white(at(&brush, 7.5, 0.0)), "the white ferrule at {ppp}");
assert!(inked(at(&brush, 14.0, 0.0)), "the handle at {ppp}");
assert!(!inked(at(&brush, 11.0, 4.0)), "the brush is thin where the bucket is wide at {ppp}");
assert!(white(at(&empty, 14.0, 0.0)), "the empty bucket has no handle there at {ppp}");
for (c, i) in [(Cursor::LivePaintBucket, &empty), (Cursor::LivePaintBucketFace, &filled), (Cursor::LivePaintBucketEdge, &brush)] {
assert!(c.stand_in().is_none(), "{c:?} is drawn");
assert_ne!(i, &cross, "{c:?} is not the crosshair at {ppp}");
assert_eq!(rasterize(c.precise(), ppp).as_ref(), Some(&cross), "{c:?} with Use Precise Cursors at {ppp}");
}
assert!(empty != filled && filled != brush && empty != brush, "three looks at {ppp}");
}
}
#[test]
fn each_bitmap_is_made_once_so_the_os_cursor_is_kept() {
let mut images = Images::default();
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -508,7 +508,10 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() {
assert_eq!(slots(&app), shipped, "the Tools panel's toolbar is untouched");
assert!(!app.ui.tools_drawer, "no drawer opened");
let list = app.run("window.toolbar.list", json!({})).unwrap();
assert_eq!(list, json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]]}]));
assert_eq!(
list,
json!([{"name": "Mine", "shown": true, "double": false, "slots": [["lasso"]], "floating": true, "side": "left", "order": null}])
);
// A second tool goes after the first.
let shown = open(&mut app, 19.0);
click(&mut app, &ctx, 20.0, items(&shown, "Magic Wand Tool")[0].0);
+18
View File
@@ -3372,6 +3372,20 @@ digits Malayalam Малаялам
Spot Color Objects Обекти със спот цветове
Pattern Objects Обекти с мостри
Gradient Objects Обекти с градиенти
Font Details Подробности за шрифтовете
Linked Images Свързани изображения
Embedded Images Вградени изображения
Compound Paths Съставни пътища
Text Objects Текстови обекти
Placed Documents Поставени документи
Symbol Instances Екземпляри на символи
Gradient Meshes Мрежи с градиент
Blends Преливания
Envelopes Пликове
Intertwine Groups Групи с преплитане
Opacity Masks Маски за непрозрачност
Objects with Effects Обекти с ефекти
Path Length Дължина на пътя
Spot Colors Спот цветове
Spot Colors… Спот цветове…
Spread: Разпространение:
@@ -4057,6 +4071,10 @@ axis Both И двете
Dock Panel Закотвен панел
Dock to Top Закотвяне горе
Dock to Bottom Закотвяне долу
Dock to Left Закотвяне вляво
Dock to Right Закотвяне вдясно
Dock Toolbar Закотвяне на лентата с инструменти
Float Toolbar Плаваща лента с инструменти
Control Bar Options Опции на контролната лента
Tool Options Опции за инструмент
Object Options Опции за обект
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -908,6 +908,10 @@
Dock Panel Usidri panel
Dock to Top Usidri na vrh
Dock to Bottom Usidri na dno
Dock to Left Usidri lijevo
Dock to Right Usidri desno
Dock Toolbar Usidri traku s alatima
Float Toolbar Odvoji traku s alatima
Control Bar Options Opcije kontrolne trake
Tool Options Opcije alata
Object Options Opcije objekta
@@ -3959,6 +3963,19 @@ theme Appearance Izgled
Spot Color Objects Objekti sa spot bojama
Pattern Objects Objekti s uzorcima
Gradient Objects Objekti s gradijentima
Font Details Detalji fontova
Linked Images Povezane slike
Embedded Images Ugrađene slike
Compound Paths Složene putanje
Text Objects Tekstualni objekti
Placed Documents Postavljeni dokumenti
Symbol Instances Instance simbola
Gradient Meshes Gradijentne mreže
Blends Stapanja
Envelopes Omotnice
Intertwine Groups Grupe isprepletanja
Opacity Masks Maske neprozirnosti
Objects with Effects Objekti s efektima
Spot Colors Spot boje
Spot Colors (0) Spot boje (0)
Swatch Options Opcije uzorka boje
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -1247,6 +1247,10 @@ antiAlias Sharp Nítid
Dock Panel Acobla el panell
Dock to Top Acobla a dalt
Dock to Bottom Acobla a baix
Dock to Left Acobla a l’esquerra
Dock to Right Acobla a la dreta
Dock Toolbar Acobla la barra d’eines
Float Toolbar Flota la barra d’eines
Control Bar Options Opcions de la barra de control
Tool Options Opcions de l’eina
Object Options Opcions de l’objecte
@@ -4385,6 +4389,19 @@ digits Malayalam Malaiàlam
Spot Color Objects Objectes amb colors directes
Pattern Objects Objectes amb motius
Gradient Objects Objectes amb degradats
Font Details Detalls dels tipus de lletra
Linked Images Imatges enllaçades
Embedded Images Imatges incrustades
Compound Paths Traçats compostos
Text Objects Objectes de text
Placed Documents Documents col·locats
Symbol Instances Instàncies de símbol
Gradient Meshes Malles de degradat
Blends Fusions
Envelopes Embolcalls
Intertwine Groups Grups entrellaçats
Opacity Masks Màscares d’opacitat
Objects with Effects Objectes amb efectes
Spot Colors Colors directes
Spot Colors (0) Colors directes (0)
Spot Colors… Colors directes…
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -923,6 +923,10 @@
Dock Panel Ukotvit panel
Dock to Top Ukotvit nahoru
Dock to Bottom Ukotvit dolů
Dock to Left Ukotvit vlevo
Dock to Right Ukotvit vpravo
Dock Toolbar Ukotvit panel nástrojů
Float Toolbar Plovoucí panel nástrojů
Control Bar Options Možnosti ovládacího panelu
Tool Options Možnosti nástroje
Object Options Možnosti objektu
@@ -4015,6 +4019,19 @@ theme Appearance Motiv
Spot Color Objects Objekty s přímými barvami
Pattern Objects Objekty se vzorky
Gradient Objects Objekty s přechody
Font Details Podrobnosti písem
Linked Images Propojené obrazy
Embedded Images Vložené obrazy
Compound Paths Složené cesty
Text Objects Textové objekty
Placed Documents Umístěné dokumenty
Symbol Instances Instance symbolů
Gradient Meshes Přechodové sítě
Blends Prolnutí
Envelopes Obálky
Intertwine Groups Skupiny proplétání
Opacity Masks Masky krytí
Objects with Effects Objekty s efekty
Spot Colors Přímé barvy
Spot Colors (0) Přímé barvy (0)
Swatch Options Možnosti položky vzorníku
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -853,6 +853,10 @@
Dock Panel Dok panel
Dock to Top Dok øverst
Dock to Bottom Dok nederst
Dock to Left Dok til venstre
Dock to Right Dok til højre
Dock Toolbar Dok værktøjslinjen
Float Toolbar Flydende værktøjslinje
Control Bar Options Indstillinger for kontrollinjen
Tool Options Værktøjsindstillinger
Object Options Objektindstillinger
@@ -3734,6 +3738,19 @@ theme Appearance Udseende
Spot Color Objects Objekter med spotfarver
Pattern Objects Objekter med mønstre
Gradient Objects Objekter med gradienter
Font Details Skrifttypedetaljer
Linked Images Linkede billeder
Embedded Images Indlejrede billeder
Compound Paths Sammensatte kurver
Text Objects Tekstobjekter
Placed Documents Placerede dokumenter
Symbol Instances Symbolforekomster
Gradient Meshes Gradientnet
Blends Blandinger
Envelopes Konvolutter
Intertwine Groups Sammenfletningsgrupper
Opacity Masks Opacitetsmasker
Objects with Effects Objekter med effekter
Spot Colors Spotfarver
Spot Colors (0) Spotfarver (0)
Swatch Options Indstillinger for farveprøve
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -3435,6 +3435,20 @@ effect Points Punkte
Spot Color Objects Objekte mit Volltonfarben
Pattern Objects Objekte mit Mustern
Gradient Objects Objekte mit Verläufen
Font Details Schriftdetails
Linked Images Verknüpfte Bilder
Embedded Images Eingebettete Bilder
Compound Paths Zusammengesetzte Pfade
Text Objects Textobjekte
Placed Documents Platzierte Dokumente
Symbol Instances Symbolinstanzen
Gradient Meshes Verlaufsgitter
Blends Angleichungen
Envelopes Hüllen
Intertwine Groups Verflechtungsgruppen
Opacity Masks Deckkraftmasken
Objects with Effects Objekte mit Effekten
Pattern Swatches Musterfarbfelder
Spot Colors Volltonfarben
Spot Colors… Volltonfarben…
Spread: Ausbreitung:
@@ -4077,6 +4091,10 @@ theme Appearance Erscheinungsbild
Dock Panel Bedienfeld andocken
Dock to Top Oben andocken
Dock to Bottom Unten andocken
Dock to Left Links andocken
Dock to Right Rechts andocken
Dock Toolbar Werkzeugleiste andocken
Float Toolbar Werkzeugleiste ablösen
Control Bar Options Optionen der Steuerungsleiste
Tool Options Werkzeugoptionen
Object Options Objektoptionen
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -2257,6 +2257,10 @@ axis Both Και τα δύο
Dock Panel Αγκύρωση πάνελ
Dock to Top Αγκύρωση επάνω
Dock to Bottom Αγκύρωση κάτω
Dock to Left Αγκύρωση αριστερά
Dock to Right Αγκύρωση δεξιά
Dock Toolbar Αγκύρωση γραμμής εργαλείων
Float Toolbar Αιωρούμενη γραμμή εργαλείων
Control Bar Options Επιλογές γραμμής ελέγχου
Tool Options Επιλογές εργαλείου
Object Options Επιλογές αντικειμένου
@@ -3969,6 +3973,20 @@ digits Malayalam Μαλαγιάλαμ
Spot Color Objects Αντικείμενα με χρώματα spot
Pattern Objects Αντικείμενα με μοτίβα
Gradient Objects Αντικείμενα με ντεγκραντέ
Font Details Λεπτομέρειες γραμματοσειρών
Linked Images Συνδεδεμένες εικόνες
Embedded Images Ενσωματωμένες εικόνες
Compound Paths Σύνθετες διαδρομές
Text Objects Αντικείμενα κειμένου
Placed Documents Τοποθετημένα έγγραφα
Symbol Instances Στιγμιότυπα συμβόλων
Gradient Meshes Πλέγματα ντεγκραντέ
Blends Αναμείξεις
Envelopes Περιβλήματα
Intertwine Groups Ομάδες διαπλοκής
Opacity Masks Μάσκες αδιαφάνειας
Objects with Effects Αντικείμενα με εφέ
Path Length Μήκος διαδρομής
Spot Colors Πλακάτα χρώματα
Spot Colors… Πλακάτα χρώματα…
Stacked Bar Graph Tool Στοιβαγμένο ραβδόγραμμα (Stacked Bar Graph Tool)
Can't render this file because it is too large.
+17
View File
@@ -3465,6 +3465,19 @@ digits Malayalam Malayálam
Spot Color Objects Objetos con tintas planas
Pattern Objects Objetos con motivos
Gradient Objects Objetos con degradados
Font Details Detalles de fuentes
Linked Images Imágenes vinculadas
Embedded Images Imágenes incrustadas
Compound Paths Trazados compuestos
Text Objects Objetos de texto
Placed Documents Documentos colocados
Symbol Instances Instancias de símbolo
Gradient Meshes Mallas de degradado
Blends Fusiones
Envelopes Envolventes
Intertwine Groups Grupos entrelazados
Opacity Masks Máscaras de opacidad
Objects with Effects Objetos con efectos
Spot Colors Tintas planas
Spot Colors… Tintas planas…
Spread: Extensión:
@@ -4155,6 +4168,10 @@ axis Both Ambos
Dock Panel Anclar panel
Dock to Top Anclar arriba
Dock to Bottom Anclar abajo
Dock to Left Anclar a la izquierda
Dock to Right Anclar a la derecha
Dock Toolbar Anclar barra de herramientas
Float Toolbar Hacer flotar la barra de herramientas
Control Bar Options Opciones de la barra de control
Tool Options Opciones de herramienta
Object Options Opciones de objeto
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -911,6 +911,10 @@
Dock Panel Telakoi paneeli
Dock to Top Telakoi ylös
Dock to Bottom Telakoi alas
Dock to Left Telakoi vasemmalle
Dock to Right Telakoi oikealle
Dock Toolbar Telakoi työkalurivi
Float Toolbar Kelluta työkalurivi
Control Bar Options Ohjauspalkin asetukset
Tool Options Työkalun asetukset
Object Options Objektin asetukset
@@ -3939,6 +3943,19 @@ theme Appearance Ulkoasu
Spot Color Objects Objektit, joissa on spottivärejä
Pattern Objects Objektit, joissa on kuvioita
Gradient Objects Objektit, joissa on liukuvärejä
Font Details Fonttien tiedot
Linked Images Linkitetyt kuvat
Embedded Images Upotetut kuvat
Compound Paths Yhdistelmäpolut
Text Objects Tekstiobjektit
Placed Documents Sijoitetut asiakirjat
Symbol Instances Symbolien ilmentymät
Gradient Meshes Liukuväriverkot
Blends Sulautukset
Envelopes Vääristyskuoret
Intertwine Groups Lomitusryhmät
Opacity Masks Peittävyysmaskit
Objects with Effects Objektit, joissa on tehosteita
Spot Colors Spottivärit
Spot Colors (0) Spottivärit (0)
Swatch Options Värimallin asetukset
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -3457,6 +3457,19 @@ digits Malayalam Malayalam
Spot Color Objects Objets avec tons directs
Pattern Objects Objets avec motifs
Gradient Objects Objets avec dégradés
Font Details Détails des polices
Linked Images Images liées
Embedded Images Images incorporées
Compound Paths Tracés transparents
Text Objects Objets texte
Placed Documents Documents importés
Symbol Instances Instances de symbole
Gradient Meshes Filets de dégradé
Blends Dégradés de formes
Envelopes Enveloppes
Intertwine Groups Groupes entrelacés
Opacity Masks Masques d’opacité
Objects with Effects Objets avec effets
Spot Colors Tons directs
Spot Colors… Tons directs…
Spread: Étendue :
@@ -4144,6 +4157,10 @@ axis Both Les deux
Dock Panel Ancrer le panneau
Dock to Top Ancrer en haut
Dock to Bottom Ancrer en bas
Dock to Left Ancrer à gauche
Dock to Right Ancrer à droite
Dock Toolbar Ancrer la barre d’outils
Float Toolbar Rendre la barre d’outils flottante
Control Bar Options Options de la barre de contrôle
Tool Options Options de l’outil
Object Options Options de l’objet
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -1386,6 +1386,10 @@ antiAlias Sharp शार्प
Dock Panel पैनल डॉक करें
Dock to Top ऊपर डॉक करें
Dock to Bottom नीचे डॉक करें
Dock to Left बाईं ओर डॉक करें
Dock to Right दाईं ओर डॉक करें
Dock Toolbar टूलबार डॉक करें
Float Toolbar टूलबार फ़्लोट करें
Control Bar Options नियंत्रण बार ऑप्शन्स
Tool Options टूल ऑप्शन्स
Object Options ऑब्जेक्ट ऑप्शन्स
@@ -4747,6 +4751,19 @@ antiAlias Sharp शार्प
Spot Color Objects स्पॉट कलर्स के साथ ऑब्जेक्ट्स
Pattern Objects पैटर्न्स के साथ ऑब्जेक्ट्स
Gradient Objects ग्रेडिएंट्स के साथ ऑब्जेक्ट्स
Font Details फ़ॉन्ट विवरण
Linked Images लिंक्ड चित्र
Embedded Images एम्बेडेड चित्र
Compound Paths कंपाउंड पाथ्स
Text Objects टेक्स्ट ऑब्जेक्ट्स
Placed Documents प्लेस्ड डॉक्यूमेंट्स
Symbol Instances सिंबल इंस्टेंस
Gradient Meshes ग्रेडिएंट मेश
Blends ब्लेंड्स
Envelopes एन्वेलप्स
Intertwine Groups इंटरट्वाइन समूह
Opacity Masks ओपेसिटी मास्क
Objects with Effects इफ़ेक्ट्स के साथ ऑब्जेक्ट्स
Spot Colors स्पॉट रंग
Spot Colors (0) स्पॉट कलर्स (0)
Spot Colors… स्पॉट कलर्स…
Can't render this file because it is too large.
+17
View File
@@ -1114,6 +1114,10 @@ font-technology Variable Változó
Dock Panel Panel dokkolása
Dock to Top Dokkolás felülre
Dock to Bottom Dokkolás alulra
Dock to Left Dokkolás balra
Dock to Right Dokkolás jobbra
Dock Toolbar Eszköztár dokkolása
Float Toolbar Eszköztár lebegtetése
Control Bar Options Vezérlősáv beállításai
Tool Options Eszközbeállítások
Object Options Objektumbeállítások
@@ -4119,6 +4123,19 @@ mark-style Japanese Japán
Spot Color Objects Direkt színeket használó objektumok
Pattern Objects Mintázatokat használó objektumok
Gradient Objects Színátmeneteket használó objektumok
Font Details Betűtípus-részletek
Linked Images Csatolt képek
Embedded Images Beágyazott képek
Compound Paths Összetett útvonalak
Text Objects Szövegobjektumok
Placed Documents Elhelyezett dokumentumok
Symbol Instances Szimbólumpéldányok
Gradient Meshes Színátmenetes hálók
Blends Összemosások
Envelopes Burkolók
Intertwine Groups Összefonási csoportok
Opacity Masks Átlátszósági maszkok
Objects with Effects Effektusokat használó objektumok
Spot Colors Direktszínek
Spot Colors (0) Direktszínek (0)
Spot Colors… Direktszínek…
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -853,6 +853,10 @@
Dock Panel Tambatkan panel
Dock to Top Tambatkan ke atas
Dock to Bottom Tambatkan ke bawah
Dock to Left Tambatkan ke kiri
Dock to Right Tambatkan ke kanan
Dock Toolbar Tambatkan bilah alat
Float Toolbar Mengambangkan bilah alat
Control Bar Options Opsi bilah kontrol
Tool Options Opsi alat
Object Options Opsi objek
@@ -3734,6 +3738,19 @@ theme Appearance Tampilan
Spot Color Objects Objek dengan Warna Spot
Pattern Objects Objek dengan Pola
Gradient Objects Objek dengan Gradien
Font Details Detail Font
Linked Images Gambar Tertaut
Embedded Images Gambar Tersemat
Compound Paths Jalur Majemuk
Text Objects Objek Teks
Placed Documents Dokumen yang Ditempatkan
Symbol Instances Instans Simbol
Gradient Meshes Mesh Gradien
Blends Blend
Envelopes Amplop
Intertwine Groups Grup Jalinan
Opacity Masks Mask Opasitas
Objects with Effects Objek dengan Efek
Spot Colors Warna spot
Spot Colors (0) Warna spot (0)
Swatch Options Opsi sampel
Can't render this file because it contains an unexpected character in line 2422 and column 5.
+18
View File
@@ -3510,6 +3510,20 @@ digits Malayalam Malayalam
Spot Color Objects Oggetti con colori spot
Pattern Objects Oggetti con motivi
Gradient Objects Oggetti con sfumature
Font Details Dettagli font
Linked Images Immagini collegate
Embedded Images Immagini incorporate
Compound Paths Tracciati composti
Text Objects Oggetti di testo
Placed Documents Documenti inseriti
Symbol Instances Istanze di simbolo
Gradient Meshes Trame sfumatura
Blends Fusioni
Envelopes Involucri
Intertwine Groups Gruppi intrecciati
Opacity Masks Maschere di opacità
Objects with Effects Oggetti con effetti
Pattern Swatches Campioni motivo
Spot Colors Colori spot
Spot Colors… Colori spot…
Spread: Estensione:
@@ -4206,6 +4220,10 @@ axis Both Entrambi
Dock Panel Ancora pannello
Dock to Top Ancora in alto
Dock to Bottom Ancora in basso
Dock to Left Ancora a sinistra
Dock to Right Ancora a destra
Dock Toolbar Ancora barra degli strumenti
Float Toolbar Rendi mobile barra degli strumenti
Control Bar Options Opzioni barra di controllo
Tool Options Opzioni strumento
Object Options Opzioni oggetto
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -3287,6 +3287,20 @@ mark-style Japanese 日本式
Spot Color Objects 特色を使用したオブジェクト
Pattern Objects パターンを使用したオブジェクト
Gradient Objects グラデーションを使用したオブジェクト
Font Details フォントの詳細
Linked Images リンク画像
Embedded Images 埋め込み画像
Compound Paths 複合パス
Text Objects テキストオブジェクト
Placed Documents 配置ドキュメント
Symbol Instances シンボルインスタンス
Gradient Meshes グラデーションメッシュ
Blends ブレンド
Envelopes エンベロープ
Intertwine Groups 織り交ぜグループ
Opacity Masks 不透明マスク
Objects with Effects 効果を使用したオブジェクト
Pattern Swatches パターンスウォッチ
Spot Colors 特色
Spot Colors… 特色…
Spread: 拡散:
@@ -4148,6 +4162,10 @@ axis Both 両方
Dock Panel パネルをドッキング
Dock to Top 上部にドッキング
Dock to Bottom 下部にドッキング
Dock to Left 左側にドッキング
Dock to Right 右側にドッキング
Dock Toolbar ツールバーをドッキング
Float Toolbar ツールバーをフローティング
Control Bar Options コントロールバーオプション
Tool Options ツールオプション
Object Options オブジェクトオプション
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -816,6 +816,10 @@
Dock Panel პანელის მიმაგრება
Dock to Top ზემოთ მიმაგრება
Dock to Bottom ქვემოთ მიმაგრება
Dock to Left მარცხნივ მიმაგრება
Dock to Right მარჯვნივ მიმაგრება
Dock Toolbar ხელსაწყოთა ზოლის მიმაგრება
Float Toolbar მცურავი ხელსაწყოთა ზოლი
Control Bar Options მართვის ზოლის პარამეტრები
Tool Options ხელსაწყოს პარამეტრები
Object Options ობიექტის პარამეტრები
@@ -3573,6 +3577,19 @@ theme Appearance იერსახე
Spot Color Objects ობიექტები სპოტ-ფერებით
Pattern Objects ობიექტები პატერნებით
Gradient Objects ობიექტები გრადიენტებით
Font Details შრიფტების დეტალები
Linked Images დაკავშირებული გამოსახულებები
Embedded Images ჩაშენებული გამოსახულებები
Compound Paths შედგენილი ტრაექტორიები
Text Objects ტექსტური ობიექტები
Placed Documents განთავსებული დოკუმენტები
Symbol Instances სიმბოლოს ეგზემპლარები
Gradient Meshes გრადიენტული ბადეები
Blends გადასვლები
Envelopes გარსები
Intertwine Groups გადახლართვის ჯგუფები
Opacity Masks გაუმჭვირვალობის ნიღბები
Objects with Effects ობიექტები ეფექტებით
Spot Colors სპოტ-ფერები
Swatch Options ფერის ნიმუშის პარამეტრები
Ungroup Color Group ფერების ჯგუფის დაშლა
Can't render this file because it is too large.
+18
View File
@@ -3276,6 +3276,20 @@ mark-style Japanese 일본식
Spot Color Objects 별색을 사용한 개체
Pattern Objects 패턴을 사용한 개체
Gradient Objects 그레이디언트를 사용한 개체
Font Details 글꼴 세부 정보
Linked Images 연결된 이미지
Embedded Images 포함된 이미지
Compound Paths 컴파운드 패스
Text Objects 텍스트 개체
Placed Documents 가져온 문서
Symbol Instances 심볼 인스턴스
Gradient Meshes 그레이디언트 메시
Blends 블렌드
Envelopes 엔벨로프
Intertwine Groups 교차 그룹
Opacity Masks 불투명 마스크
Objects with Effects 효과를 사용한 개체
Pattern Swatches 패턴 견본
Spot Colors 별색
Spot Colors… 별색…
Spread: 확산:
@@ -4132,6 +4146,10 @@ axis Both 양쪽
Dock Panel 패널 고정
Dock to Top 위쪽에 고정
Dock to Bottom 아래쪽에 고정
Dock to Left 왼쪽에 고정
Dock to Right 오른쪽에 고정
Dock Toolbar 도구 막대 고정
Float Toolbar 도구 막대 분리
Control Bar Options 컨트롤 막대 옵션
Tool Options 도구 옵션
Object Options 개체 옵션
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -1368,6 +1368,10 @@
Dock Panel Paneel dokken
Dock to Top Bovenaan dokken
Dock to Bottom Onderaan dokken
Dock to Left Links dokken
Dock to Right Rechts dokken
Dock Toolbar Werkbalk dokken
Float Toolbar Werkbalk laten zweven
Control Bar Options Opties voor bedieningsbalk
Tool Options Gereedschapsopties
Object Options Objectopties
@@ -4249,6 +4253,19 @@ theme Appearance Vormgeving
Spot Color Objects Objecten met spotkleuren
Pattern Objects Objecten met patronen
Gradient Objects Objecten met verlopen
Font Details Lettertypedetails
Linked Images Gekoppelde afbeeldingen
Embedded Images Ingesloten afbeeldingen
Compound Paths Samengestelde paden
Text Objects Tekstobjecten
Placed Documents Geplaatste documenten
Symbol Instances Symboolinstanties
Gradient Meshes Verlooprasters
Blends Vermengingen
Envelopes Omvormingen
Intertwine Groups Verstrengelingsgroepen
Opacity Masks Dekkingmaskers
Objects with Effects Objecten met effecten
Spot Colors Spotkleuren
Spot Colors (0) Spotkleuren (0)
Swatch Options Kleurstaalopties
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -868,6 +868,10 @@
Dock Panel Zadokuj panel
Dock to Top Zadokuj u góry
Dock to Bottom Zadokuj u dołu
Dock to Left Zadokuj po lewej
Dock to Right Zadokuj po prawej
Dock Toolbar Zadokuj pasek narzędzi
Float Toolbar Odepnij pasek narzędzi
Control Bar Options Opcje paska sterowania
Tool Options Opcje narzędzia
Object Options Opcje obiektu
@@ -3874,6 +3878,20 @@ theme Appearance Wygląd
Spot Color Objects Obiekty z kolorami dodatkowymi
Pattern Objects Obiekty ze wzorkami
Gradient Objects Obiekty z gradientami
Font Details Szczegóły czcionek
Linked Images Połączone obrazy
Embedded Images Osadzone obrazy
Compound Paths Ścieżki złożone
Text Objects Obiekty tekstowe
Placed Documents Umieszczone dokumenty
Symbol Instances Wystąpienia symboli
Gradient Meshes Siatki gradientowe
Blends Przejścia
Envelopes Koperty
Intertwine Groups Grupy przeplatania
Opacity Masks Maski krycia
Objects with Effects Obiekty z efektami
Pattern Swatches Próbki wzorków
Spot Colors Kolory dodatkowe
Swatch Options Opcje próbki
Ungroup Color Group Rozgrupuj grupę kolorów
Can't render this file because it contains an unexpected character in line 2 and column 73.
+17
View File
@@ -2913,6 +2913,19 @@ digits Malayalam Malaiala
Spot Color Objects Objetos com cores spot
Pattern Objects Objetos com padrões
Gradient Objects Objetos com gradientes
Font Details Detalhes das fontes
Linked Images Imagens vinculadas
Embedded Images Imagens incorporadas
Compound Paths Caminhos compostos
Text Objects Objetos de texto
Placed Documents Documentos colocados
Symbol Instances Instâncias de símbolo
Gradient Meshes Malhas de gradiente
Blends Mesclagens
Envelopes Envelopes
Intertwine Groups Grupos entrelaçados
Opacity Masks Máscaras de opacidade
Objects with Effects Objetos com efeitos
Spot Colors Cores Spot
Spot Colors… Cores Spot…
Spread: Propagação:
@@ -3382,6 +3395,10 @@ imageTrace Outline Contorno
Dock Panel Encaixar Painel
Dock to Top Encaixar na Parte Superior
Dock to Bottom Encaixar na Parte Inferior
Dock to Left Encaixar à Esquerda
Dock to Right Encaixar à Direita
Dock Toolbar Encaixar Barra de Ferramentas
Float Toolbar Flutuar Barra de Ferramentas
Control Bar Options Opções da Barra de Controle
Tool Options Opções de Ferramenta
Object Options Opções de Objeto
Can't render this file because it contains an unexpected character in line 6 and column 47.
+17
View File
@@ -3497,6 +3497,19 @@ digits Malayalam Малаялам
Spot Color Objects Объекты с плашечными цветами
Pattern Objects Объекты с узорами
Gradient Objects Объекты с градиентами
Font Details Сведения о шрифтах
Linked Images Связанные изображения
Embedded Images Внедрённые изображения
Compound Paths Составные контуры
Text Objects Текстовые объекты
Placed Documents Размещённые документы
Symbol Instances Экземпляры символов
Gradient Meshes Градиентные сетки
Blends Переходы
Envelopes Оболочки
Intertwine Groups Группы переплетения
Opacity Masks Непрозрачные маски
Objects with Effects Объекты с эффектами
Spot Colors Плашечные цвета
Spot Colors… Плашечные цвета…
Spread: Разворот:
@@ -4192,6 +4205,10 @@ axis Both Оба
Dock Panel Прикрепить панель
Dock to Top Прикрепить сверху
Dock to Bottom Прикрепить снизу
Dock to Left Прикрепить слева
Dock to Right Прикрепить справа
Dock Toolbar Прикрепить панель инструментов
Float Toolbar Сделать панель инструментов плавающей
Control Bar Options Параметры панели управления
Tool Options Параметры инструмента
Object Options Параметры объекта
Can't render this file because it is too large.
+17
View File
@@ -3387,6 +3387,19 @@ digits Malayalam Malayalam
Spot Color Objects Objekt med dekorfärger
Pattern Objects Objekt med mönster
Gradient Objects Objekt med gradienter
Font Details Typsnittsdetaljer
Linked Images Länkade bilder
Embedded Images Inbäddade bilder
Compound Paths Sammansatta banor
Text Objects Textobjekt
Placed Documents Placerade dokument
Symbol Instances Symbolinstanser
Gradient Meshes Gradientnät
Blends Blandningar
Envelopes Kuvert
Intertwine Groups Sammanflätningsgrupper
Opacity Masks Opacitetsmasker
Objects with Effects Objekt med effekter
Spot Colors Dekorfärger
Spot Colors… Dekorfärger…
Spread: Spridning:
@@ -4071,6 +4084,10 @@ axis Both Båda
Dock Panel Docka panel
Dock to Top Docka överst
Dock to Bottom Docka nederst
Dock to Left Docka till vänster
Dock to Right Docka till höger
Dock Toolbar Docka verktygsfältet
Float Toolbar Gör verktygsfältet flytande
Control Bar Options Alternativ för kontrollfältet
Tool Options Verktygsalternativ
Object Options Objektalternativ
Can't render this file because it is too large.
+22 -13
View File
@@ -292,24 +292,33 @@ fn control_bar_panel_menu_labels_are_in_complete_catalogs() {
}
}
/// The titles of Document Info's Spot Color Objects, Pattern Objects and Gradient Objects
/// categories, which the panel, its menu and the Objects category's counts show.
/// Document Info's labels: every category title, which the panel and its menu show, every count
/// label of the Objects category, and the Document category's fixed row labels (the artboard rows
/// show artboard names and are left out).
#[test]
fn document_info_object_category_titles_are_in_complete_catalogs() {
fn document_info_labels_are_in_complete_catalogs() {
let mut session = vectorcraft_engine::Session::new();
session.execute("file.new", &serde_json::json!({"width": 100, "height": 100})).unwrap();
session.execute("shape.rectangle", &serde_json::json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
let info = session.execute("document.info", &serde_json::json!({})).unwrap();
let titles: Vec<&str> = info["sections"]
.as_array()
.unwrap()
.iter()
.filter(|s| matches!(s["id"].as_str(), Some("spotColors" | "patterns" | "gradients")))
.filter_map(|s| s["title"].as_str())
.collect();
assert_eq!(titles, ["Spot Color Objects", "Pattern Objects", "Gradient Objects"]);
let sections = info["sections"].as_array().unwrap();
let titles: Vec<&str> = sections.iter().filter_map(|s| s["title"].as_str()).collect();
let categories: Vec<&str> = vectorcraft_engine::cmd::CATEGORIES.iter().map(|&(_, title)| title).collect();
assert_eq!(titles, categories);
let mut labels = categories;
labels.extend(vectorcraft_engine::cmd::OBJECT_LABELS.iter().map(|&(_, label)| label));
let objects = sections.iter().find(|s| s["id"] == "objects").unwrap()["rows"].as_array().unwrap();
assert!(objects.iter().any(|r| r[0] == "Path Length"), "{objects:?}");
labels.push("Path Length");
let document = sections.iter().find(|s| s["id"] == "document").unwrap()["rows"].as_array().unwrap();
let artboards = document.iter().position(|r| r[0] == "Artboards").unwrap();
let names = artboards + 1..=artboards + document[artboards][1].as_str().unwrap().parse::<usize>().unwrap();
let fixed: Vec<&str> = document.iter().enumerate().filter(|(k, _)| !names.contains(k)).filter_map(|(_, r)| r[0].as_str()).collect();
assert_eq!(fixed.len(), 9, "{fixed:?}");
labels.extend(fixed);
for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) {
for title in &titles {
assert!(lang.catalog().plain(title).is_some(), "{} is missing {title}", lang.code);
for label in &labels {
assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code);
}
}
}
+17
View File
@@ -3286,6 +3286,19 @@ digits Malayalam Malayalam
Spot Color Objects Spot Renkli Nesneler
Pattern Objects Desenli Nesneler
Gradient Objects Degradeli Nesneler
Font Details Yazı Tipi Ayrıntıları
Linked Images Bağlantılı Görseller
Embedded Images Gömülü Görseller
Compound Paths Bileşik Yollar
Text Objects Metin Nesneleri
Placed Documents Yerleştirilen Belgeler
Symbol Instances Sembol Örnekleri
Gradient Meshes Degrade Örgüler
Blends Karışımlar
Envelopes Zarflar
Intertwine Groups İç İçe Geçme Grupları
Opacity Masks Opaklık Maskeleri
Objects with Effects Efektli Nesneler
Spot Colors Nokta Renkleri
Spot Colors… Nokta Renkleri…
Spread: Yayılma:
@@ -3955,6 +3968,10 @@ axis Both Her İkisi
Dock Panel Bağlantı İstasyonu Paneli
Dock to Top Üste yerleştir
Dock to Bottom Alta yerleştir
Dock to Left Sola yerleştir
Dock to Right Sağa yerleştir
Dock Toolbar Araç çubuğunu yerleştir
Float Toolbar Araç Çubuğunu Yüzer Yap
Control Bar Options Kontrol Çubuğu Seçenekleri
Tool Options Araç Seçenekleri
Object Options Nesne Seçenekleri
Can't render this file because it contains an unexpected character in line 5 and column 25.
+18
View File
@@ -3503,6 +3503,20 @@ effect Points Точки
Spot Color Objects Об’єкти з плашковими кольорами
Pattern Objects Об’єкти з візерунками
Gradient Objects Об’єкти з градієнтами
Font Details Відомості про шрифти
Linked Images Пов’язані зображення
Embedded Images Впроваджені зображення
Compound Paths Складені контури
Text Objects Текстові об’єкти
Placed Documents Розміщені документи
Symbol Instances Екземпляри символів
Gradient Meshes Градієнтні сітки
Blends Переходи
Envelopes Оболонки
Intertwine Groups Групи переплетення
Opacity Masks Маски непрозорості
Objects with Effects Об’єкти з ефектами
Pattern Swatches Зразки візерунків
Spot Colors Плашкові кольори
Spot Colors… Плашкові кольори…
Spread: Розворот:
@@ -4195,6 +4209,10 @@ axis Both Обидві
Dock Panel Прикріпити панель
Dock to Top Прикріпити вгорі
Dock to Bottom Прикріпити внизу
Dock to Left Прикріпити ліворуч
Dock to Right Прикріпити праворуч
Dock Toolbar Прикріпити панель інструментів
Float Toolbar Від’єднати панель інструментів
Control Bar Options Параметри панелі керування
Tool Options Параметри інструменту
Object Options Параметри об’єкта
Can't render this file because it is too large.
+18
View File
@@ -1012,6 +1012,10 @@ font-technology Variable Biến thiên
Dock Panel Neo bảng
Dock to Top Neo lên trên
Dock to Bottom Neo xuống dưới
Dock to Left Neo sang trái
Dock to Right Neo sang phải
Dock Toolbar Neo thanh công cụ
Float Toolbar Thả nổi thanh công cụ
Control Bar Options Tùy chọn thanh điều khiển
Tool Options Tùy chọn công cụ
Object Options Tùy chọn đối tượng
@@ -3851,6 +3855,20 @@ mark-style Japanese Kiểu Nhật
Spot Color Objects Đối tượng có màu đặc biệt
Pattern Objects Đối tượng có họa tiết
Gradient Objects Đối tượng có chuyển sắc
Font Details Chi tiết phông chữ
Linked Images Hình ảnh đã liên kết
Embedded Images Hình ảnh đã nhúng
Compound Paths Đường dẫn phức
Text Objects Đối tượng văn bản
Placed Documents Tài liệu đã đặt
Symbol Instances Thực thể ký hiệu
Gradient Meshes Lưới chuyển sắc
Blends Hòa trộn
Envelopes Envelope
Intertwine Groups Nhóm đan xen
Opacity Masks Mặt nạ độ mờ
Objects with Effects Đối tượng có hiệu ứng
Pattern Swatches Mẫu màu họa tiết
Spot Colors Màu đặc biệt
Spot Colors… Màu đặc biệt…
Spray Radius Bán kính phun
Can't render this file because it contains an unexpected character in line 204 and column 5.
+17
View File
@@ -3326,6 +3326,19 @@ digits Malayalam 马拉雅拉姆数字
Spot Color Objects 使用专色的对象
Pattern Objects 使用图案的对象
Gradient Objects 使用渐变的对象
Font Details 字体详细信息
Linked Images 链接的图像
Embedded Images 嵌入的图像
Compound Paths 复合路径
Text Objects 文本对象
Placed Documents 置入的文档
Symbol Instances 符号实例
Gradient Meshes 渐变网格
Blends 混合
Envelopes 封套
Intertwine Groups 交织编组
Opacity Masks 不透明度蒙版
Objects with Effects 使用效果的对象
Spot Colors 专色
Spot Colors… 专色…
Spread: 扩散:
@@ -5443,6 +5456,10 @@ axis Both 两者
Dock Panel 停放面板
Dock to Top 停放到顶部
Dock to Bottom 停放到底部
Dock to Left 停放到左侧
Dock to Right 停放到右侧
Dock Toolbar 停放工具栏
Float Toolbar 浮动工具栏
Control Bar Options 控制栏选项
Tool Options 工具选项
Object Options 对象选项
Can't render this file because it contains an unexpected character in line 2 and column 73.
+18
View File
@@ -4563,6 +4563,20 @@ digits Malayalam 馬來亞拉姆數字
Spot Color Objects 使用特別色的物件
Pattern Objects 使用圖樣的物件
Gradient Objects 使用漸層的物件
Font Details 字體詳細資訊
Linked Images 已連結的影像
Embedded Images 嵌入的影像
Compound Paths 複合路徑
Text Objects 文字物件
Placed Documents 已置入的文件
Symbol Instances 符號範例
Gradient Meshes 漸層網格
Blends 漸變
Envelopes 封套
Intertwine Groups 交織群組
Opacity Masks 不透明度遮色片
Objects with Effects 使用效果的物件
Pattern Swatches 圖樣色票
Spot Colors 特別色
Spot Colors… 特別色…
Spread: 擴散:
@@ -5272,6 +5286,10 @@ axis Both 兩者
Dock Panel 停駐面板
Dock to Top 停駐到頂部
Dock to Bottom 停駐到底部
Dock to Left 停駐到左側
Dock to Right 停駐到右側
Dock Toolbar 停駐工具列
Float Toolbar 浮動工具列
Control Bar Options 控制列選項
Tool Options 工具選項
Object Options 物件選項
Can't render this file because it contains an unexpected character in line 6 and column 47.
+18 -1
View File
@@ -564,7 +564,24 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{name: string} delete the toolbar made with New Toolbar called `name`, and the groups torn off it, from the current workspace, as Manage Toolbars' trash can does",
),
("window.toolbar.list", "List Toolbars", "", "{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots}]"),
(
"window.toolbar.dock",
"Dock Toolbar",
"",
"{name: string, side?: left|right, order?: int} dock the toolbar made with New Toolbar called `name` in the lane along the window's left or right edge (omitted: the edge it docked at last, the left at first), as Dock to Left and Dock to Right in its title bar's context menu and dropping its title bar on that edge do; `order` is its place in that edge's stack, 0 at the top (omitted: the end, or where it is when it is docked at that edge already); a bad `side` or `order` is an error and changes nothing; returns {toolbar, floating, side, order, pos}",
),
(
"window.toolbar.float",
"Float Toolbar",
"",
"{name: string, x?: number, y?: number} float the toolbar made with New Toolbar called `name` with its top-left corner at x, y in screen points (both or neither; omitted: where it floated last), as Float Toolbar in its title bar's context menu and dragging its title bar out of its lane do; returns {toolbar, floating, side, order, pos}",
),
(
"window.toolbar.list",
"List Toolbars",
"",
"{} the toolbars made with New Toolbar in the current workspace: [{name, shown, double, slots, floating, side, order}], `side` the edge it docks at (while floating, the edge it docked at last) and `order` its place in that edge's stack while docked (else null)",
),
("window.taskBar", "Contextual Task Bar", "", "{}"),
(
"window.pathfinder.compoundShapes",
+3 -2
View File
@@ -1435,8 +1435,9 @@ impl craft_ui::docking::DockContent<String> for PanelContent<'_> {
}
fn limits(&self, id: &String) -> craft_ui::docking::PanelLimits {
let min =
if id == CANVAS { egui::vec2(200.0 + crate::toolbar::docked_width(&self.app.ui), 120.0) } else { egui::vec2(PANEL_MIN_WIDTH, 80.0) };
// The canvas keeps room for Tools and the lane of toolbars docked beside it.
let beside = crate::toolbar::docked_width(&self.app.ui) + crate::custom_toolbars::beside_canvas_reserve(&self.app.ui);
let min = if id == CANVAS { egui::vec2(200.0 + beside, 120.0) } else { egui::vec2(PANEL_MIN_WIDTH, 80.0) };
craft_ui::docking::PanelLimits { min, ..Default::default() }
}
@@ -95,6 +95,28 @@ fn fit_to_artwork_bounds_fits_each_selected_artboard_to_its_own_art() {
assert_eq!(boards(&app), [rect(10.0, 10.0, 30.0, 40.0), was[1], rect(250.0, 10.0, 270.0, 50.0)]);
}
/// A batch the app runs (as the Actions panel plays an action) with a Fit to Artwork Bounds step
/// fits artboards 1 and 3, selected with the Artboard tool, and leaves artboard 2, the active one,
/// as it was.
#[test]
fn a_batchs_fit_to_artwork_bounds_step_fits_each_selected_artboard() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
for (x, h) in [(10, 30), (130, 20), (250, 40)] {
app.session.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": h})).unwrap();
}
app.session.execute("select.all", &json!({})).unwrap();
app.session.execute("paint.setStroke", &json!({"none": true})).unwrap();
let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let was = boards(&app);
app.select_tool("artboard");
select(&mut app, 1);
app.session.set_tool_option("selected", &json!([0, 2]));
app.run("command.batch", json!({"commands": [{"command": "artboard.fitToArt", "params": {}}]})).unwrap();
let rect = vectorcraft_geom::Rect::new;
assert_eq!(boards(&app), [rect(10.0, 10.0, 30.0, 40.0), was[1], rect(250.0, 10.0, 270.0, 50.0)]);
}
/// With the Artboard tool, Shift-click on a row selects the artboards from the last row clicked
/// without Shift to it and makes it the active one, Ctrl/Cmd-click adds its artboard to the
/// tool's selection or takes it out (#1139), a plain click selects it alone, and every selected
+11 -2
View File
@@ -868,7 +868,8 @@ impl FloatingFlyout {
}
/// A toolbar made with Window › Toolbars › New Toolbar (`window.toolbar.new`): it floats on its
/// own, filled with tools from the All Tools drawer, and is kept with the workspace it was made in.
/// own or docks along the window's left or right edge, filled with tools from the All Tools drawer,
/// and is kept with the workspace it was made in.
/// The groups torn off it are kept with it (`floating`), so the Tools panel's strips
/// (`UiState::floating_flyouts`) hold none of them.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -881,8 +882,16 @@ pub struct CustomToolbar {
/// It shows (Window › Toolbars › its name toggles it).
#[serde(default = "yes")]
pub shown: bool,
/// Top-left corner in screen points.
/// Top-left corner in screen points while it floats; while it is docked, where it floated last.
pub pos: [f32; 2],
/// Its place in the stack of toolbars docked along one of the window's edges (0 at the top),
/// while it is docked there; none while it floats at `pos`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dock: Option<u32>,
/// It docks along the window's right edge, not the left: the edge it is docked at, or while it
/// floats the edge it docked at last.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub dock_right: bool,
/// The tool each slot of several tools shows, chosen last (keyed by the slot's first tool).
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub slot_tool: std::collections::BTreeMap<String, String>,
+2
View File
@@ -145,6 +145,8 @@ pub(crate) fn show_beside_canvas(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.ui.toolbar_pos.is_none() && (app.ui.tools_beside_canvas || app.ui.toolbar_right) {
show(app, ui);
}
// The lane where toolbars made with New Toolbar dock on the left, right of Tools.
crate::custom_toolbars::lane_beside_canvas(app, ui);
}
/// Is the Tools panel docked on the right, between the canvas and the panels?
+8 -1
View File
@@ -46,6 +46,13 @@ pub(crate) fn escape_cancelled_move(ctx: &egui::Context) -> bool {
ctx.data(|d| d.get_temp::<u64>(escape_cancel_id())) == Some(ctx.cumulative_frame_nr_for(ctx.viewport_id()))
}
/// This frame's Escape put a moved bar back ([`escape_cancelled_move`]): a toolbar made with New
/// Toolbar ([`crate::custom_toolbars::cancel_move_on_escape`]) as well as the Tools panel.
pub(crate) fn mark_escape_cancelled(ctx: &egui::Context) {
let frame = ctx.cumulative_frame_nr_for(ctx.viewport_id());
ctx.data_mut(|d| d.insert_temp(escape_cancel_id(), frame));
}
/// The strip along the canvas's left edge where the Tools panel docks while Keep Tools Beside the
/// Canvas is on, as last laid out.
pub(crate) fn tools_zone_id() -> Id {
@@ -194,7 +201,7 @@ pub fn track(app: &mut VectorcraftApp, ctx: &egui::Context) {
}
/// The `x`, `y` params: a top-left corner in screen points, if given.
fn position(p: &Value) -> Result<Option<Pos2>, String> {
pub(crate) fn position(p: &Value) -> Result<Option<Pos2>, String> {
let coord = |k: &str| match p.get(k) {
None | Some(Value::Null) => Some(None),
Some(v) => v.as_f64().filter(|f| f.abs() < 1e6).map(|f| Some(f as f32)),
+4 -1
View File
@@ -417,7 +417,10 @@ button (Add Tool…) opens a menu of every tool under the drawer's headings: a c
{tool, toolbar}`; the tools already in the toolbar are dimmed under their headings. The drawer has no Show section
there. `window.floatTools {tool, toolbar}` floats one of its groups, and a group torn off it shows and hides with
it. `window.toolbar.list` returns the toolbars (`ui.custom_toolbars` in `ui.inspect`: name, slots, shown flag,
two-column flag, top-left corner, the groups torn off it). They are kept with the workspace they were made in:
two-column flag, top-left corner, the groups torn off it, and `dock` and `dock_right` while docked or once docked).
`window.toolbar.dock {name, side?, order?}` docks a toolbar in the lane along the window's left or right edge, and
`window.toolbar.float {name, x?, y?}` floats it again; dropping its title bar on an edge or dragging it out of its
lane does the same (see the docking section in `docs/mcp.md`). They are kept with the workspace they were made in:
switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new
workspace with a copy of them.
+3 -2
View File
@@ -684,8 +684,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Done:** custom document ruler origin (#1212): corner drag with preview, double-click reset to the active artboard, relative X/Y inputs and native save/reopen.
- **Done:** View › Rulers › Change to Global / Artboard Rulers (`view.globalRulers`, Cmd+Alt+R): artboard rulers, a new document's, count from the active artboard, each artboard with its own zero point; rulers, X/Y fields and guide readouts follow the mode, which is saved with the document. Estimate unchanged.
- **Done (#2849):** View › Rulers › Show Video Rulers (`view.videoRulers`): the rulers show and count the active artboard in video pixels from its top-left corner, a pixel as many points wide as the artboard's Video Ruler Pixel Aspect Ratio and one point tall ([public source](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/set-video-display-options-for-artboards.html)); Hide Video Rulers returns them to the General unit and the ruler origin. Shift-snapping a new guide to ruler ticks still uses the General unit's ticks. Estimate unchanged.
- **Partial:** custom toolbars (#1759): Window › Toolbars › New Toolbar makes them, kept with the workspace they
were made in, and Window › Toolbars › Manage Toolbars renames, copies and deletes them; docking them is missing.
- **Done:** custom toolbars (#1759): Window › Toolbars › New Toolbar makes them, kept with the workspace they
were made in, and Window › Toolbars › Manage Toolbars renames, copies and deletes them; they dock in lanes along
the window's left and right edges (`window.toolbar.dock`, `window.toolbar.float`).
Inside the estimate below.
- **Done (#1753):** a saved workspace keeps the width of the dock column.
- **Done (#4135):** floating panels open in OS windows of their own on the desktop, so they can sit on another monitor; on the web and on Wayland they float inside the window.
+43 -2
View File
@@ -2677,6 +2677,43 @@ kept with the workspace, and built-in workspaces and workspaces saved without it
{"name":"invoke_menu","arguments":{"command":"window.toolsBesideCanvas","params":{"on":true}}}
```
## Docking toolbars made with New Toolbar
A toolbar made with New Toolbar floats when it is made. `window.toolbar.dock {name, side?, order?}` (Dock to Left and
Dock to Right in the context menu of the toolbar's title bar, remote mode, `invoke_menu`) docks it in a lane along the
window's left or right edge. On the left, the lane is right of the Tools panel when the Tools panel is docked at the
window's edge. With Keep Tools Beside the Canvas on and the Tools panel docked on the left, the lane is right of the
Tools panel beside the canvas, and dropping a title bar on the Tools panel or on the lane docks the toolbar there. `side` is `left` or `right` (`start` and `end` also work); without it, the toolbar docks at the edge it
docked at last, or at the left the first time. Toolbars docked at one edge stack from the top. `order` is the
toolbar's place in that stack, 0 at the top, from 0 to the number of other toolbars docked there; without it, the
toolbar goes at the end, or stays where it is when it is already docked at that edge. Each toolbar takes an equal
share of the lane's height and its tools scroll in it, and the lane is as wide as its widest toolbar. When the lane
is too short to give each toolbar 88 points of height, the stack wraps into more columns, left to right, and the lane
widens, so no toolbar covers another. A lane takes at most half the width the canvas and panels would have (beside
the canvas, it also leaves the canvas at least 200 points, and the canvas keeps room for one column); when that
many columns still give a toolbar less than 88 points, the toolbars in those columns show only their title bars, which
still float, dock and show the context menu. A column too short for all of its title bars shows as many as fit, and
the mouse wheel over the column scrolls through the others, one toolbar per notch.
`window.toolbar.float {name, x?, y?}` (Float Toolbar in the same menu) floats it with its top-left corner at `x`, `y`
in screen points, or where it floated last when both are omitted. Both commands answer
`{toolbar, floating, side, order, pos}`: `side` is the edge the toolbar docks at (while it floats, the edge it docked
at last), `order` its place in that edge's stack (null while it floats) and `pos` where it floats (while it is docked,
where it floated last). A missing or unknown name, a `side` other than left or right, an `order` that is not a whole
number in range, or only one of `x` and `y` is an error and changes nothing. `window.toolbar.list` reports `floating`,
`side` and `order` for each toolbar.
With the pointer, dropping a floating toolbar's title bar on the window's left or right edge, or on that edge's lane,
docks it at the end of that edge's stack; the target lights up while the title bar is dragged over it. Dragging a
docked toolbar's title bar out of its lane floats it under the pointer. Escape, or the window losing focus, during
the drag puts the toolbar back where it was. Hiding a docked toolbar keeps its place, renaming it keeps its place, a
copy made with Manage Toolbars' + floats, and deleting one closes up the stack. Placement is kept with the workspace.
Toolbars saved before docking existed load floating. The lanes, the edge targets and the stacking are VectorCraft's
own layout rules.
```json
{"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}}
```
## Learn panel
Window › Learn and the Explore tutorials button beside the search icon at the right end of the app bar show and hide
@@ -5447,8 +5484,12 @@ the selected artboards (those the Artboard tool has selected, else the active on
`artboard.fitToSelection` calls it runs without `index`. Both include MCP's `run_command` calls in remote mode. The
Artboards panel menu's Fit to Artwork Bounds also passes the selected artboards. A batch passes its `artboard` on to
each of their steps that names no `index`, as the step's `index`. When the document a step runs in has no artboard at
that index, the step gets that document's last artboard. An action recorded in the Actions panel leaves `index` and
`indices` out of these steps, and they resize the artboard that is active when the action plays.
that index, the step gets that document's last artboard. An `artboard.fitToArt` step that names neither `index` nor
`indices`, while the Artboard tool is chosen with several artboards selected when the step runs, gets those artboards
as its `indices` instead, and the batch's journal entry records them, so a replay of the journal fits the same
artboards. A step's own `index` or `indices` is kept. An action recorded in the Actions panel leaves `index` and
`indices` out of these steps: when the action plays, Fit to Artwork Bounds resizes the artboards the Artboard tool then
has selected (two or more), else the active artboard, and Fit to Selected Art resizes the active artboard.
```json
{"name":"run_command","arguments":{"command":"object.align","params":{"horizontal":"left","to":"artboard","artboard":1}}}
+19 -2
View File
@@ -850,6 +850,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Window › Toolbars › New Toolbar… and New Toolbar… in the All Tools drawer's menu ask for a name and make a blank toolbar that floats on its own, moved by its title bar and listed under Window › Toolbars, whose item shows or hides it. The title bar's × hides it, and its double arrow shows its tools in one column or two. Its ••• button opens the All Tools drawer beside it, and tools dragged from the drawer fill it. The toolbars are kept with the workspace they were made in: switching workspaces shows that workspace's toolbars, Reset Workspace keeps them, and New Workspace starts the new workspace with a copy of them (<https://helpx.adobe.com/illustrator/using/tools.html>; `window.toolbar.new`, `window.toolbar.custom`, the `toolbar` param of `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset`; `tools_added_to_a_new_toolbar_survive_a_workspace_reload`).
- A toolbar made with New Toolbar has a + button (Add Tool…) above its ••• button. A click on it, or Enter while it has the keyboard focus, opens a menu of every tool under the All Tools drawer's headings, without the drawer: a tool picked there goes at the end of that toolbar, and the tools already in it are dimmed. Under Remove Tool, the menu lists the toolbar's tools, and a click takes one out. This menu is VectorCraft's own way to fill a toolbar without a drag (`toolbar.addTool` and `toolbar.removeTool` with `toolbar`; `the_add_tool_menu_fills_a_new_toolbar_without_a_drag`).
- Window › Toolbars › Manage Toolbars… and Manage Toolbars… in the All Tools drawer's menu open a dialog that lists the toolbars made with New Toolbar: a new name typed for the selected toolbar renames it, + copies it with its tools (with none selected, + makes a blank toolbar), and the trash can deletes it. Each change shows under Window › Toolbars and stays in the workspace (<https://helpx.adobe.com/illustrator/using/tools.html>; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete`; `manage_toolbars_renames_duplicates_and_deletes`).
- A toolbar made with New Toolbar docks in a lane along the window's left or right edge when its title bar is dropped on that edge, or with Dock to Left and Dock to Right in the title bar's context menu. Toolbars docked at one edge stack from the top, each with its share of the lane's height, and the lane is as wide as its widest toolbar; a lane too short for its stack wraps it into more columns, up to half the window's width, and past that the toolbars show only their title bars, which the mouse wheel scrolls through when even they do not fit. Dragging the title bar out of the lane, or Float Toolbar, floats it again, and Escape during the drag puts it back. Hiding and renaming keep its place, and the workspace keeps it. New toolbars still start floating. The lanes and the stacking are VectorCraft's own rules (#1759; `window.toolbar.dock`, `window.toolbar.float`; `toolbars_dock_and_float_by_their_commands`, `docked_toolbars_stack_in_lanes_along_the_window_edges`, `a_title_bar_dropped_on_an_edge_docks_the_toolbar`).
- Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge; the canvas's left edge then also docks a floating Tools panel, and workspaces keep the setting. Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_redock_at_the_targets_of_the_chosen_placement`).
- Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md).
- Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged.
@@ -1069,7 +1070,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them.
- **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html).
- **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile and arrowheads turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`).
- **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step.
- **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step.
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command, the Eyedropper, a graphic style, Default Fill and Stroke or Swap Fill and Stroke, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph or Appearance controls, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485).
An Eyedropper pick that includes transparency and leaves a mark's top fill or stroke row without paint, or removes that row when the source has no row of that kind, where that row had paint before, also replaces the opacity and blend mode the graph keeps for that kind of row in the series; a row that had no paint before the pick leaves them as they are.
- **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete.
@@ -1161,8 +1162,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
With Align to Artboard chosen, the Align panel's Distribute Objects and Distribute Spacing buttons use the active artboard (`object.distribute` and `object.distributeSpacing` with `to: "artboard"` and `artboard`). The first object's left or top edge goes to the artboard's left or top edge, and the last object's right or bottom edge goes to the artboard's right or bottom edge. Distribute Objects spaces the other objects evenly by its button's line, and two objects are enough. Distribute Spacing makes the gaps between the objects equal. With anchor points selected, the buttons space the points among themselves and do not use the artboard. When an action plays, its Distribute Objects and Distribute Spacing steps with Align to Artboard use the artboard that is active then.
With a key object, the Align panel's Distribute Objects buttons use the Distribute Spacing value (`object.distribute {spacing}`): the key object, or the compound path or selected group that contains it, stays in place, and the objects' left edges, centers or right edges (top edges, centers or bottom edges) end up that far apart, outward from the key object's, in their order. With the field's default value of 0, a click puts every object on the key object's line (behavior reference: [Ask Mordy: Distributing Objects](http://rwillustrator.blogspot.com/2008/01/ask-mordy-distribute.html)).
Choosing the Artboard tool (Shift+O, its toolbar button, Edit Artboards in Properties or Document Setup, or the Artboards panel menu's Artboard Options…) starts it on the active artboard: the canvas outlines that artboard, and Delete, Cut, Copy, the Transform panel and Artboard Options act on it.
Object › Artboards › Fit to Selected Art resizes the active artboard (`artboard.fitToSelection {index}`). It used to resize artboard 1 whichever artboard was active. When an action plays, its Fit to Artwork Bounds and Fit to Selected Art steps that name no artboard resize the artboard that is active then.
Object › Artboards › Fit to Selected Art resizes the active artboard (`artboard.fitToSelection {index}`). It used to resize artboard 1 whichever artboard was active. When an action plays, its Fit to Selected Art steps that name no artboard resize the artboard that is active then, and its Fit to Artwork Bounds steps resize the artboards selected then.
Object › Artboards › Fit to Artwork Bounds and the Artboards panel menu's Fit to Artwork Bounds fit each selected artboard (those the Artboard tool has selected, else the active one) to the art on it, as the public [Use the artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) page describes (`artboard.fitToArt {indices}`). An object partly on an artboard counts for each artboard it overlaps, and an artboard with no art on it keeps its size and place. They used to fit the active artboard to all the art in the document.
A Fit to Artwork Bounds step of a batch run from the app (`command.batch`), including an action played from the Actions panel, fits each artboard the Artboard tool has selected when the step runs, as the command does on its own and as the [help page](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) describes. A step's own `index` or `indices` is kept, and the journal records the artboards the step fitted, so a replay fits the same ones. The step used to fit only the active artboard.
The Artboards panel menu's Duplicate Artboards copies each selected artboard (those the Artboard tool has selected, else the active one) with its art, in one undo step, and the copies are then selected, as the public [Use the artboard context menu](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/use-artboard-context-menu.html) page describes. With the Artboard tool, Copy and Cut take every selected artboard with its art, as the public [Cut, copy, and paste artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/cut-copy-and-paste-artboards.html) page describes, and Paste brings them all back in one undo step (`artboard.duplicate`, `artboard.copy` and `artboard.cut` with `indices`). The copies keep their places relative to each other, together right of the last artboard. All three used to act on the active artboard only.
With the Artboard tool selecting several artboards, Paste in Place, Paste in Front and Paste in Back put a copy of the copied art on each, where it was on the artboard it was copied from, in one undo step, as the public [Cut, copy, and paste artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/cut-copy-and-paste-artboards.html) page describes (`artboards` on the three commands). Art copied from no artboard keeps its place on the first selected artboard and its offset to it on the others, and an `artboard` or `artboards` index the document does not have is an error; these rules are VectorCraft's own. The three commands used to paste one copy, on the active artboard, and an `artboard` index the document did not have pasted the art where it was.
A replay of the journal repeats a Cut or Copy made with the Artboard tool on the artboards it took (`edit.cut` and `edit.copy` record `selectedArtboards` and `art`), whichever tool is chosen in the new session and whatever is selected there. A recorded action follows the tool chosen when it plays. The replay used to act on the objects selected then, or stop with nothing selected. This rule is VectorCraft's own.
@@ -1192,6 +1194,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Extrude & Bevel and Inflate treat strokes as outlined: each visible stroke builds a solid from its outline in its own paint beside the top fill's ([three-d.md](three-d.md#fills-and-strokes)).
- A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`.
- With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`.
- When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_draws_its_faces_in_one_order`, `solids::tests::a_depth_cycle_keeps_the_cap_last`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`.
- Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715).
- Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)).
- Extrude & Bevel and Inflate build detailed shapes: each solid takes up to 65,536 outline points and 163,840 faces (VectorCraft's own limits, was 2,048 points and 32,768 faces), counted before any point is sampled; when the faces do not fit, every curve takes fewer pieces, down to 4. A closed path of 2,000 curves extrudes with a bevel and inflates, and paths of 5,000 and 10,000 curves build at the default settings (`crates/three-d/src/solid/tests_limits.rs`).
@@ -1221,6 +1224,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Nearly unchanged appearance is expected when reducing points. The checklist is partial, without raising scores.
Simplify and Add Anchor Points record no undo step when they change no path, and a path they leave as it is keeps its live shape.
Simplify keeps its result within the tolerance of the path, on long arcs and on paths of many anchors alike (`fit.rs` tests `no_fitted_piece_is_farther_than_the_tolerance` and `long_arcs_stay_within_the_tolerance`). A closed subpath that refits to one curve is dropped, so this does not hold for it. A segment that would need more than 65,536 samples at that tolerance stays as it is, and with Convert to Straight Lines it becomes evenly spaced lines instead, up to 65,536, which past the limits in `docs/mcp.md` (Simplify) can be farther than the tolerance from the segment.
Simplify, Object › Path › Smooth, the Smooth tool and freehand strokes (`path.freehand`) turn a refitted curve into a straight line only when the line runs within 0.5° of the directions the path arrives and leaves along, so no corner appears where a curve meets a line; a nearly straight piece that would turn more stays a flat curve (`ops.rs` test `simplify_turns_a_curve_into_a_line_only_where_the_joins_stay_smooth`).
The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines.
Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK.
With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`.
@@ -1456,6 +1460,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Document Info's Gradient Objects category lists the objects whose fill or stroke is a gradient, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as the count of objects with gradient fills or strokes. Each object is listed by name with the gradients it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "gradients"}`, `gradientObjects`). Naming a linked gradient by its swatch and any other gradient by its kind, and leaving out paint that draws nothing by the rules Pattern Objects follows, gradient swatches no art uses, gradient meshes and gradients drawn by effects, are VectorCraft's own rules. Objects counts the listed objects as Gradient Objects. Test: `cmd::docinfo::tests::info_lists_the_gradient_objects` (vectorcraft-engine).
Document Info's Spot Color Objects category lists the objects that use spot colors, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as objects using spot color separations. Each object is listed by name with the spot colors it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "spotColors"}`, `spotObjects`). Taking a solid color or a gradient stop linked to a spot swatch at a tint above 0 and a grayscale image colorized with one, leaving out process colors that look the same, Registration, gradients whose stops are all at an opacity of 0, fills and strokes at an opacity of 0, paint that draws nothing by the rules Pattern Objects follows, spot swatches no art uses and spot colors inside patterns, symbols, opacity masks, effects and placed files, are VectorCraft's own rules. Objects counts the listed objects as Spot Color Objects. Tests: `cmd::docinfo::tests::info_lists_the_spot_color_objects`, `spot_color_objects_take_colorized_images_and_skip_clear_gradients` and `spot_color_objects_skip_clear_fills_and_strokes` (vectorcraft-engine).
Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`.
Document Info's category menu and headings show every category title in the interface language, Font Details, Linked Images and Embedded Images included, and the Objects category shows every count label in it too: Compound Paths, Text Objects, Placed Documents, Symbol Instances, Gradient Meshes, Blends, Envelopes, Intertwine Groups, Opacity Masks and Objects with Effects. The Document category's Pattern Swatches row and the Objects category's Path Length row are translated in every catalog that has every menu label. `document.info` and the saved report keep the English labels. Showing these labels in the interface language is VectorCraft's own rule. Test: `i18n::tests::document_info_labels_are_in_complete_catalogs` (vectorcraft-ui-egui).
The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`).
A rename in Brush Options and Delete Brush change every stroke that paints with the brush: in the layers and opacity masks, symbols, graph designs, pattern tiles, graphic styles and the art of other brushes. A rename gives those strokes the new name, and Delete Brush makes them plain strokes, in one undo step.
A scatter, art or pattern brush dragged from the Brushes panel onto an empty part of the canvas places a copy of its art there to edit, as the [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html) page describes (`brush.placeArt`). The copy is centered where it is dropped. A pattern brush comes out as its tiles in a row, 10 pt apart, each in a group named for its tile, with an unpainted rectangle at the back of a tile that has a repeat frame. The centering and the tile layout are VectorCraft's own rules. Evidence: `tests::brushsym::place_art_puts_a_copy_of_the_brush_art_where_it_is_dropped`, `tests::brushsym::pattern_brushes_place_their_tiles_in_a_row` (vectorcraft-engine), `canvas::tests::a_brush_with_art_dropped_off_the_art_places_a_copy_of_its_art_there` (vectorcraft-ui-egui).
@@ -2192,6 +2197,18 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s
`live_paint_bucket_drag_rejects_invalid_points_atomically` covers invalid command input.
Behaviour source: [Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html).
Scores and estimates unchanged.
- **Live Paint Bucket cursors:** over a face a click fills (of a Live Paint group, or a region of
the selected paths) the cursor is a filled paint bucket, over an edge it paints it is a brush,
and where a click paints nothing it is an empty bucket. It follows Paint Fills, Paint Strokes
and Shift, and shows with Highlight off too; Alt still shows the Eyedropper, and Use Precise
Cursors shows the crosshair. The drawings are VectorCraft's own. With a Live Paint group and
ordinary paths selected, a region of the paths outside the group is highlighted and shows the
filled bucket, as a click there fills it. Tests:
`bucket_cursor_shows_what_a_click_paints`, `bucket_cursor_fills_a_region_of_the_selected_paths`,
`bucket_fills_a_region_of_a_selection_that_mixes_a_group_and_paths`,
`the_live_paint_bucket_shows_a_bucket_or_a_brush`. Behavior source:
[the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html).
The cursor swatch preview is not built. Scores and estimates unchanged.
## Revision history
+19 -7
View File
@@ -117,11 +117,20 @@ The rest is our reading:
each side face of the fill's solid that is turned toward the viewer is drawn before every face of the same
shape's strokes, turned toward the viewer, whose bounds overlap it, so the stroke's walls cover the fill's walls
at concave corners. This applies to strokes on closed paths without dashes, a width profile or a brush, painted
with a solid color or a gradient without transparent stops; with other strokes, and without caps, the faces keep
their depth order. Otherwise
each solid is drawn on its own with its opacity and blending, the lower item's first. With a light that is not
white, each solid is also drawn on its own when one of them is a puffed, shaded Inflate surface in a solid color
(drawn as one composite) or is painted with a gradient that has transparent stops (drawn with an opacity mask).
with a solid color or a gradient without transparent stops, under Extrude & Bevel (both kinds). Under Inflate
the fill can rise in front of such a stroke, so it is drawn like the other strokes. Other strokes (dashed, with a
width profile or a brush, on an open subpath, or in a paint that may show through) leave parts of the fill's edge
uncovered, such as the gaps between dashes. Each face of such a stroke that passes through a face of the fill's
solid, or through a face of another of the shape's strokes, where the two overlap in the drawing is cut where
their depths meet, and the faces of the shape's fill and strokes that overlap are drawn in the order of their
depths where they overlap, with caps on or off. A fill wall in a gap stays in its own depth order. Inflate's
curved surfaces follow this only as closely as their flat facets do. A solid painted with a gradient that has
transparent stops under a light that is not white is drawn with an opacity mask: its faces keep their places in
this order, in runs that each carry the mask, and so do its graphics. A member of a 3D group with its own opacity
mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when
they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the
lower item's first. With a light that is not white, each solid is also drawn on its own when one of them is a
puffed, shaded Inflate surface in a solid color (drawn as one composite).
- The solids turn, twist and taper about the center of the bounds of all their shapes, Inflate's grid covers
those bounds, and with Perspective one eye sees every solid. A stroke too narrow to hold a point of Inflate's
grid stays flat.
@@ -150,8 +159,11 @@ them all. The members stay editable: moving or editing one reshapes the solids.
inside the 3D group applies to the solids of that group's members together. An opacity mask on
a member masks its solids, and one on a group inside the 3D group masks the solids of that group's members
together. The mask stays where it is on the page; it does not turn with the solids. A disabled mask is ignored.
- When a member, or a group inside the 3D group, has an opacity mask or a blending mode other than Normal, each
solid is drawn on its own, the backmost member's first, as when a solid is transparent.
- When a member, or a group inside the 3D group, has an opacity mask or a blending mode other than Normal, the
members' faces are not drawn in one shared order. Each member whose fills and strokes are opaque with Normal
blending draws their faces in one order of its own inside its masks and blending modes, as described under
[Fills and strokes](#fills-and-strokes). Otherwise each solid is drawn on its own, the backmost member's first, as
when a solid is transparent.
- When every solid is opaque, all members' faces are drawn in one back-to-front order; otherwise each solid is drawn
on its own, the backmost member's first.
- Hidden members and guides are left out. A group holding a live object other than a blend (an envelope, a mesh, a
+2 -1
View File
@@ -161,7 +161,8 @@ tools, never checked side by side) isn't captured row by row.
| Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) |
| Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge |
| Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it |
| Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Live Paint Bucket, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed |
| Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview |
| Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed |
| Blob Brush and Eraser: the tip's outline at the pointer | done | before a press and while painting, the outline of the tip (its size, angle and roundness, at the zoom) follows the pointer, black on a white halo, round a small centre dot; `[` / `]` and Tool Options change it at once; precise cursors (Caps Lock) show only the crosshair; it goes when the pointer leaves the canvas, while Cmd/Ctrl lends a selection tool and while Alt lends the Blob Brush the Smooth tool (#4977); `crates/tools/src/draw2/gesture.rs` and its tests While the button is down a round Blob Brush shows the outline of the area it will add, rounded at both ends, not a line as wide as the brush that ends square (#4343). |
| Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) |
| Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` |