mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 13:27:56 +00:00
Merge main into feat/proof-setup-customize
This commit is contained in:
@@ -190,18 +190,34 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions,
|
||||
|
||||
/// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither,
|
||||
/// transparency and matte; `o.reduction` sets only the distance weights, and `o.colors` is not
|
||||
/// used. Only the first 255 colors of `palette` are used, leaving room for the transparent entry.
|
||||
/// Entries no pixel uses are left out.
|
||||
/// used. Only the first 256 colors of `palette` are used, or the first 255 when a pixel becomes
|
||||
/// transparent, leaving room for the transparent entry. Entries no pixel uses are left out.
|
||||
pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed {
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
let colors = opaque_colors(px, o, false);
|
||||
let mut palette: Vec<[u8; 3]> = palette.iter().take(255).copied().collect();
|
||||
let has_clear = o.transparency && px.iter().any(|p| p[3] < 128);
|
||||
let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect();
|
||||
if palette.is_empty() {
|
||||
palette.push(o.matte.unwrap_or([255; 3]));
|
||||
}
|
||||
finish(px, &colors, width, height, &palette, o, o.dither)
|
||||
}
|
||||
|
||||
/// For each pixel of `rgba`, the entry of `palette` nearest its color, as [`quantize_to`] measures
|
||||
/// it (the matte, transparency and `o.reduction`'s distance weights) without dither; `None` for a
|
||||
/// pixel that becomes transparent, and for every pixel when `palette` is empty.
|
||||
pub fn nearest_entries(rgba: &[u8], o: &PaletteOptions, palette: &[[u8; 3]]) -> Vec<Option<usize>> {
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
let colors = opaque_colors(px, o, false);
|
||||
let pal: Vec<[f32; 3]> = palette.iter().map(|c| c.map(f32::from)).collect();
|
||||
let index = PaletteIndex::new(&pal, o.reduction.weights());
|
||||
colors
|
||||
.iter()
|
||||
.zip(px)
|
||||
.map(|(c, p)| if pal.is_empty() || (o.transparency && p[3] < 128) { None } else { Some(index.nearest(c.map(f32::from))) })
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The color of each pixel when opaque: blended over the matte, and gray when `gray`.
|
||||
fn opaque_colors(px: &[[u8; 4]], o: &PaletteOptions, gray: bool) -> Vec<[u8; 3]> {
|
||||
let matte = o.matte.unwrap_or([255; 3]);
|
||||
|
||||
@@ -102,11 +102,18 @@ fn a_given_palette_keeps_the_entries_pixels_use() {
|
||||
assert_eq!(ix.transparent, Some(0));
|
||||
assert_eq!(ix.palette[1..], [[255, 0, 0], [0, 0, 255]], "unused entries left out, the order kept");
|
||||
assert_eq!(ix.indices, [1, 2, 0, 1]);
|
||||
// At most 255 of the given colors are used, leaving room for the transparent entry.
|
||||
// With no transparent pixel all 256 of the given colors can be used; with one, the first 255
|
||||
// leave room for the transparent entry.
|
||||
let many: Vec<[u8; 3]> = (0..300u32).map(|i| [(i % 256) as u8, (i / 256) as u8, 0]).collect();
|
||||
let all = image(256, 2, |x, y| [x as u8, y as u8, 0]);
|
||||
let ix = quantize_to(&all, 256, 2, &o, &many);
|
||||
assert!(ix.palette.len() <= 255 && ix.palette.iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len());
|
||||
assert!(ix.palette.len() == 256 && ix.palette.iter().all(|c| many[..256].contains(c)), "{}", ix.palette.len());
|
||||
assert!(ix.palette.contains(&many[255]), "the 256th color is used");
|
||||
let mut clear = all.clone();
|
||||
clear[3] = 0;
|
||||
let ix = quantize_to(&clear, 256, 2, &o, &many);
|
||||
assert_eq!(ix.transparent, Some(0));
|
||||
assert!(ix.palette.len() <= 256 && ix.palette[1..].iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -80,14 +80,19 @@ fn lossy_makes_runs_and_smaller_gifs() {
|
||||
let px = image(96, 64, |x, y| [(x * 2 + y) as u8, (y * 3) as u8, ((x * y) % 255) as u8]);
|
||||
let ix = quantize(&px, 96, 64, &PaletteOptions { colors: 64, dither: Dither::Diffusion, ..Default::default() });
|
||||
let mut lossy_ix = ix.clone();
|
||||
lossy(&mut lossy_ix, &px, 80);
|
||||
lossy(&mut lossy_ix, &px, 80, &[]);
|
||||
let runs = |ix: &Indexed| ix.indices.windows(2).filter(|w| w[0] != w[1]).count();
|
||||
assert!(runs(&lossy_ix) < runs(&ix));
|
||||
let size = |ix: &Indexed| gif::encode(ix, false).unwrap().len();
|
||||
assert!(size(&lossy_ix) < size(&ix), "{} vs {}", size(&lossy_ix), size(&ix));
|
||||
let mut none = ix.clone();
|
||||
lossy(&mut none, &px, 0);
|
||||
lossy(&mut none, &px, 0, &[]);
|
||||
assert_eq!(none, ix);
|
||||
// A fixed entry keeps its pixels and takes no others.
|
||||
let fixed: Vec<u8> = (0..ix.palette.len()).filter_map(|i| u8::try_from(i).ok()).collect();
|
||||
let mut kept = ix.clone();
|
||||
lossy(&mut kept, &px, 100, &fixed);
|
||||
assert_eq!(kept, ix);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -83,19 +83,24 @@ pub fn to_transparent(ix: &mut Indexed, mapped: impl Fn(usize) -> bool) -> Vec<O
|
||||
|
||||
/// Lossy GIF compression: a pixel takes the entry of the pixel left of it when that entry is
|
||||
/// within `amount` (0–100) of its own colour in `rgba` (the straight pixels it was reduced from).
|
||||
/// Longer runs of one index compress better in a GIF, at the cost of some noise.
|
||||
pub fn lossy(ix: &mut Indexed, rgba: &[u8], amount: u8) {
|
||||
/// Longer runs of one index compress better in a GIF, at the cost of some noise. No pixel moves
|
||||
/// into or out of the transparent entry or an entry in `fixed`.
|
||||
pub fn lossy(ix: &mut Indexed, rgba: &[u8], amount: u8, fixed: &[u8]) {
|
||||
let w = ix.width as usize;
|
||||
if amount == 0 || w == 0 || rgba.len() != ix.indices.len() * 4 {
|
||||
return;
|
||||
}
|
||||
// Up to 64 levels apart in each channel at 100.
|
||||
let limit = (f32::from(amount.min(100)) / 100.0 * 64.0).powi(2) * 3.0;
|
||||
let mut held = [false; 256];
|
||||
for i in fixed.iter().chain(&ix.transparent) {
|
||||
held[usize::from(*i)] = true;
|
||||
}
|
||||
let px = rgba.as_chunks::<4>().0;
|
||||
for (row, src) in ix.indices.chunks_mut(w).zip(px.chunks(w)) {
|
||||
for x in 1..row.len() {
|
||||
let (prev, cur) = (row[x - 1], row[x]);
|
||||
if prev == cur || ix.transparent.is_some_and(|t| t == prev || t == cur) {
|
||||
if prev == cur || held[usize::from(prev)] || held[usize::from(cur)] {
|
||||
continue;
|
||||
}
|
||||
let (Some(c), Some(p)) = (src.get(x), ix.palette.get(prev as usize)) else { continue };
|
||||
|
||||
@@ -64,10 +64,13 @@ use crate::{Frame, Renderer, blend_mode, fill_rule, paint};
|
||||
mod bounds;
|
||||
mod entries;
|
||||
mod pixels;
|
||||
mod placement;
|
||||
mod predicates;
|
||||
mod raster;
|
||||
mod renderer;
|
||||
|
||||
pub use placement::pinned_appearance_for_geometry_edit;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use bounds::visual_bounds;
|
||||
pub(crate) use bounds::{
|
||||
|
||||
@@ -726,6 +726,12 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b
|
||||
let a = art_effects_reach(symbols, n);
|
||||
Some(b.inflate(a, a))
|
||||
}
|
||||
// A spine can rotate a blend's keys and steps past their unrotated visual bounds.
|
||||
NodeKind::Blend { .. } => {
|
||||
let b = n.reach_bounds_with(symbols)?;
|
||||
let a = live_content_reach(symbols, n);
|
||||
vectorcraft_geom::union_opt(Some(b.inflate(a, a)), placed_blend_effect_bounds(symbols, n))
|
||||
}
|
||||
_ => {
|
||||
let b = n.visual_bounds_with(symbols)?;
|
||||
let b = match &n.kind {
|
||||
@@ -804,16 +810,43 @@ pub(crate) fn with_own_raster_reach(symbols: &SymbolBoxes, n: &Node, b: Rect) ->
|
||||
b.inflate(o, o)
|
||||
}
|
||||
|
||||
/// `n`'s own visual box, type's grown to hold its glyphs ([`glyphs_box`]): what it draws when its
|
||||
/// object effects leave it as it is (Revolve builds no art from type).
|
||||
/// `n`'s own box, type's grown to hold its glyphs ([`glyphs_box`]) and a blend's to hold its
|
||||
/// spine-placed keys and steps: what it draws when its object effects leave it as it is
|
||||
/// (Revolve builds no art from type).
|
||||
fn own_box(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let b = n.visual_bounds_with(symbols)?;
|
||||
let b = match &n.kind {
|
||||
NodeKind::Blend { .. } => vectorcraft_geom::union_opt(n.reach_bounds_with(symbols), placed_blend_effect_bounds(symbols, n)),
|
||||
_ => n.visual_bounds_with(symbols),
|
||||
}?;
|
||||
Some(match &n.kind {
|
||||
NodeKind::Text(t) => vectorcraft_geom::union_opt(Some(b), glyphs_box(t, n.appearance.outset())).unwrap_or(b),
|
||||
_ => b,
|
||||
})
|
||||
}
|
||||
|
||||
/// A rotated blend's effect-bearing content, measured after spine placement. Geometry effects
|
||||
/// run on the placed shapes, so their reach on the original keys need not cover what they paint.
|
||||
/// Effect-free blends keep the quick rail envelope without evaluating their steps.
|
||||
fn placed_blend_effect_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
|
||||
let NodeKind::Blend { spec, .. } = &n.kind else { return None };
|
||||
if spec.orientation != vectorcraft_doc::BlendOrientation::AlignToPath {
|
||||
return None;
|
||||
}
|
||||
let mut has_effects = false;
|
||||
n.walk(&mut |c| {
|
||||
has_effects |= has_fx(c)
|
||||
|| has_object_fx(c)
|
||||
|| match &c.kind {
|
||||
NodeKind::SymbolInstance { symbol, .. } => symbols.has_effects(symbol),
|
||||
_ => false,
|
||||
};
|
||||
});
|
||||
if !has_effects {
|
||||
return None;
|
||||
}
|
||||
effects::expand_live(Some(symbols.document()), n).iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, cull_bounds(symbols, c)))
|
||||
}
|
||||
|
||||
/// The box of type `t`'s glyphs as laid out (its layout bounds, else laid out now), grown by its
|
||||
/// characters' strokes, miter spikes included, and by `outset`: on a path they stand above it and
|
||||
/// run past its ends, in an area they can hang past its frame, where its own box
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Stored gradient fits for geometry edits on the renderer's ordinary shape/container paths.
|
||||
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeKind};
|
||||
use vectorcraft_effects::{self as effects, GeomContext};
|
||||
use vectorcraft_geom::{BezPath, Rect, Shape};
|
||||
|
||||
use super::bounds::{apply_carrying, effected_path_carrying, item_effects, node_bezpath};
|
||||
use super::predicates::has_non_container_art_fx;
|
||||
use super::renderer::carried;
|
||||
|
||||
/// Store the current renderer fit of gradients that can be represented by the existing appearance.
|
||||
///
|
||||
/// Alternate materialized art, visible plug-ins, Rasterize and path-coordinate stroke gradients
|
||||
/// keep their existing fit behavior. An unsupported or non-roundtripping carry also leaves its row
|
||||
/// unchanged; this neither flattens art nor changes persisted effects. `None` makes no change.
|
||||
pub fn pinned_appearance_for_geometry_edit(doc: &Document, n: &Node) -> Option<Appearance> {
|
||||
if !n.appearance.has_unplaced_gradient() || unsupported(n) || has_non_container_art_fx(n) {
|
||||
return None;
|
||||
}
|
||||
// Enclosing geometry effects change the fit outside this node-local pass.
|
||||
// Without that context, leave the paint fitted rather than storing a false frame.
|
||||
if doc.ancestry(n.id)?.into_iter().filter(|&id| id != n.id).any(|id| {
|
||||
doc.node(id).is_some_and(|ancestor| {
|
||||
matches!(ancestor.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && effects::has_geometry(&ancestor.appearance.effects)
|
||||
})
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::Group { .. } | NodeKind::Layer { .. } => effects::pinned_container_appearance(doc, n),
|
||||
NodeKind::Path { guide: false, .. } | NodeKind::Compound { .. } => pinned_shape(doc, n),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn rasterizes(fx: &[Effect]) -> bool {
|
||||
fx.iter().any(|effect| effect.visible && effect.id == effects::RASTERIZE)
|
||||
}
|
||||
|
||||
fn unsupported(n: &Node) -> bool {
|
||||
effects::has_plugin_effect(n)
|
||||
|| rasterizes(&n.appearance.effects)
|
||||
|| n.appearance.items.iter().any(|item| {
|
||||
item.visible() && (rasterizes(item.effects()) || matches!(item, AppearanceItem::Stroke(stroke) if stroke.path_gradient().is_some()))
|
||||
})
|
||||
}
|
||||
|
||||
fn unplaced(item: &AppearanceItem) -> bool {
|
||||
item.visible() && matches!(item.paint(), Paint::Gradient(gradient) if !gradient.is_placed())
|
||||
}
|
||||
|
||||
fn pinned_shape(doc: &Document, n: &Node) -> Option<Appearance> {
|
||||
let bp = node_bezpath(n)?;
|
||||
let (geometry, object_carry) = effected_path_carrying(doc, n, &bp);
|
||||
if geometry.elements().is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Share the renderer's actual temporary object carry and skipped-effect flags.
|
||||
let temporary = carried(n, &object_carry);
|
||||
let paints = temporary.as_deref().unwrap_or(n);
|
||||
let context = GeomContext { doc: Some(doc), ..GeomContext::of(paints) };
|
||||
let mut appearance = (*n.appearance).clone();
|
||||
let mut changed = false;
|
||||
for (index, original) in n.appearance.items.iter().enumerate().filter(|(_, item)| unplaced(item)) {
|
||||
// `item` must belong to the same temporary appearance borrowed by `context.item`:
|
||||
// that lookup uses pointer identity to recover the actual row index/seed.
|
||||
let item = paints.appearance.items.get(index)?;
|
||||
let (item_geometry, item_carry) = apply_carrying(item_effects(item), &geometry, &context.item(item));
|
||||
let bounds = item_bounds(item, &geometry, &item_geometry, &item_carry)?;
|
||||
if let Some(pinned) = effects::pinned_gradient_item(original, bounds, &[&object_carry, &item_carry]) {
|
||||
*appearance.items.get_mut(index)? = pinned;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed.then_some(appearance)
|
||||
}
|
||||
|
||||
/// The same temporary item carry/skipped flags and `ib` choice as `Renderer::paint_items`.
|
||||
fn item_bounds(item: &AppearanceItem, geometry: &BezPath, item_geometry: &BezPath, carry: &effects::Carry) -> Option<Rect> {
|
||||
let mut appearance = Appearance { items: vec![item.clone()], ..Default::default() };
|
||||
if !carry.is_empty() && matches!(item.paint(), Paint::Gradient(_)) {
|
||||
carry.apply(&mut appearance);
|
||||
}
|
||||
let mut item = appearance.items.pop()?;
|
||||
if carry.skipped() {
|
||||
carry.hide_skipped(item.effects_mut());
|
||||
}
|
||||
Some(if effects::has_geometry(item_effects(&item)) && !item_geometry.elements().is_empty() {
|
||||
item_geometry.bounding_box()
|
||||
} else {
|
||||
geometry.bounding_box()
|
||||
})
|
||||
}
|
||||
@@ -25,11 +25,20 @@ pub(crate) fn has_fx(n: &Node) -> bool {
|
||||
/// effect copies it with a gradient or changes its fills and strokes ([`effects::has_transform_art`]),
|
||||
/// or is it a group or layer with an appearance of its own (see [`Renderer::draw_object_fx`])?
|
||||
pub(crate) fn has_object_fx(n: &Node) -> bool {
|
||||
object_fx(n, true)
|
||||
}
|
||||
|
||||
/// The alternate-art dispatches other than a group or layer's own container appearance.
|
||||
pub(super) fn has_non_container_art_fx(n: &Node) -> bool {
|
||||
object_fx(n, false)
|
||||
}
|
||||
|
||||
fn object_fx(n: &Node, containers: bool) -> bool {
|
||||
(effects::needs_outline(n) && (visible(&n.appearance.effects) || n.projection().is_some()))
|
||||
|| effects::has_item_geometry(n)
|
||||
|| effects::has_instance_row_raster(n)
|
||||
|| effects::has_transform_art(n)
|
||||
|| effects::has_container_appearance(n)
|
||||
|| (containers && effects::has_container_appearance(n))
|
||||
|| effects::has_crop_marks(n)
|
||||
|| effects::addons::halftone::has_halftone(n)
|
||||
|| effects::has_adjustment(n)
|
||||
|
||||
@@ -1029,7 +1029,7 @@ impl Renderer {
|
||||
/// the Transform effects the geometry pass left out hidden ([`effects::Carry::hide_skipped`]), so
|
||||
/// its raster effects and those of its fills and strokes stay with its art; `None` when it stays
|
||||
/// as it is.
|
||||
fn carried(n: &Node, carry: &effects::Carry) -> Option<Arc<Node>> {
|
||||
pub(super) fn carried(n: &Node, carry: &effects::Carry) -> Option<Arc<Node>> {
|
||||
let moves = carry.moves(&n.appearance);
|
||||
(moves || carry.skipped()).then(|| {
|
||||
let mut m = n.clone();
|
||||
|
||||
@@ -43,6 +43,7 @@ use lru::FrameCache;
|
||||
pub use brush_fx::instance_art;
|
||||
pub use changed::{Changed, changed, placed_area, view_pixels};
|
||||
pub use effects::stroke::width_outline;
|
||||
pub use fx::pinned_appearance_for_geometry_edit;
|
||||
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, installed_memory, newly_undecodable, set_image_cache_budget};
|
||||
pub use live::expand_live;
|
||||
pub use pattern::render_pattern_swatch;
|
||||
|
||||
Reference in New Issue
Block a user