Add GPU rendering of gradients read across their contours, using the Vello fork's new polar gradient paint

This commit is contained in:
Keavon Chambers committed 2026-12-05 04:44:44 -08:00
1 parent f76d89a6ca
commit 58e32134a3
5 files changed
+225 -62

No files matched your search

Generated
+3 -3
View File
@@ -8084,7 +8084,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -8099,7 +8099,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -8113,7 +8113,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
dependencies = [
"naga",
"wesl",
+3 -3
View File
@@ -315,6 +315,6 @@ debug = true
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
# TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
+94 -51
View File
@@ -3440,7 +3440,9 @@ fn peniko_extend(gradient_spread: GradientSpread) -> peniko::Extend {
enum GradientBrush {
Peniko(peniko::Brush),
/// Apollonian circles, which only Vello GPU's fork draws.
Apollonian(vello_gpu::PencilGradient),
Apollonian(vello_gpu::ApollonianGradient),
/// A position running around the contours, which only Vello GPU's fork draws.
Polar(vello_gpu::PolarGradient),
}
impl<'b> From<&'b GradientBrush> for SceneBrush<'b> {
@@ -3448,6 +3450,7 @@ impl<'b> From<&'b GradientBrush> for SceneBrush<'b> {
match brush {
GradientBrush::Peniko(brush) => brush.into(),
GradientBrush::Apollonian(gradient) => gradient.into(),
GradientBrush::Polar(gradient) => gradient.into(),
}
}
}
@@ -3492,30 +3495,7 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
let brush = |kind: peniko::GradientKind, stops: peniko::ColorStops, extend: peniko::Extend| GradientBrush::Peniko(peniko::Brush::Gradient(gradient(kind, stops, extend)));
let ramp = |kind: peniko::GradientKind| brush(kind, peniko_color_stops(samples), peniko_extend(spread));
let gradient = match shape {
GradientShape::Linear => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Linear)), gradient_placement(placement, shape)), None)])),
GradientShape::Radial => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Radial)), placement), None)])),
// Its contours come from its own geometry, so its ramp takes the linear kind, which goes unused
GradientShape::Apollonian(parameters) => {
let ramp = gradient(unit_gradient_kind(GradientForm::Linear), peniko_color_stops(samples), peniko_extend(spread));
let apollonian = vello_gpu::PencilGradient {
ramp,
geometry: apollonian_geometry(&parameters),
};
return Some(VelloGradientPaint(vec![((GradientBrush::Apollonian(apollonian), placement), None)]));
}
GradientShape::Across(GradientAcross { chart, .. }) => {
let kind = match chart {
AcrossChart::Nothing => return None,
AcrossChart::Concentric { center } => peniko::SweepGradientPosition::new(kurbo::Point::new(center, 0.), 0., std::f32::consts::TAU).into(),
AcrossChart::Linear | AcrossChart::Cone { .. } | AcrossChart::Mobius { .. } | AcrossChart::Bipolar { .. } => across_linear_kind(),
};
return Some(VelloGradientPaint(vec![((ramp(kind), placement), None)]));
}
GradientShape::Standard(gradient) => gradient,
};
// Ramps along the gradient line are placed like the linear form, and circles by the full placement
// Ramps along the gradient line, and steps across it, are placed like the linear form
let desheared = desheared_placement(placement);
let linear = |[start, end]: [f64; 2]| -> peniko::GradientKind {
peniko::LinearGradientPosition {
@@ -3524,15 +3504,6 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
}
.into()
};
let radial = |cone: Cone| -> peniko::GradientKind {
peniko::RadialGradientPosition {
start_center: kurbo::Point::new(cone.start_center, 0.),
start_radius: cone.start_radius as f32,
end_center: kurbo::Point::new(cone.end_center, 0.),
end_radius: cone.end_radius as f32,
}
.into()
};
let stops = |colors: &[(f32, Color)]| {
let stop = |&(offset, color): &(f32, Color)| peniko::ColorStop {
offset,
@@ -3540,7 +3511,6 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
};
peniko::ColorStops(colors.iter().map(stop).collect())
};
let end_color = |end| end_stop_color(samples, end);
// A step at `at` from one color to the other, as a unit-long gradient there with both stops at its start
let step = |at: f64, direction: f64, [before, after]: [Color; 2]| {
@@ -3548,6 +3518,79 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
(brush, rebased_transform(desheared, at))
};
// An eraser opaque wherever a layer kept to one side of a line across the gradient line is hidden
let eraser = |keep: HalfPlane| {
let colors = if keep.keeps_before {
[Color::TRANSPARENT, Color::BLACK]
} else {
[Color::BLACK, Color::TRANSPARENT]
};
step(keep.at, 1., colors)
};
let gradient = match shape {
GradientShape::Linear => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Linear)), gradient_placement(placement, shape)), None)])),
GradientShape::Radial => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Radial)), placement), None)])),
// Its contours come from its own geometry, so its ramp takes the linear kind, which goes unused
GradientShape::Apollonian(parameters) => {
let ramp = gradient(unit_gradient_kind(GradientForm::Linear), peniko_color_stops(samples), peniko_extend(spread));
let apollonian = vello_gpu::ApollonianGradient {
ramp,
geometry: apollonian_geometry(&parameters),
};
return Some(VelloGradientPaint(vec![((GradientBrush::Apollonian(apollonian), placement), None)]));
}
GradientShape::Across(GradientAcross { chart, .. }) => {
let polar = |geometry| {
let ramp = gradient(across_linear_kind(), peniko_color_stops(samples), peniko_extend(spread));
GradientBrush::Polar(vello_gpu::PolarGradient { ramp, geometry })
};
// The angle of `(numerator[0] z + numerator[1]) / (denominator[0] z + denominator[1])` with real coefficients
let mobius_angle = |numerator: [f64; 2], denominator: [f64; 2]| {
let real = |[slope, intercept]: [f64; 2]| [[slope as f32, 0.], [intercept as f32, 0.]];
let measure = vello_gpu::PolarMeasure::Angle;
polar(vello_gpu::PolarGeometry::Mobius {
numerator: real(numerator),
denominator: real(denominator),
measure,
})
};
let (brush, keep) = match chart {
AcrossChart::Nothing => return None,
AcrossChart::Linear => (ramp(across_linear_kind()), None),
// Vello's own sweep gradient, which Graphite builds without, measures the same angle as `z - center`
AcrossChart::Concentric { center } => (mobius_angle([1., -center], [0., 1.]), None),
AcrossChart::Cone { cone, keep } => (polar(cone_angle_geometry(cone)), keep),
AcrossChart::Mobius { numerator, denominator } => (mobius_angle(numerator, denominator), None),
// `(z - (center_x, -half_height)) / (z - (center_x, half_height))`
AcrossChart::Bipolar { center_x, half_height, scale } => {
let (center_x, half_height) = (center_x as f32, half_height as f32);
let geometry = vello_gpu::PolarGeometry::Mobius {
numerator: [[1., 0.], [-center_x, half_height]],
denominator: [[1., 0.], [-center_x, -half_height]],
measure: vello_gpu::PolarMeasure::LogModulus { scale: scale as f32, offset: 0. },
};
(polar(geometry), None)
}
};
return Some(VelloGradientPaint(vec![((brush, placement), keep.map(eraser))]));
}
GradientShape::Standard(gradient) => gradient,
};
// Circles are placed by the full placement
let radial = |cone: Cone| -> peniko::GradientKind {
peniko::RadialGradientPosition {
start_center: kurbo::Point::new(cone.start_center, 0.),
start_radius: cone.start_radius as f32,
end_center: kurbo::Point::new(cone.end_center, 0.),
end_radius: cone.end_radius as f32,
}
.into()
};
let end_color = |end| end_stop_color(samples, end);
let layers: Vec<_> = standard_layers(gradient)
.into_iter()
.map(|(paint, mask)| {
@@ -3562,37 +3605,37 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
StandardPaint::Solid(end) => (GradientBrush::Peniko(peniko::Brush::Solid(peniko::Color::new(end_color(end).to_gamma_srgb_channels()))), placement),
};
// The eraser is opaque wherever the layer is hidden
let eraser = mask.map(|keep| {
let colors = if keep.keeps_before {
[Color::TRANSPARENT, Color::BLACK]
} else {
[Color::BLACK, Color::TRANSPARENT]
};
step(keep.at, 1., colors)
});
(paint, eraser)
(paint, mask.map(eraser))
})
.collect();
(!layers.is_empty()).then_some(VelloGradientPaint(layers))
}
/// SVG 2's cone as Vello GPU's polar gradient paint takes it, in single precision.
fn cone_angle_geometry(cone: Cone) -> vello_gpu::PolarGeometry {
vello_gpu::PolarGeometry::ConeAngle {
start_center: [cone.start_center as f32, 0.],
start_radius: cone.start_radius as f32,
end_center: [cone.end_center as f32, 0.],
end_radius: cone.end_radius as f32,
}
}
/// The Apollonian circles of a gradient as Vello GPU's Apollonian gradient paint takes them, in single precision.
fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::PencilGeometry {
fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::ApollonianGeometry {
let circle = |circle: &AxisCircle| [circle.a as f32, circle.b as f32, circle.c as f32];
vello_gpu::PencilGeometry {
vello_gpu::ApollonianGeometry {
start: circle(&parameters.start),
end: circle(&parameters.end),
selection: match parameters.selection {
CrossingSelection::SameSideAs { radical_x } => vello_gpu::PencilSelection::SameSideAs { radical_x: radical_x as f32 },
CrossingSelection::OnArc { quadratic } => vello_gpu::PencilSelection::OnArc {
CrossingSelection::SameSideAs { radical_x } => vello_gpu::ApollonianSelection::SameSideAs { radical_x: radical_x as f32 },
CrossingSelection::OnArc { quadratic } => vello_gpu::ApollonianSelection::OnArc {
quadratic: quadratic.map(|coefficient| coefficient as f32),
},
},
wrap: parameters.wrap.map(|wrap| vello_gpu::PencilWrap {
wrap: parameters.wrap.map(|wrap| vello_gpu::ApollonianWrap {
reference_x: wrap.reference_x as f32,
band_side: wrap.band_side as f32,
t: wrap.t as f32,
@@ -11,7 +11,7 @@ use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
use std::borrow::Cow;
use std::collections::HashMap;
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
use vello_gpu::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion};
use vello_gpu::{ApollonianGradient, Image, ImageSource, PaintType, PolarGradient, TextureId, TextureRegion};
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
const SHAPE_TOLERANCE: f64 = 0.1;
@@ -100,7 +100,9 @@ pub enum SceneBrush<'b> {
/// A solid color, gradient, or image.
Peniko(BrushRef<'b>),
/// A gradient whose contours are Apollonian circles, which only Vello GPU's fork draws.
Apollonian(&'b PencilGradient),
Apollonian(&'b ApollonianGradient),
/// A gradient whose position runs around its contours, which only Vello GPU's fork draws.
Polar(&'b PolarGradient),
}
impl<'b> From<BrushRef<'b>> for SceneBrush<'b> {
@@ -133,12 +135,18 @@ impl From<&peniko::Color> for SceneBrush<'_> {
}
}
impl<'b> From<&'b PencilGradient> for SceneBrush<'b> {
fn from(gradient: &'b PencilGradient) -> Self {
impl<'b> From<&'b ApollonianGradient> for SceneBrush<'b> {
fn from(gradient: &'b ApollonianGradient) -> Self {
Self::Apollonian(gradient)
}
}
impl<'b> From<&'b PolarGradient> for SceneBrush<'b> {
fn from(gradient: &'b PolarGradient) -> Self {
Self::Polar(gradient)
}
}
/// The pixels behind an image the scene draws.
#[derive(Clone, Debug)]
pub enum SceneImage {
@@ -744,7 +752,11 @@ impl<'a> VelloSceneBuilder<'a> {
fn set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> {
let (paint, paint_to_brush) = match brush {
SceneBrush::Apollonian(gradient) => {
self.scene.set_pencil_gradient_paint(gradient.clone());
self.scene.set_apollonian_gradient_paint(gradient.clone());
return Some(Affine::IDENTITY);
}
SceneBrush::Polar(gradient) => {
self.scene.set_polar_gradient_paint(gradient.clone());
return Some(Affine::IDENTITY);
}
SceneBrush::Peniko(BrushRef::Solid(color)) => (PaintType::Solid(color), Affine::IDENTITY),
@@ -575,6 +575,114 @@ fn apollonian_gradients_match_their_cpu_evaluation() {
}
}
#[test]
fn across_gradients_match_their_cpu_evaluation() {
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::radius_curvature;
use std::fmt::Write;
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100), and then sheared
let placements = [
DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.)),
DAffine2::from_cols(DVec2::new(50., 10.), DVec2::new(15., 35.), DVec2::new(60., 100.)),
];
let radius = radius_curvature;
let (standard, apollonian) = (GradientModel::Standard, GradientModel::Apollonian);
let settings = [
([0., 0.], standard, "the linear form"),
([-1., 0.5], standard, "the radial form"),
([radius(2.), radius(-1.)], standard, "concentric circles"),
([-1., radius(0.75)], standard, "a focal point inside the end circle, off its center"),
([radius(0.2), radius(1.5)], standard, "a focal circle nested inside the end circle"),
([radius(0.6), radius(0.6)], standard, "crossing circles"),
([radius(-0.2), radius(-0.4)], standard, "separate circles"),
([radius(0.8), 0.], standard, "an end line beside a start circle reaching past the end"),
([radius(0.45), 0.], standard, "an end line beside a start circle nearly reaching the end"),
([radius(0.6), 0.], standard, "an end line beside a start circle just past the end"),
([radius(3000.), radius(-4000.)], standard, "both ends nearly flat around an apex"),
([radius(2.), radius(-1.)], apollonian, "concentric Apollonian circles"),
([1., 0.3], apollonian, "Apollonian circles around the start point"),
([0.9, 0.2], apollonian, "nested Apollonian circles"),
([0.8, 1.], apollonian, "Apollonian circles around the end point"),
([1., 1.], apollonian, "Apollonian circles of two points"),
([0.6, 0.6], apollonian, "crossing Apollonian circles"),
([0.5, 0.25], apollonian, "crossing Apollonian circles of different sizes"),
];
let mut report = String::new();
for (curvatures, model, setting) in settings {
for placement in placements {
for spread in [GradientSpread::Pad, GradientSpread::Repeat] {
let Some(line) = compare_across_gradient_with_cpu(curvatures, model, placement, spread, setting) else {
return;
};
let _ = writeln!(report, "{line}");
}
}
}
eprintln!("{report}");
}
/// Renders a black to white gradient read across its contours, with these curvatures and model, placed by `placement` and read with `spread`, into a
/// 200 by 200 view, and checks each pixel against the CPU's evaluation, returning a line describing how they compare, or `None` without a GPU.
fn compare_across_gradient_with_cpu(curvatures: [f64; 2], model: GradientModel, placement: DAffine2, spread: GradientSpread, setting: &str) -> Option<String> {
use core_types::list::{ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_SPREAD};
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::GradientShape;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
let graphic = match curved_black_to_white_gradient(placement, Some(curvatures), model) {
graphic_types::Graphic::Gradient(item) => {
graphic_types::Graphic::Gradient(item.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across).with_attribute(ATTR_GRADIENT_SPREAD, spread))
}
graphic => graphic,
};
let pixels = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
// The CPU's level at a point on the screen, or `None` where it's unpainted, which the spread repeats only where the position doesn't wind
let GradientShape::Across(across) = GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Across, placement) else {
panic!("{setting} should be read across its contours");
};
let to_gradient = placement.inverse();
let level_at = |point: DVec2| {
let v = across.chart.v(to_gradient.transform_point2(point))?;
let position = match spread {
_ if across.chart.winds() => v,
GradientSpread::Repeat => v - v.floor(),
_ => v.clamp(0., 1.),
};
Some((position * 255.).round() as i32)
};
let expected = |x: i32, y: i32| level_at(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
// Each pixel takes the level at its center, except within two pixels of a seam where the position wraps, a step, or an edge of the painted area, which only rounding and antialiasing tell apart
let (mut worst, mut beside_steps, mut disagreements) = (0, 0, 0);
for y in 2..size.y as i32 - 2 {
for x in 2..size.x as i32 - 2 {
let neighborhood: Vec<Option<i32>> = (-2..=2).flat_map(|dy| (-2..=2).map(move |dx| (x + dx, y + dy))).map(|(x, y)| expected(x, y)).collect();
let painted_neighbors = neighborhood.iter().filter(|level| level.is_some()).count();
let levels = neighborhood.iter().flatten();
let (lowest, highest) = (*levels.clone().min().unwrap_or(&0), *levels.max().unwrap_or(&255));
let [red, _, _, alpha] = pixel(&pixels, size, x as u32, y as u32);
match (alpha, expected(x, y)) {
(0, None) => {}
(255, Some(level)) if painted_neighbors == 25 && highest - lowest <= 64 => worst = worst.max((red as i32 - level).abs()),
(255, Some(_)) => beside_steps += 1,
_ if painted_neighbors != 0 && painted_neighbors != 25 => {}
_ => disagreements += 1,
}
}
}
let context = format!("{setting} {curvatures:?}, {spread:?}, placed by {placement:?}");
assert!(worst <= 3, "{context}: up to {worst} levels from the CPU");
assert_eq!(disagreements, 0, "{context}: pixels disagreeing with the CPU on being painted");
Some(format!("{context}: within {worst} levels, {beside_steps} pixels beside seams and steps"))
}
#[test]
fn one_stop_curved_gradients_leave_their_gaps_unpainted() {
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, Item};