mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 00:34:25 +00:00
One fill for a closed polygon
PaintShape::Polygon is any closed polygon whose edges don't cross. kit::fill_polygon fills it as one mesh: egui's edge fade around the outline and an ear-clipped inside, so the parts of one shape meet without a seam. Draw fills every polygon with it. Chart wedges and area polygons fill as one polygon each, and the eyedropper ring band as one polygon, in place of runs of convex pieces whose faded edges left seams between them.
This commit is contained in:
@@ -311,13 +311,11 @@ fn arc(center: Pos2, radius: f32, from: f32, to: f32) -> Vec<Pos2> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A band of `color` between the radii `inner` and `outer` over the angles `from` to `to`, as convex quads.
|
||||
/// A band of `color` between the radii `inner` and `outer` over the angles `from` to `to`.
|
||||
fn band(draw: &Draw<'_>, center: Pos2, (inner, outer): (f32, f32), (from, to): (f32, f32), color: Srgba) {
|
||||
let (near, far) = (arc(center, inner, from, to), arc(center, outer, from, to));
|
||||
for at in 0..RING_SEGMENTS {
|
||||
let quad = vec![near[at], far[at], far[at + 1], near[at + 1]];
|
||||
draw.data_fill(&PaintShape::Polygon(quad), DataColor::new(Color32::from(color)));
|
||||
}
|
||||
let mut outline = arc(center, inner, from, to);
|
||||
outline.extend(arc(center, outer, from, to).into_iter().rev());
|
||||
draw.data_fill(&PaintShape::Polygon(outline), DataColor::new(Color32::from(color)));
|
||||
}
|
||||
|
||||
impl CanvasTool for EyedropperTool<'_> {
|
||||
|
||||
@@ -14,8 +14,6 @@ const MIN_STROKE_ZOOM: f32 = 0.5;
|
||||
const WEDGE_STEP: f32 = 0.05;
|
||||
/// A wedge has between these many steps.
|
||||
const WEDGE_STEPS: (usize, usize) = (2, 400);
|
||||
/// Cross products smaller than this are collinear when testing a polygon for convexity.
|
||||
const COLLINEAR: f32 = 1e-3;
|
||||
|
||||
/// Horizontal text anchor.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
@@ -258,11 +256,9 @@ impl ChartPrimitive {
|
||||
}
|
||||
|
||||
/// Paints `primitives` with their origin at `origin`, scaled by `zoom`: rects (stroked inside), lines (dashed in the
|
||||
/// theme's dash pattern when asked), polygons (a convex one whole, else as the vertical strips of an area chart's
|
||||
/// polygon: its top edge along the first half of the points and its baseline back along the second half, exact for
|
||||
/// an area chart's "mountain" shape), wedges as one convex shape per step of 0.05 rad (2…400 steps), circles, and
|
||||
/// text anchored by its alignment. A document line width scales with `zoom`, never below half its width; a theme
|
||||
/// width stays as the theme gives it.
|
||||
/// theme's dash pattern when asked), polygons, wedges as one polygon whose arcs take a point per 0.05 rad (2…400
|
||||
/// steps), circles, and text anchored by its alignment. A document line width scales with `zoom`, never below half
|
||||
/// its width; a theme width stays as the theme gives it.
|
||||
pub fn paint_chart(draw: &Draw<'_>, origin: Pos2, primitives: &[ChartPrimitive], zoom: f32) {
|
||||
let at = |x: f32, y: f32| pos2(origin.x + x * zoom, origin.y + y * zoom);
|
||||
let line_width = |width: DataStrokeWidth| width.scaled(zoom.max(MIN_STROKE_ZOOM));
|
||||
@@ -298,36 +294,24 @@ pub fn paint_chart(draw: &Draw<'_>, origin: Pos2, primitives: &[ChartPrimitive],
|
||||
if points.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
if is_convex(&points) {
|
||||
draw.data_fill(&PaintShape::Polygon(points.clone()), *fill);
|
||||
} else {
|
||||
for strip in area_strips(&points) {
|
||||
draw.data_fill(&PaintShape::Polygon(strip.to_vec()), *fill);
|
||||
}
|
||||
}
|
||||
outline(&PaintShape::Polygon(points), stroke);
|
||||
let shape = PaintShape::Polygon(points);
|
||||
draw.data_fill(&shape, *fill);
|
||||
outline(&shape, stroke);
|
||||
}
|
||||
ChartPrimitive::Wedge { center_x, center_y, outer_radius, inner_radius, start_angle, end_angle, fill, stroke } => {
|
||||
let centre = at(*center_x, *center_y);
|
||||
let steps = (((end_angle - start_angle).abs() / WEDGE_STEP).ceil() as usize).clamp(WEDGE_STEPS.0, WEDGE_STEPS.1);
|
||||
let on = |angle: f32, radius: f32| pos2(centre.x + radius * zoom * angle.sin(), centre.y - radius * zoom * angle.cos());
|
||||
let angle = |i: usize| start_angle + (end_angle - start_angle) * i as f32 / steps as f32;
|
||||
for i in 0..steps {
|
||||
let (a, b) = (angle(i), angle(i + 1));
|
||||
let step = if *inner_radius > 0.0 {
|
||||
vec![on(a, *outer_radius), on(b, *outer_radius), on(b, *inner_radius), on(a, *inner_radius)]
|
||||
} else {
|
||||
vec![on(a, *outer_radius), on(b, *outer_radius), centre]
|
||||
};
|
||||
draw.data_fill(&PaintShape::Polygon(step), *fill);
|
||||
}
|
||||
let mut edge: Vec<Pos2> = (0..=steps).map(|i| on(angle(i), *outer_radius)).collect();
|
||||
if *inner_radius > 0.0 {
|
||||
edge.extend((0..=steps).rev().map(|i| on(angle(i), *inner_radius)));
|
||||
} else {
|
||||
edge.push(centre);
|
||||
}
|
||||
outline(&PaintShape::Polygon(edge), stroke);
|
||||
let shape = PaintShape::Polygon(edge);
|
||||
draw.data_fill(&shape, *fill);
|
||||
outline(&shape, stroke);
|
||||
}
|
||||
ChartPrimitive::Circle { center_x, center_y, radius, fill, stroke } => {
|
||||
let shape = PaintShape::Circle(at(*center_x, *center_y), radius * zoom);
|
||||
@@ -362,28 +346,3 @@ pub fn paint_chart(draw: &Draw<'_>, origin: Pos2, primitives: &[ChartPrimitive],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the closed path turns one way throughout.
|
||||
fn is_convex(points: &[Pos2]) -> bool {
|
||||
let n = points.len();
|
||||
let mut sign = 0.0f32;
|
||||
for i in 0..n {
|
||||
let (a, b, c) = (points[i], points[(i + 1) % n], points[(i + 2) % n]);
|
||||
let cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x);
|
||||
if cross.abs() > COLLINEAR {
|
||||
if sign == 0.0 {
|
||||
sign = cross.signum();
|
||||
} else if cross.signum() != sign {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The vertical strips of an area chart's polygon, each a convex quad: the top edge runs along the first half of
|
||||
/// the points and the baseline back along the second half.
|
||||
fn area_strips(points: &[Pos2]) -> Vec<[Pos2; 4]> {
|
||||
let n = points.len();
|
||||
(0..(n / 2).saturating_sub(1)).map(|i| [points[i], points[i + 1], points[n - 2 - i], points[n - 1 - i]]).collect()
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ pub enum PaintShape {
|
||||
Rect(Rect, CornerRadius),
|
||||
/// A circle.
|
||||
Circle(Pos2, f32),
|
||||
/// A convex polygon.
|
||||
/// A closed polygon, convex or not, whose edges don't cross.
|
||||
Polygon(Vec<Pos2>),
|
||||
/// An open path.
|
||||
Path(Vec<Pos2>),
|
||||
@@ -493,7 +493,21 @@ impl<'a> Draw<'a> {
|
||||
let shape = match shape {
|
||||
PaintShape::Rect(rect, radius) => Shape::Rect(RectShape::new(*rect, *radius, fill_color, stroke, StrokeKind::Inside)),
|
||||
PaintShape::Circle(center, radius) => Shape::Circle(CircleShape { center: *center, radius: *radius, fill: fill_color, stroke }),
|
||||
PaintShape::Polygon(points) => Shape::convex_polygon(points.clone(), fill_color, stroke),
|
||||
PaintShape::Polygon(points) => {
|
||||
if fill.is_some() {
|
||||
let feather = self.painter.ctx().tessellation_options(|options| {
|
||||
if options.feathering { options.feathering_size_in_pixels / self.painter.pixels_per_point() } else { 0.0 }
|
||||
});
|
||||
let mesh = super::kit::fill_polygon(points, fill_color, feather);
|
||||
if !mesh.is_empty() {
|
||||
self.painter.add(Shape::mesh(mesh));
|
||||
}
|
||||
}
|
||||
if stroke.is_empty() {
|
||||
return;
|
||||
}
|
||||
Shape::closed_line(points.clone(), stroke)
|
||||
}
|
||||
PaintShape::Path(points) => Shape::line(points.clone(), stroke),
|
||||
};
|
||||
self.painter.add(shape);
|
||||
|
||||
@@ -138,6 +138,106 @@ fn checker_texture(ctx: &Context, light: Color32, dark: Color32) -> TextureId {
|
||||
TextureCache::texture_with(ctx, ("craft-ui-checker", light, dark), options, || ColorImage::new([2, 2], vec![light, dark, dark, light]))
|
||||
}
|
||||
|
||||
/// A turn whose cross product is at most this (in square points) is straight: its vertex is cut away without a
|
||||
/// triangle.
|
||||
const FLAT_TURN: f32 = 1e-4;
|
||||
|
||||
/// The closed polygon through `points` (convex or not; its edges must not cross) filled with `color`, as one mesh:
|
||||
/// the edge fades out over `feather` points as egui fades a convex fill (0 for a hard edge), and the inside is cut
|
||||
/// into triangles by ear clipping, so the parts of one shape meet without a seam. Either winding fills; a last point
|
||||
/// equal to the first is dropped. The one polygon fill: `Draw` fills every `PaintShape::Polygon` with it.
|
||||
pub fn fill_polygon(points: &[Pos2], color: Color32, feather: f32) -> Mesh {
|
||||
let mut mesh = Mesh::default();
|
||||
let mut ring = points.to_vec();
|
||||
ring.dedup();
|
||||
if ring.len() > 1 && ring.first() == ring.last() {
|
||||
ring.pop();
|
||||
}
|
||||
let n = ring.len();
|
||||
if n < 3 || color == Color32::TRANSPARENT || ring.iter().any(|p| !p.is_finite()) {
|
||||
return mesh;
|
||||
}
|
||||
// Clockwise on screen (y down), the winding egui's fill and its edge normals expect.
|
||||
let doubled_area: f32 = (0..n).map(|i| ring[i].x * ring[(i + 1) % n].y - ring[(i + 1) % n].x * ring[i].y).sum();
|
||||
if doubled_area < 0.0 {
|
||||
ring.reverse();
|
||||
}
|
||||
let triangles = ear_clip(&ring);
|
||||
if feather > 0.0 {
|
||||
// An opaque inner and a clear outer vertex per point, half the feather each side of the edge (egui's
|
||||
// `fill_closed_path`), with the normals of egui's `Path::add_line_loop`.
|
||||
let edge_normal = |i: usize| (ring[(i + 1) % n] - ring[i]).normalized().rot90();
|
||||
for i in 0..n {
|
||||
let (before, after) = (edge_normal((i + n - 1) % n), edge_normal(i));
|
||||
let normal = (before + after) * 0.5;
|
||||
let length_sq = normal.length_sq();
|
||||
let normal = if length_sq > f32::EPSILON { normal / length_sq } else { after };
|
||||
mesh.colored_vertex(ring[i] - normal * (0.5 * feather), color);
|
||||
mesh.colored_vertex(ring[i] + normal * (0.5 * feather), Color32::TRANSPARENT);
|
||||
}
|
||||
for i in 0..n as u32 {
|
||||
let before = (i + n as u32 - 1) % n as u32;
|
||||
mesh.add_triangle(2 * i, 2 * before, 2 * before + 1);
|
||||
mesh.add_triangle(2 * before + 1, 2 * i + 1, 2 * i);
|
||||
}
|
||||
for [a, b, c] in triangles {
|
||||
mesh.add_triangle(2 * a, 2 * b, 2 * c);
|
||||
}
|
||||
} else {
|
||||
for &point in &ring {
|
||||
mesh.colored_vertex(point, color);
|
||||
}
|
||||
for [a, b, c] in triangles {
|
||||
mesh.add_triangle(a, b, c);
|
||||
}
|
||||
}
|
||||
mesh
|
||||
}
|
||||
|
||||
/// The triangles that cover the clockwise (on screen) polygon `ring`, as indices into it: each turn is cut off as an
|
||||
/// ear when no reflex vertex lies inside it. Only reflex vertices can lie inside an ear, so a convex polygon takes
|
||||
/// one pass. A polygon whose edges cross still ends: when a whole round finds no ear, the next turn is cut anyway.
|
||||
fn ear_clip(ring: &[Pos2]) -> Vec<[u32; 3]> {
|
||||
let n = ring.len();
|
||||
let turn = |a: usize, b: usize, c: usize| {
|
||||
let (a, b, c) = (ring[a], ring[b], ring[c]);
|
||||
(b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)
|
||||
};
|
||||
let side = |a: Pos2, b: Pos2, p: Pos2| (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x);
|
||||
let inside = |p: Pos2, a: Pos2, b: Pos2, c: Pos2| side(a, b, p) > 0.0 && side(b, c, p) > 0.0 && side(c, a, p) > 0.0;
|
||||
let mut prev: Vec<usize> = (0..n).map(|i| (i + n - 1) % n).collect();
|
||||
let mut next: Vec<usize> = (0..n).map(|i| (i + 1) % n).collect();
|
||||
let mut reflex: Vec<bool> = (0..n).map(|i| turn(prev[i], i, next[i]) < -FLAT_TURN).collect();
|
||||
let reflex_at: Vec<usize> = (0..n).filter(|&i| reflex[i]).collect();
|
||||
let mut removed = vec![false; n];
|
||||
let mut triangles = Vec::with_capacity(n - 2);
|
||||
let (mut at, mut left, mut misses) = (0, n, 0);
|
||||
while left > 3 {
|
||||
let (a, c) = (prev[at], next[at]);
|
||||
let bend = turn(a, at, c);
|
||||
let flat = bend.abs() <= FLAT_TURN;
|
||||
let ear = flat
|
||||
|| bend > 0.0 && !reflex_at.iter().any(|&j| reflex[j] && !removed[j] && j != a && j != c && inside(ring[j], ring[a], ring[at], ring[c]));
|
||||
if ear || misses > left {
|
||||
if !flat {
|
||||
triangles.push([a as u32, at as u32, c as u32]);
|
||||
}
|
||||
removed[at] = true;
|
||||
(next[a], prev[c]) = (c, a);
|
||||
for v in [a, c] {
|
||||
reflex[v] = turn(prev[v], v, next[v]) < -FLAT_TURN;
|
||||
}
|
||||
(at, left, misses) = (c, left - 1, 0);
|
||||
} else {
|
||||
(at, misses) = (next[at], misses + 1);
|
||||
}
|
||||
}
|
||||
if turn(prev[at], at, next[at]).abs() > FLAT_TURN {
|
||||
triangles.push([prev[at] as u32, at as u32, next[at] as u32]);
|
||||
}
|
||||
triangles
|
||||
}
|
||||
|
||||
/// The samples along each rounded corner of a ramp, so the strip's edge follows the arc.
|
||||
const ARC_STEPS: usize = 8;
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ pub use icon::{Glyph, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_name
|
||||
pub use ime_surface::ImeSurface;
|
||||
pub use kit::{
|
||||
Checker, CheckerArea, GridAxis, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, ellipse,
|
||||
grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks,
|
||||
fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks,
|
||||
};
|
||||
pub use marker::{Marker, MarkerSize};
|
||||
pub use reset_mark::ResetMark;
|
||||
|
||||
@@ -22,6 +22,44 @@ fn ellipse_points_lie_on_the_ellipse_whatever_the_conjugate_axes() {
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_concave_polygon_fills_its_area_once_in_either_winding() {
|
||||
use egui::{Color32, Pos2};
|
||||
|
||||
let cross = |a: Pos2, b: Pos2, c: Pos2| (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
|
||||
let area = |ring: &[Pos2]| (0..ring.len()).map(|i| cross(Pos2::ZERO, ring[i], ring[(i + 1) % ring.len()])).sum::<f32>().abs() / 2.0;
|
||||
// Even-odd ray cast to the right.
|
||||
let inside = |ring: &[Pos2], p: Pos2| {
|
||||
(0..ring.len()).fold(false, |odd, i| {
|
||||
let (a, b) = (ring[i], ring[(i + 1) % ring.len()]);
|
||||
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { !odd } else { odd }
|
||||
})
|
||||
};
|
||||
let ell = vec![pos2(0.0, 0.0), pos2(40.0, 0.0), pos2(40.0, 10.0), pos2(10.0, 10.0), pos2(10.0, 30.0), pos2(0.0, 30.0)];
|
||||
// A doughnut sector over 2 rad: the outer arc out, the inner arc back.
|
||||
let on = |radius: f32, i: usize| {
|
||||
let angle = 2.0 * i as f32 / 40.0;
|
||||
pos2(60.0 + radius * angle.sin(), 60.0 - radius * angle.cos())
|
||||
};
|
||||
let sector: Vec<Pos2> = (0..=40).map(|i| on(50.0, i)).chain((0..=40).rev().map(|i| on(25.0, i))).collect();
|
||||
|
||||
for shape in [ell, sector] {
|
||||
for ring in [shape.clone(), shape.iter().rev().copied().collect()] {
|
||||
let mesh = craft_ui::primitives::fill_polygon(&ring, Color32::WHITE, 0.0);
|
||||
let triangles: Vec<[Pos2; 3]> = mesh.indices.chunks(3).map(|t| [0, 1, 2].map(|k| mesh.vertices[t[k] as usize].pos)).collect();
|
||||
let turns: Vec<f32> = triangles.iter().map(|&[a, b, c]| cross(a, b, c)).collect();
|
||||
assert!(turns.iter().all(|t| *t > 0.0) || turns.iter().all(|t| *t < 0.0), "every triangle turns the same way");
|
||||
let covered: f32 = turns.iter().map(|t| t.abs() / 2.0).sum();
|
||||
let whole = area(&ring);
|
||||
assert!((covered - whole).abs() < whole * 1e-3, "the triangles cover {covered}, the polygon {whole}");
|
||||
for [a, b, c] in triangles {
|
||||
let centroid = pos2((a.x + b.x + c.x) / 3.0, (a.y + b.y + c.y) / 3.0);
|
||||
assert!(inside(&ring, centroid), "a triangle around {centroid:?} lies outside the polygon");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_rounded_ramp_keeps_inside_its_corners_and_a_square_one_fills_its_rect() {
|
||||
use craft_behavior::Axis;
|
||||
|
||||
Reference in New Issue
Block a user