mirror of
https://github.com/storytold/deckcraft.git
synced 2026-11-10 12:29:34 -06:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e47ef826a1 |
@@ -125,9 +125,7 @@ pub fn draw(ctx: &mut RenderContext, bevel: &Bevel, fill: Option<Rgba>, path: &B
|
|||||||
let longest = bounds.width().max(bounds.height()) * k;
|
let longest = bounds.width().max(bounds.height()) * k;
|
||||||
let s = (MAX_SIDE / longest).min(1.0) * k;
|
let s = (MAX_SIDE / longest).min(1.0) * k;
|
||||||
let (pw, ph) = (((bounds.width() * s).ceil() as u32).clamp(1, 2048), ((bounds.height() * s).ceil() as u32).clamp(1, 2048));
|
let (pw, ph) = (((bounds.width() * s).ceil() as u32).clamp(1, 2048), ((bounds.height() * s).ceil() as u32).clamp(1, 2048));
|
||||||
// Each pixel tests every edge, so a dense outline is simplified to the raster's edge budget.
|
let polys = crate::pathgrad::polygons(path);
|
||||||
let pixel = (bounds.width() / f64::from(pw)).min(bounds.height() / f64::from(ph));
|
|
||||||
let polys = crate::pathgrad::simplify(crate::pathgrad::polygons(path), pixel, crate::pathgrad::edge_budget(pw, ph));
|
|
||||||
if polys.is_empty() {
|
if polys.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,6 @@ use vello_cpu::{RenderContext, peniko};
|
|||||||
|
|
||||||
/// Nesting depth of clips and layers past which a glyph opens no more (hostile fonts).
|
/// Nesting depth of clips and layers past which a glyph opens no more (hostile fonts).
|
||||||
const MAX_DEPTH: usize = 64;
|
const MAX_DEPTH: usize = 64;
|
||||||
/// Fills and gradient stops one colour glyph may paint; the rest of a hostile glyph is skipped.
|
|
||||||
const MAX_WORK: usize = 100_000;
|
|
||||||
|
|
||||||
/// Paint `gid` of `face` as a colour glyph, its origin mapped by `at` (y down, points) at `scale`
|
/// Paint `gid` of `face` as a colour glyph, its origin mapped by `at` (y down, points) at `scale`
|
||||||
/// points per font unit. `fg` is the text colour (palette index 0xFFFF) and `alpha` fades it all.
|
/// points per font unit. `fg` is the text colour (palette index 0xFFFF) and `alpha` fades it all.
|
||||||
@@ -28,7 +26,7 @@ pub fn paint(ctx: &mut RenderContext, face: &FontFace, gid: u32, at: Affine, sca
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
// Font units are y up; the slide is y down.
|
// Font units are y up; the slide is y down.
|
||||||
let base = at * Affine::scale(scale) * Affine::scale_non_uniform(1.0, -1.0);
|
let base = at * Affine::scale(scale) * Affine::scale_non_uniform(1.0, -1.0);
|
||||||
let mut p = Painter { ctx, face, base, stack: vec![Affine::IDENTITY], palette, fg, opened: Vec::new(), work: 0 };
|
let mut p = Painter { ctx, face, base, stack: vec![Affine::IDENTITY], palette, fg, opened: Vec::new() };
|
||||||
p.ctx.push_layer(None, None, Some(alpha.clamp(0.0, 1.0) as f32), None, None);
|
p.ctx.push_layer(None, None, Some(alpha.clamp(0.0, 1.0) as f32), None, None);
|
||||||
let ok = glyph.paint(face.location(), &mut p).is_ok();
|
let ok = glyph.paint(face.location(), &mut p).is_ok();
|
||||||
// A malformed glyph may leave layers open: close them all.
|
// A malformed glyph may leave layers open: close them all.
|
||||||
@@ -52,8 +50,6 @@ struct Painter<'a> {
|
|||||||
/// Clips and composite groups pushed by the glyph, innermost last: true when a layer was
|
/// Clips and composite groups pushed by the glyph, innermost last: true when a layer was
|
||||||
/// opened on the context for it (false past `MAX_DEPTH`, so its pop is skipped too).
|
/// opened on the context for it (false past `MAX_DEPTH`, so its pop is skipped too).
|
||||||
opened: Vec<bool>,
|
opened: Vec<bool>,
|
||||||
/// Fills plus gradient stops painted so far, against [`MAX_WORK`].
|
|
||||||
work: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn affine(t: &Transform) -> Affine {
|
fn affine(t: &Transform) -> Affine {
|
||||||
@@ -178,16 +174,6 @@ impl ColorPainter for Painter<'_> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn fill(&mut self, brush: Brush<'_>) {
|
fn fill(&mut self, brush: Brush<'_>) {
|
||||||
let stops = match &brush {
|
|
||||||
Brush::Solid { .. } => 0,
|
|
||||||
Brush::LinearGradient { color_stops, .. } | Brush::RadialGradient { color_stops, .. } | Brush::SweepGradient { color_stops, .. } => {
|
|
||||||
color_stops.len()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
self.work = self.work.saturating_add(1 + stops);
|
|
||||||
if self.work > MAX_WORK {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
match brush {
|
match brush {
|
||||||
Brush::Solid { palette_index, alpha } => {
|
Brush::Solid { palette_index, alpha } => {
|
||||||
let c = self.color(palette_index, alpha);
|
let c = self.color(palette_index, alpha);
|
||||||
|
|||||||
@@ -25,16 +25,6 @@ const MAX_EDGE_WORK: u64 = 64_000_000;
|
|||||||
/// Fewest edges a simplified polygon keeps, so a coarse outline still has a shape.
|
/// Fewest edges a simplified polygon keeps, so a coarse outline still has a shape.
|
||||||
const MIN_POLY_EDGES: usize = 8;
|
const MIN_POLY_EDGES: usize = 8;
|
||||||
|
|
||||||
/// Most points `polygons` keeps from one path; a path flattening past this (a huge finite curve) is
|
|
||||||
/// not drawn rather than held in memory first.
|
|
||||||
const MAX_POINTS: usize = 2_000_000;
|
|
||||||
|
|
||||||
/// The edge budget for a `pw` x `ph` raster where each pixel tests every edge.
|
|
||||||
pub(crate) fn edge_budget(pw: u32, ph: u32) -> usize {
|
|
||||||
let pixels = u64::from(pw).saturating_mul(u64::from(ph)).max(1);
|
|
||||||
usize::try_from(MAX_EDGE_WORK / pixels).unwrap_or(usize::MAX).max(MIN_POLY_EDGES)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Colour position (0 at the focus, 1 at the edge) of `p` for path `kind` in `bounds` with the
|
/// Colour position (0 at the focus, 1 at the edge) of `p` for path `kind` in `bounds` with the
|
||||||
/// focus rect `focus` (fractions inset from left, top, right, bottom), `outline` being the
|
/// focus rect `focus` (fractions inset from left, top, right, bottom), `outline` being the
|
||||||
/// shape's flattened polygon(s) for `shape`.
|
/// shape's flattened polygon(s) for `shape`.
|
||||||
@@ -124,31 +114,21 @@ fn shape_position(outline: &[Vec<Point>], c: Point, p: Point) -> f64 {
|
|||||||
pub fn polygons(path: &BezPath) -> Vec<Vec<Point>> {
|
pub fn polygons(path: &BezPath) -> Vec<Vec<Point>> {
|
||||||
let mut out: Vec<Vec<Point>> = Vec::new();
|
let mut out: Vec<Vec<Point>> = Vec::new();
|
||||||
let mut cur: Vec<Point> = Vec::new();
|
let mut cur: Vec<Point> = Vec::new();
|
||||||
let mut total = 0usize;
|
kurbo::flatten(path.iter(), 0.25, |el| match el {
|
||||||
kurbo::flatten(path.iter(), 0.25, |el| {
|
PathEl::MoveTo(p) => {
|
||||||
total += 1;
|
if cur.len() > 1 {
|
||||||
if total > MAX_POINTS {
|
out.push(std::mem::take(&mut cur));
|
||||||
return;
|
|
||||||
}
|
|
||||||
match el {
|
|
||||||
PathEl::MoveTo(p) => {
|
|
||||||
if cur.len() > 1 {
|
|
||||||
out.push(std::mem::take(&mut cur));
|
|
||||||
}
|
|
||||||
cur = vec![p];
|
|
||||||
}
|
}
|
||||||
PathEl::LineTo(p) => cur.push(p),
|
cur = vec![p];
|
||||||
PathEl::ClosePath => {
|
|
||||||
if let Some(f) = cur.first().copied() {
|
|
||||||
cur.push(f);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
|
PathEl::LineTo(p) => cur.push(p),
|
||||||
|
PathEl::ClosePath => {
|
||||||
|
if let Some(f) = cur.first().copied() {
|
||||||
|
cur.push(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
});
|
});
|
||||||
if total > MAX_POINTS {
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
if cur.len() > 1 {
|
if cur.len() > 1 {
|
||||||
out.push(cur);
|
out.push(cur);
|
||||||
}
|
}
|
||||||
@@ -166,7 +146,7 @@ pub fn polygons(path: &BezPath) -> Vec<Vec<Point>> {
|
|||||||
/// `outline` cut down to at most about `max_edges` edges in total: first by dropping points
|
/// `outline` cut down to at most about `max_edges` edges in total: first by dropping points
|
||||||
/// closer than `tol` to the last kept one (detail finer than a raster pixel), then, if still too
|
/// closer than `tol` to the last kept one (detail finer than a raster pixel), then, if still too
|
||||||
/// many, by keeping every k-th point. Each polygon stays closed. Returns it unchanged when it fits.
|
/// many, by keeping every k-th point. Each polygon stays closed. Returns it unchanged when it fits.
|
||||||
pub(crate) fn simplify(outline: Vec<Vec<Point>>, tol: f64, max_edges: usize) -> Vec<Vec<Point>> {
|
fn simplify(outline: Vec<Vec<Point>>, tol: f64, max_edges: usize) -> Vec<Vec<Point>> {
|
||||||
let edges = |o: &[Vec<Point>]| o.iter().map(|p| p.len().saturating_sub(1)).sum::<usize>();
|
let edges = |o: &[Vec<Point>]| o.iter().map(|p| p.len().saturating_sub(1)).sum::<usize>();
|
||||||
if edges(&outline) <= max_edges {
|
if edges(&outline) <= max_edges {
|
||||||
return outline;
|
return outline;
|
||||||
@@ -253,17 +233,13 @@ pub fn fill(ctx: &mut RenderContext, kind: &str, focus: [f64; 4], stops: &[(f64,
|
|||||||
let s = (MAX_SIDE / longest).min(1.0) * k;
|
let s = (MAX_SIDE / longest).min(1.0) * k;
|
||||||
let (pw, ph) = (((bounds.width() * s).ceil() as u32).clamp(1, 4096), ((bounds.height() * s).ceil() as u32).clamp(1, 4096));
|
let (pw, ph) = (((bounds.width() * s).ceil() as u32).clamp(1, 4096), ((bounds.height() * s).ceil() as u32).clamp(1, 4096));
|
||||||
let outline = if kind == "shape" {
|
let outline = if kind == "shape" {
|
||||||
let max_edges = edge_budget(pw, ph);
|
let pixels = u64::from(pw).saturating_mul(u64::from(ph)).max(1);
|
||||||
|
let max_edges = usize::try_from(MAX_EDGE_WORK / pixels).unwrap_or(usize::MAX).max(MIN_POLY_EDGES);
|
||||||
let pixel = (bounds.width() / f64::from(pw)).min(bounds.height() / f64::from(ph));
|
let pixel = (bounds.width() / f64::from(pw)).min(bounds.height() / f64::from(ph));
|
||||||
simplify(polygons(path), pixel, max_edges)
|
simplify(polygons(path), pixel, max_edges)
|
||||||
} else {
|
} else {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
};
|
};
|
||||||
// An outline `polygons` refused (too many points) has no contours: skip the shape rather than
|
|
||||||
// paint it with the rectangle fallback's different gradient.
|
|
||||||
if kind == "shape" && outline.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let lut = ramp(stops);
|
let lut = ramp(stops);
|
||||||
let a = alpha.clamp(0.0, 1.0);
|
let a = alpha.clamp(0.0, 1.0);
|
||||||
let mut data = Vec::with_capacity((pw * ph) as usize);
|
let mut data = Vec::with_capacity((pw * ph) as usize);
|
||||||
@@ -396,20 +372,6 @@ mod tests {
|
|||||||
assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());
|
assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_shape_gradient_with_no_usable_outline_paints_nothing() {
|
|
||||||
// One polygon over the per-polygon cap is dropped by `polygons`.
|
|
||||||
let path = many_segment_square(26_000);
|
|
||||||
assert!(polygons(&path).is_empty());
|
|
||||||
let mut ctx = RenderContext::new(64, 64);
|
|
||||||
let stops = [(0.0, Rgba::rgb(0, 0, 0)), (1.0, Rgba::rgb(255, 255, 255))];
|
|
||||||
fill(&mut ctx, "shape", CENTRE, &stops, Rect::new(0.0, 0.0, 64.0, 64.0), &path, Affine::IDENTITY, 1.0);
|
|
||||||
ctx.flush();
|
|
||||||
let mut px = vec![0u8; 64 * 64 * 4];
|
|
||||||
ctx.render(vello_cpu::PixmapMut::new(64, 64, &mut px).unwrap(), &mut vello_cpu::Resources::new());
|
|
||||||
assert!(px.chunks(4).all(|p| p[3] == 0), "nothing was painted");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_ramp_runs_through_the_stops() {
|
fn the_ramp_runs_through_the_stops() {
|
||||||
let stops = [(0.0, Rgba::rgb(0, 0, 0)), (0.5, Rgba::rgb(128, 128, 128)), (1.0, Rgba::rgb(255, 255, 255))];
|
let stops = [(0.0, Rgba::rgb(0, 0, 0)), (0.5, Rgba::rgb(128, 128, 128)), (1.0, Rgba::rgb(255, 255, 255))];
|
||||||
|
|||||||
+23
-7
@@ -61,16 +61,23 @@ pub fn missing(files: &[String], assets_md: &str) -> Vec<String> {
|
|||||||
files.iter().filter(|f| is_asset(f) && !patterns.iter().any(|p| glob(p, f))).cloned().collect()
|
files.iter().filter(|f| is_asset(f) && !patterns.iter().any(|p| glob(p, f))).cloned().collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `*` matches any run of characters except `/`; everything else literally.
|
/// `*` matches any run of characters except `/`; everything else literally. Matched with a
|
||||||
|
/// table over the pattern, so a pattern with many `*` costs pattern length times name length
|
||||||
|
/// rather than exploring every way to split the name.
|
||||||
fn glob(pat: &str, s: &str) -> bool {
|
fn glob(pat: &str, s: &str) -> bool {
|
||||||
match pat.split_once('*') {
|
let t: Vec<char> = s.chars().collect();
|
||||||
None => pat == s,
|
// `row[k]`: the pattern so far matches the first k characters of the name.
|
||||||
Some((head, tail)) => {
|
let mut row = vec![false; t.len() + 1];
|
||||||
let Some(rest) = s.strip_prefix(head) else { return false };
|
row[0] = true;
|
||||||
let ends = rest.char_indices().map(|(i, _)| i).chain(std::iter::once(rest.len()));
|
for pc in pat.chars() {
|
||||||
ends.take_while(|&i| !rest[..i].contains('/')).any(|i| glob(tail, &rest[i..]))
|
let mut next = vec![false; t.len() + 1];
|
||||||
|
next[0] = pc == '*' && row[0];
|
||||||
|
for k in 1..=t.len() {
|
||||||
|
next[k] = if pc == '*' { row[k] || (next[k - 1] && t[k - 1] != '/') } else { row[k - 1] && t[k - 1] == pc };
|
||||||
}
|
}
|
||||||
|
row = next;
|
||||||
}
|
}
|
||||||
|
row[t.len()]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Splits `git ls-files -z` output into real file names (no display quoting of Unicode or special characters).
|
/// Splits `git ls-files -z` output into real file names (no display quoting of Unicode or special characters).
|
||||||
@@ -120,6 +127,15 @@ mod tests {
|
|||||||
assert_eq!(missing(&["assets/é.png".into()], "`assets/*.svg`"), vec!["assets/é.png".to_string()]);
|
assert_eq!(missing(&["assets/é.png".into()], "`assets/*.svg`"), vec!["assets/é.png".to_string()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn many_wildcards_on_a_failing_name_finish_at_once() {
|
||||||
|
let pat = format!("{}b", "a*".repeat(40));
|
||||||
|
assert!(!glob(&pat, &"a".repeat(60)));
|
||||||
|
assert!(glob(&pat, &format!("{}b", "a".repeat(60))));
|
||||||
|
assert!(!glob("a*b", "a/b"));
|
||||||
|
assert!(glob("a*b", "ab"));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn ls_files_output_is_nul_separated_and_unquoted() {
|
fn ls_files_output_is_nul_separated_and_unquoted() {
|
||||||
let names = parse_ls_files("assets/zażółć.png\0docs/images/a b\nc.png\0".as_bytes());
|
let names = parse_ls_files("assets/zażółć.png\0docs/images/a b\nc.png\0".as_bytes());
|
||||||
|
|||||||
Reference in New Issue
Block a user