1use crate::{Color, Rect, State, Vec2, Vec3, Vec4, effects, vec2};
30use std::f32::consts::{FRAC_PI_2, PI, TAU};
31
32#[derive(Clone, Copy, Debug, PartialEq)]
51pub enum Fill {
52 Solid(Color),
54 Linear {
56 from: Vec2,
57 to: Vec2,
58 start: Color,
59 end: Color,
60 },
61 Radial {
63 center: Vec2,
64 radius: f32,
65 inner: Color,
66 outer: Color,
67 },
68}
69
70impl From<Color> for Fill {
71 fn from(color: Color) -> Self {
72 Self::Solid(color)
73 }
74}
75
76impl Fill {
77 pub fn linear(from: Vec2, to: Vec2, start: Color, end: Color) -> Self {
79 Self::Linear {
80 from,
81 to,
82 start,
83 end,
84 }
85 }
86 pub fn vertical(rect: Rect, top: Color, bottom: Color) -> Self {
88 Self::linear(
89 vec2(rect.x, rect.y),
90 vec2(rect.x, rect.y + rect.h),
91 top,
92 bottom,
93 )
94 }
95 pub fn horizontal(rect: Rect, left: Color, right: Color) -> Self {
97 Self::linear(
98 vec2(rect.x, rect.y),
99 vec2(rect.x + rect.w, rect.y),
100 left,
101 right,
102 )
103 }
104 pub fn radial(center: Vec2, radius: f32, inner: Color, outer: Color) -> Self {
106 Self::Radial {
107 center,
108 radius,
109 inner,
110 outer,
111 }
112 }
113 pub fn at(&self, p: Vec2) -> Color {
115 match *self {
116 Self::Solid(c) => c,
117 Self::Linear {
118 from,
119 to,
120 start,
121 end,
122 } => {
123 let axis = to - from;
124 let len2 = axis.length_squared();
125 let t = if len2 > 0. {
126 ((p - from).dot(axis) / len2).clamp(0., 1.)
127 } else {
128 0.
129 };
130 mix(start, end, t)
131 }
132 Self::Radial {
133 center,
134 radius,
135 inner,
136 outer,
137 } => {
138 let t = if radius > 0. {
139 ((p - center).length() / radius).clamp(0., 1.)
140 } else {
141 1.
142 };
143 mix(inner, outer, t)
144 }
145 }
146 }
147 fn is_finite(&self) -> bool {
148 let c = |c: Color| c.r.is_finite() && c.g.is_finite() && c.b.is_finite() && c.a.is_finite();
149 match *self {
150 Self::Solid(a) => c(a),
151 Self::Linear {
152 from,
153 to,
154 start,
155 end,
156 } => from.is_finite() && to.is_finite() && c(start) && c(end),
157 Self::Radial {
158 center,
159 radius,
160 inner,
161 outer,
162 } => center.is_finite() && radius.is_finite() && c(inner) && c(outer),
163 }
164 }
165}
166
167pub fn mix(a: Color, b: Color, t: f32) -> Color {
169 Color::new(
170 a.r + (b.r - a.r) * t,
171 a.g + (b.g - a.g) * t,
172 a.b + (b.b - a.b) * t,
173 a.a + (b.a - a.a) * t,
174 )
175}
176
177fn fade(c: Color, alpha: f32) -> Color {
178 Color::new(c.r, c.g, c.b, c.a * alpha)
179}
180
181#[derive(Clone, Copy, Debug, PartialEq)]
189pub struct Shadow {
190 pub color: Color,
192 pub offset: Vec2,
194 pub blur: f32,
196 pub spread: f32,
198}
199
200impl Shadow {
201 pub fn soft(color: Color) -> Self {
203 Self {
204 color,
205 offset: vec2(0., 4.),
206 blur: 16.,
207 spread: 0.,
208 }
209 }
210 pub fn offset(mut self, offset: Vec2) -> Self {
211 self.offset = offset;
212 self
213 }
214 pub fn blur(mut self, blur: f32) -> Self {
215 self.blur = blur;
216 self
217 }
218 pub fn spread(mut self, spread: f32) -> Self {
219 self.spread = spread;
220 self
221 }
222}
223
224#[derive(Clone, Copy, Debug, Default, PartialEq)]
226pub enum Join {
227 #[default]
229 Miter,
230 Bevel,
232 Round,
234}
235
236#[derive(Clone, Copy, Debug, Default, PartialEq)]
238pub enum Cap {
239 #[default]
241 Butt,
242 Square,
244 Round,
246}
247
248#[derive(Clone, Copy, Debug, PartialEq)]
256pub struct Stroke {
257 pub width: f32,
258 pub color: Color,
259 pub join: Join,
260 pub cap: Cap,
261 pub closed: bool,
263}
264
265impl Stroke {
266 pub fn new(width: f32, color: Color) -> Self {
267 Self {
268 width,
269 color,
270 join: Join::Miter,
271 cap: Cap::Butt,
272 closed: false,
273 }
274 }
275 pub fn join(mut self, join: Join) -> Self {
276 self.join = join;
277 self
278 }
279 pub fn cap(mut self, cap: Cap) -> Self {
280 self.cap = cap;
281 self
282 }
283 pub fn closed(mut self, closed: bool) -> Self {
284 self.closed = closed;
285 self
286 }
287}
288
289pub(crate) struct Sink<'a> {
295 pub(crate) s: &'a mut State,
296 start: u32,
297 x: Vec4,
299 y: Vec4,
300 w: Vec4,
301 plain: bool,
303}
304
305impl<'a> Sink<'a> {
306 pub(crate) fn new(s: &'a mut State) -> Self {
307 let start = s.vertices.len() as u32;
308 let m = s.matrix;
309 let plain = s.lighting.is_none() && !s.world_colors;
310 Self {
311 s,
312 start,
313 x: m.x_axis,
314 y: m.y_axis,
315 w: m.w_axis,
316 plain,
317 }
318 }
319 pub(crate) fn device_pixel(&self) -> f32 {
321 Self::device_pixel_of(self.s)
322 }
323 #[inline]
326 pub(crate) fn reserve(&mut self, count: usize) {
327 self.s.reserve_vertices(count);
328 }
329 #[inline]
333 fn project(&self, p: Vec2, mut c: Color) -> [f32; 8] {
334 if !self.plain {
335 c = self.shade(p, c);
336 }
337 let v = self.x * p.x + self.y * p.y + self.w;
338 [v.x, v.y, v.z, v.w, c.r, c.g, c.b, c.a]
339 }
340 #[inline(never)]
342 fn shade(&self, p: Vec2, mut c: Color) -> Color {
343 if let Some(l) = self.s.lighting {
344 c = l.shade_vertex(p.extend(0.), Vec3::Z, c);
345 }
346 if let Some(look) = self.s.world_look() {
347 c = look.shade(c);
348 }
349 c
350 }
351 #[inline]
352 pub(crate) fn tri(&mut self, a: Vec2, ca: Color, b: Vec2, cb: Color, c: Vec2, cc: Color) {
353 let v = [
354 self.project(a, ca),
355 self.project(b, cb),
356 self.project(c, cc),
357 ];
358 self.s.vertices.extend_from_slice(&v);
359 }
360 #[inline]
362 pub(crate) fn rect(&mut self, x: f32, y: f32, w: f32, h: f32, c: Color) {
363 self.rect_edges(x, y, x + w, y + h, c)
364 }
365 #[inline]
368 pub(crate) fn rect_edges(&mut self, left: f32, top: f32, right: f32, bottom: f32, c: Color) {
369 self.quad(
370 [
371 vec2(left, top),
372 vec2(right, top),
373 vec2(right, bottom),
374 vec2(left, bottom),
375 ],
376 [c; 4],
377 )
378 }
379 #[inline]
382 fn quad(&mut self, p: [Vec2; 4], c: [Color; 4]) {
383 let [a, b, e, d] = [0, 1, 2, 3].map(|i| self.project(p[i], c[i]));
384 self.s.vertices.extend_from_slice(&[a, b, d, d, b, e]);
385 }
386}
387
388impl Drop for Sink<'_> {
389 fn drop(&mut self) {
390 let count = self.s.vertices.len() as u32 - self.start;
391 if count > 0 {
392 let depth = self.s.depth;
393 self.s.record_immediate(self.start, count, depth);
394 }
395 }
396}
397
398const MAX_QUARTER: usize = 16;
403const MAX_POINTS: usize = 4 * (MAX_QUARTER + 1);
405const SIGNS: [Vec2; 4] = [vec2(1., 1.), vec2(-1., 1.), vec2(-1., -1.), vec2(1., -1.)];
407
408struct UnitTables {
412 quarter: [[Vec2; MAX_POINTS]; MAX_QUARTER + 1],
415 circle: [[Vec2; 4 * MAX_QUARTER + 1]; MAX_QUARTER + 1],
418}
419
420fn unit_tables() -> &'static UnitTables {
421 static TABLES: std::sync::OnceLock<UnitTables> = std::sync::OnceLock::new();
422 TABLES.get_or_init(|| {
423 let unit = |a: f32| vec2(a.cos(), a.sin());
424 let mut t = UnitTables {
425 quarter: [[Vec2::ZERO; MAX_POINTS]; MAX_QUARTER + 1],
426 circle: [[Vec2::ZERO; 4 * MAX_QUARTER + 1]; MAX_QUARTER + 1],
427 };
428 for s in 1..=MAX_QUARTER {
429 for i in 0..4 * (s + 1) {
430 let (quarter, step) = (i / (s + 1), i % (s + 1));
431 t.quarter[s][i] = unit((quarter as f32 + step as f32 / s as f32) * FRAC_PI_2);
432 }
433 let n = 4 * s;
434 for i in 0..n {
435 t.circle[s][i] = unit(i as f32 * TAU / n as f32);
436 }
437 t.circle[s][n] = t.circle[s][0];
438 }
439 t
440 })
441}
442
443pub(crate) fn unit_circle(n: usize) -> Option<&'static [Vec2]> {
447 (n.is_multiple_of(4) && (4..=4 * MAX_QUARTER).contains(&n))
448 .then(|| &unit_tables().circle[n / 4][..=n])
449}
450
451fn quarter_segments(radius_px: f32) -> usize {
453 if radius_px.is_nan() || radius_px <= 0.5 {
454 return 1;
455 }
456 ((radius_px.sqrt() * 1.5).ceil() as usize).clamp(2, MAX_QUARTER)
457}
458
459pub(crate) fn curve_segments(radius_px: f32) -> usize {
462 quarter_segments(radius_px) * 4
463}
464
465#[derive(Clone, Copy)]
467struct Outline {
468 center: Vec2,
469 ax: Vec2,
470 half: Vec2,
471 radius: f32,
472 segments: usize,
473}
474
475struct Ring {
477 points: [Vec2; MAX_POINTS],
478 colors: [Color; MAX_POINTS],
479}
480
481impl Outline {
482 fn new(rect: Rect, radius: f32, px: f32) -> Option<Self> {
483 if !(rect.is_finite() && radius.is_finite() && rect.w > 0. && rect.h > 0.) {
484 return None;
485 }
486 let half = vec2(rect.w, rect.h) * 0.5;
487 let radius = radius.clamp(0., half.x.min(half.y));
488 Some(Self {
489 center: vec2(rect.x, rect.y) + half,
490 ax: Vec2::X,
491 half,
492 radius,
493 segments: quarter_segments(radius / px),
494 })
495 }
496 fn points(&self) -> usize {
497 4 * (self.segments + 1)
498 }
499 fn ring(&self, offset: f32, fill: &Fill, alpha: f32) -> Ring {
502 let half = (self.half + Vec2::splat(offset)).max(Vec2::ZERO);
503 let radius = (self.radius + offset).clamp(0., half.x.min(half.y));
504 let corner = half - Vec2::splat(radius);
505 let ay = self.ax.perp();
506 let per = self.segments + 1;
507 let units = &unit_tables().quarter[self.segments.clamp(1, MAX_QUARTER)];
508 let mut ring = Ring {
509 points: [Vec2::ZERO; MAX_POINTS],
510 colors: [Color::new(0., 0., 0., 0.); MAX_POINTS],
511 };
512 for (q, sign) in SIGNS.into_iter().enumerate() {
513 let base = corner * sign;
514 let span = q * per..(q + 1) * per;
515 for (point, unit) in ring.points[span.clone()].iter_mut().zip(&units[span]) {
516 let local = base + *unit * radius;
517 *point = self.center + self.ax * local.x + ay * local.y;
518 }
519 }
520 let n = self.points();
521 match *fill {
522 Fill::Solid(c) => ring.colors[..n].fill(fade(c, alpha)),
523 _ => {
524 for (c, p) in ring.colors[..n].iter_mut().zip(&ring.points[..n]) {
525 *c = fade(fill.at(*p), alpha);
526 }
527 }
528 }
529 ring
530 }
531 fn fan(&self, sink: &mut Sink, ring: &Ring, fill: &Fill, alpha: f32) {
533 let n = self.points();
534 let center = fade(fill.at(self.center), alpha);
535 sink.reserve(n * 3);
536 let mut prev = n - 1;
537 for i in 0..n {
538 sink.tri(
539 self.center,
540 center,
541 ring.points[prev],
542 ring.colors[prev],
543 ring.points[i],
544 ring.colors[i],
545 );
546 prev = i;
547 }
548 }
549 fn strip(&self, sink: &mut Sink, inner: &Ring, outer: &Ring) {
551 let n = self.points();
552 sink.reserve(n * 6);
553 let mut prev = n - 1;
554 for i in 0..n {
555 sink.quad(
556 [
557 inner.points[prev],
558 inner.points[i],
559 outer.points[i],
560 outer.points[prev],
561 ],
562 [
563 inner.colors[prev],
564 inner.colors[i],
565 outer.colors[i],
566 outer.colors[prev],
567 ],
568 );
569 prev = i;
570 }
571 }
572}
573
574const MAX_EDGE: usize = 8;
576const MAX_DENSE: usize = MAX_POINTS + 4 * (MAX_EDGE - 1);
578const RADIAL_RINGS: usize = 4;
580
581fn radial_is_exact(outline: &Outline, center: Vec2, radius: f32, px: f32) -> bool {
585 let eps = px * 1e-3;
586 (outline.half.x - outline.half.y).abs() <= eps
587 && outline.radius >= outline.half.x - eps
588 && (center - outline.center).length() <= eps
589 && radius >= outline.radius - eps
590}
591
592fn filled_radial(outline: Outline, fill: Fill, radius: f32, sink: &mut Sink, px: f32) {
598 let f = px * 0.5;
599 let n = outline.points();
600 let per = outline.segments + 1;
601 let corner = outline.half - Vec2::splat(outline.radius);
602 let step = (radius * 0.5).max(px * 8.);
604 let pieces = |length: f32| ((length / step).ceil() as usize).clamp(1, MAX_EDGE);
605 let edges = [pieces(2. * corner.x), pieces(2. * corner.y)];
606 let dense = |offset: f32| {
607 let base = outline.ring(offset, &Fill::Solid(Color::new(0., 0., 0., 0.)), 0.);
608 let mut out = [Vec2::ZERO; MAX_DENSE];
609 let mut len = 0;
610 for q in 0..4 {
611 for &p in &base.points[q * per..(q + 1) * per] {
612 out[len] = p;
613 len += 1;
614 }
615 let pieces = edges[q % 2];
617 let (a, b) = (
618 base.points[(q + 1) * per - 1],
619 base.points[(q + 1) * per % n],
620 );
621 for j in 1..pieces {
622 out[len] = a + (b - a) * (j as f32 / pieces as f32);
623 len += 1;
624 }
625 }
626 (out, len)
627 };
628 let colors = |points: &[Vec2], alpha: f32| {
629 let mut out = [Color::new(0., 0., 0., 0.); MAX_DENSE];
630 for (c, p) in out.iter_mut().zip(points) {
631 *c = fade(fill.at(*p), alpha);
632 }
633 out
634 };
635 let (edge, len) = dense(-f);
636 let (outer, _) = dense(f);
637 let center = outline.center;
638 let rings =
639 ((outline.half.x.max(outline.half.y) / px / 16.).ceil() as usize).clamp(2, RADIAL_RINGS);
640 let scaled = |k: usize| {
641 let mut out = [Vec2::ZERO; MAX_DENSE];
642 let t = k as f32 / rings as f32;
643 for (o, p) in out.iter_mut().zip(&edge[..len]) {
644 *o = if k == rings {
645 *p
646 } else {
647 center + (*p - center) * t
648 };
649 }
650 out
651 };
652 sink.reserve(len * (3 + 6 * rings));
653 let hub = fill.at(center);
654 let mut ring = scaled(1);
655 let mut ring_colors = colors(&ring[..len], 1.);
656 let mut prev = len - 1;
657 for i in 0..len {
658 sink.tri(
659 center,
660 hub,
661 ring[prev],
662 ring_colors[prev],
663 ring[i],
664 ring_colors[i],
665 );
666 prev = i;
667 }
668 let band = |sink: &mut Sink, a: &[Vec2], ca: &[Color], b: &[Vec2], cb: &[Color]| {
669 let mut prev = len - 1;
670 for i in 0..len {
671 sink.quad(
672 [a[prev], a[i], b[i], b[prev]],
673 [ca[prev], ca[i], cb[i], cb[prev]],
674 );
675 prev = i;
676 }
677 };
678 for k in 2..=rings {
679 let next = scaled(k);
680 let next_colors = colors(&next[..len], 1.);
681 band(sink, &ring, &ring_colors, &next, &next_colors);
682 (ring, ring_colors) = (next, next_colors);
683 }
684 band(
685 sink,
686 &ring,
687 &ring_colors,
688 &outer,
689 &colors(&outer[..len], 0.),
690 );
691}
692
693fn filled(outline: Outline, fill: Fill, sink: &mut Sink, px: f32) {
694 if let Fill::Radial { center, radius, .. } = fill
695 && !radial_is_exact(&outline, center, radius, px)
696 {
697 return filled_radial(outline, fill, radius, sink, px);
698 }
699 let f = px * 0.5;
700 let inner = outline.ring(-f, &fill, 1.);
701 outline.fan(sink, &inner, &fill, 1.);
702 outline.strip(sink, &inner, &outline.ring(f, &fill, 0.));
703}
704
705fn stroked(outline: Outline, width: f32, color: Color, sink: &mut Sink, px: f32) {
706 let f = px * 0.5;
707 let half = (width * 0.5).max(f);
708 let alpha = (width / px).min(1.);
709 let fill = Fill::Solid(color);
710 let rings = [
711 outline.ring(-half - f, &fill, 0.),
712 outline.ring(-half + f, &fill, alpha),
713 outline.ring(half - f, &fill, alpha),
714 outline.ring(half + f, &fill, 0.),
715 ];
716 for pair in rings.windows(2) {
717 outline.strip(sink, &pair[0], &pair[1]);
718 }
719}
720
721fn with_sink<R>(draw: impl FnOnce(&mut Sink, f32) -> R) -> R {
722 crate::edit(|s| {
723 let mut sink = Sink::new(s);
724 let px = sink.device_pixel();
725 draw(&mut sink, px)
726 })
727}
728
729pub fn fill_rounded_rect(rect: Rect, radius: f32, fill: impl Into<Fill>) {
738 let fill = fill.into();
739 if !fill.is_finite() {
740 return;
741 }
742 with_sink(|sink, px| {
743 if let Some(outline) = Outline::new(rect, radius, px) {
744 filled(outline, fill, sink, px);
745 }
746 })
747}
748
749pub fn stroke_rounded_rect(rect: Rect, radius: f32, width: f32, color: Color) {
758 if !(width.is_finite() && width > 0. && Fill::Solid(color).is_finite()) {
759 return;
760 }
761 with_sink(|sink, px| {
762 if let Some(outline) = Outline::new(rect, radius, px) {
763 stroked(outline, width, color, sink, px);
764 }
765 })
766}
767
768fn circle_rect(center: Vec2, radius: f32) -> Rect {
769 Rect::new(
770 center.x - radius,
771 center.y - radius,
772 radius * 2.,
773 radius * 2.,
774 )
775}
776
777pub fn fill_circle(center: Vec2, radius: f32, fill: impl Into<Fill>) {
787 fill_rounded_rect(circle_rect(center, radius), radius, fill)
788}
789
790pub fn stroke_circle(center: Vec2, radius: f32, width: f32, color: Color) {
797 stroke_rounded_rect(circle_rect(center, radius), radius, width, color)
798}
799
800pub fn fill_capsule(a: Vec2, b: Vec2, radius: f32, fill: impl Into<Fill>) {
809 let fill = fill.into();
810 if !(a.is_finite() && b.is_finite() && radius.is_finite() && radius > 0. && fill.is_finite()) {
811 return;
812 }
813 let axis = (b - a).normalize_or(Vec2::X);
814 let length = (b - a).length();
815 with_sink(|sink, px| {
816 let outline = Outline {
817 center: (a + b) * 0.5,
818 ax: axis,
819 half: vec2(length * 0.5 + radius, radius),
820 radius,
821 segments: quarter_segments(radius / px),
822 };
823 filled(outline, fill, sink, px);
824 })
825}
826
827pub const MAX_POLYGON_POINTS: usize = 64;
829
830pub fn fill_polygon(points: &[Vec2], fill: impl Into<Fill>) {
853 let fill = fill.into();
854 let n = points.len();
855 if !(3..=MAX_POLYGON_POINTS).contains(&n)
856 || !fill.is_finite()
857 || !points.iter().all(|p| p.is_finite())
858 {
859 return;
860 }
861 let mut twice_area = 0.;
863 let mut centroid = Vec2::ZERO;
864 for i in 0..n {
865 let (a, b) = (points[i], points[(i + 1) % n]);
866 twice_area += a.x * b.y - b.x * a.y;
867 centroid += a;
868 }
869 centroid /= n as f32;
870 if !twice_area.is_finite() || twice_area.abs() < 1e-6 {
871 return;
872 }
873 let outward = if twice_area > 0. { -1. } else { 1. };
874 with_sink(|sink, px| {
875 let f = px * 0.5;
876 let mut inner = [Vec2::ZERO; MAX_POLYGON_POINTS];
877 let mut outer = [Vec2::ZERO; MAX_POLYGON_POINTS];
878 let mut colors = [Color::new(0., 0., 0., 0.); MAX_POLYGON_POINTS];
879 let mut clear = [Color::new(0., 0., 0., 0.); MAX_POLYGON_POINTS];
880 for i in 0..n {
881 let p = points[i];
882 let prev = points[(i + n - 1) % n];
883 let next = points[(i + 1) % n];
884 let edge_in = (p - prev).normalize_or_zero();
885 let edge_out = (next - p).normalize_or_zero();
886 let n_in = edge_in.perp() * outward;
888 let n_out = edge_out.perp() * outward;
889 let miter = (n_in + n_out).normalize_or(n_out);
890 let cos = miter.dot(n_out).abs().max(0.25);
891 let reach = f / cos;
892 inner[i] = p - miter * reach;
893 outer[i] = p + miter * reach;
894 let c = fill.at(p);
895 colors[i] = c;
896 clear[i] = fade(c, 0.);
897 }
898 let hub = fill.at(centroid);
899 sink.reserve(n * 9);
900 let mut prev = n - 1;
901 for i in 0..n {
902 sink.tri(
903 centroid,
904 hub,
905 inner[prev],
906 colors[prev],
907 inner[i],
908 colors[i],
909 );
910 sink.quad(
911 [inner[prev], inner[i], outer[i], outer[prev]],
912 [colors[prev], colors[i], clear[i], clear[prev]],
913 );
914 prev = i;
915 }
916 })
917}
918
919pub fn fill_triangle(a: Vec2, b: Vec2, c: Vec2, fill: impl Into<Fill>) {
926 fill_polygon(&[a, b, c], fill)
927}
928
929pub fn fill_sector(center: Vec2, radius: f32, start: f32, sweep: f32, fill: impl Into<Fill>) {
941 let fill = fill.into();
942 if !(center.is_finite()
943 && radius.is_finite()
944 && radius > 0.
945 && start.is_finite()
946 && sweep.is_finite()
947 && fill.is_finite())
948 || sweep == 0.
949 {
950 return;
951 }
952 if sweep.abs() >= TAU {
953 return fill_circle(center, radius, fill);
954 }
955 with_sink(|sink, px| {
956 let f = px * 0.5;
957 let steps = ((quarter_segments(radius / px) * 4) as f32 * sweep.abs() / TAU)
958 .ceil()
959 .clamp(1., 64.) as usize;
960 let hub = fill.at(center);
961 let point = |i: usize, r: f32| {
962 let a = start + sweep * i as f32 / steps as f32;
963 center + vec2(a.cos(), a.sin()) * r
964 };
965 sink.reserve(steps * 9 + 12);
966 let inner_r = (radius - f).max(0.);
967 for i in 0..steps {
968 let (a0, a1) = (point(i, inner_r), point(i + 1, inner_r));
969 let (b0, b1) = (point(i, radius + f), point(i + 1, radius + f));
970 let (c0, c1) = (fill.at(a0), fill.at(a1));
971 sink.tri(center, hub, a0, c0, a1, c1);
972 sink.quad([a0, a1, b1, b0], [c0, c1, fade(c1, 0.), fade(c0, 0.)]);
973 }
974 let sign = sweep.signum();
976 for (i, side) in [(0usize, -1.), (steps, 1.)] {
977 let tip = point(i, inner_r);
978 let dir = (tip - center).normalize_or_zero();
979 let out = dir.perp() * side * sign * f;
980 let (ch, ct) = (hub, fill.at(tip));
981 sink.quad(
982 [center, tip, tip + out, center + out],
983 [ch, ct, fade(ct, 0.), fade(ch, 0.)],
984 );
985 }
986 })
987}
988
989pub fn drop_shadow(rect: Rect, radius: f32, shadow: Shadow) {
998 let Shadow {
999 color,
1000 offset,
1001 blur,
1002 spread,
1003 } = shadow;
1004 if !(offset.is_finite() && blur.is_finite() && spread.is_finite()) {
1005 return;
1006 }
1007 let rect = Rect::new(
1008 rect.x + offset.x - spread,
1009 rect.y + offset.y - spread,
1010 rect.w + spread * 2.,
1011 rect.h + spread * 2.,
1012 );
1013 if !Fill::Solid(color).is_finite() {
1014 return;
1015 }
1016 with_sink(|sink, px| {
1017 let blur = blur.max(px);
1018 let Some(mut outline) = Outline::new(rect, radius + spread.max(0.), px) else {
1019 return;
1020 };
1021 outline.segments = quarter_segments((outline.radius + blur * 0.5) / px);
1022 let fill = Fill::Solid(color);
1023 let half = blur * 0.5;
1024 const T: [f32; 5] = [0., 0.25, 0.5, 0.75, 1.];
1026 let alpha = |t: f32| 1. - t * t * (3. - 2. * t);
1027 let rings = T.map(|t| outline.ring(-half + t * blur, &fill, alpha(t)));
1028 outline.fan(sink, &rings[0], &fill, 1.);
1029 for pair in rings.windows(2) {
1030 outline.strip(sink, &pair[0], &pair[1]);
1031 }
1032 })
1033}
1034
1035#[derive(Clone, Copy)]
1041struct Section(Vec2, [Vec2; 4]);
1042
1043struct Strokes<'s, 'a> {
1044 sink: &'s mut Sink<'a>,
1045 color: Color,
1046 alpha: f32,
1047 core: f32,
1049 fringe: f32,
1050 prev: Option<Section>,
1051}
1052
1053impl Strokes<'_, '_> {
1054 fn section(&mut self, p: Vec2, n: Vec2, scale: f32) {
1055 let outer = n * ((self.core + self.fringe) * scale);
1056 let inner = n * ((self.core - self.fringe).max(0.) * scale);
1057 let next = Section(p, [p + outer, p + inner, p - inner, p - outer]);
1058 if let Some(Section(center, prev)) = self.prev {
1059 let clear = fade(self.color, 0.);
1060 let solid = fade(self.color, self.alpha);
1061 let colors = [clear, solid, solid, clear];
1062 let q = next.1;
1063 for k in [0, 2] {
1064 self.sink.quad(
1065 [prev[k], q[k], q[k + 1], prev[k + 1]],
1066 [colors[k], colors[k], colors[k + 1], colors[k + 1]],
1067 );
1068 }
1069 if center == p {
1070 self.sink.tri(p, solid, prev[1], solid, q[1], solid);
1072 self.sink.tri(p, solid, q[2], solid, prev[2], solid);
1073 } else {
1074 self.sink.quad([prev[1], q[1], q[2], prev[2]], [solid; 4]);
1075 }
1076 }
1077 self.prev = Some(next);
1078 }
1079 fn break_strip(&mut self) {
1080 self.prev = None;
1081 }
1082 fn sweep(&mut self, p: Vec2, from: Vec2, angle: f32, steps: usize) {
1084 turn(0., angle, steps, |_, u| {
1085 let n = vec2(from.x * u.x - from.y * u.y, from.x * u.y + from.y * u.x);
1086 self.section(p, n, 1.);
1087 });
1088 }
1089 fn sweep_cap(&mut self, p: Vec2, from: Vec2, angle: f32, steps: usize) {
1095 turn(0., angle, steps, |_, u| {
1096 let n = vec2(from.x * u.x - from.y * u.y, from.x * u.y + from.y * u.x);
1097 let outer = n * (self.core + self.fringe);
1098 let inner = n * (self.core - self.fringe).max(0.);
1099 let next = Section(p, [p, p, p - inner, p - outer]);
1100 if let Some(Section(_, prev)) = self.prev {
1101 let clear = fade(self.color, 0.);
1102 let solid = fade(self.color, self.alpha);
1103 let q = next.1;
1104 self.sink
1105 .quad([prev[2], q[2], q[3], prev[3]], [solid, solid, clear, clear]);
1106 self.sink.tri(p, solid, q[2], solid, prev[2], solid);
1107 }
1108 self.prev = Some(next);
1109 });
1110 }
1111 fn cap(&mut self, p: Vec2, dir: Vec2, cap: Cap, start: bool, steps: usize) {
1112 let n = dir.perp();
1113 match cap {
1114 Cap::Butt => self.section(p, n, 1.),
1115 Cap::Square => {
1116 let shift = dir * self.core * if start { -1. } else { 1. };
1117 self.section(p + shift, n, 1.);
1118 if !start {
1119 return;
1120 }
1121 self.section(p, n, 1.);
1122 }
1123 Cap::Round => {
1124 if start {
1125 self.sweep_cap(p, -n, PI, steps * 2);
1126 self.break_strip();
1127 self.section(p, n, 1.);
1128 } else {
1129 self.section(p, n, 1.);
1130 self.break_strip();
1131 self.sweep_cap(p, n, PI, steps * 2);
1132 }
1133 }
1134 }
1135 }
1136 fn join(&mut self, p: Vec2, d_in: Vec2, d_out: Vec2, join: Join, steps: usize) {
1137 let n_in = d_in.perp();
1138 let n_out = d_out.perp();
1139 let cross = d_in.x * d_out.y - d_in.y * d_out.x;
1140 if cross.abs() < 1e-4 && d_in.dot(d_out) > 0. {
1141 self.section(p, n_in, 1.);
1142 return;
1143 }
1144 let miter = (n_in + n_out).normalize_or_zero();
1145 let cos = miter.dot(n_in);
1146 if join == Join::Miter && cos > 0.25 {
1147 self.section(p, miter, 1. / cos);
1148 return;
1149 }
1150 let angle = cross.atan2(d_in.dot(d_out));
1151 let steps = if join == Join::Round {
1152 ((angle.abs() / FRAC_PI_2) * steps as f32).ceil().max(1.) as usize
1153 } else {
1154 1
1155 };
1156 self.sweep(p, n_in, angle, steps);
1157 }
1158}
1159
1160fn turn(start: f32, sweep: f32, steps: usize, mut f: impl FnMut(usize, Vec2)) {
1166 const ANCHOR: usize = 16;
1167 let (ds, dc) = (sweep / steps as f32).sin_cos();
1168 let mut u = Vec2::ZERO;
1169 for i in 0..=steps {
1170 u = if i % ANCHOR == 0 || i == steps {
1171 let (s, c) = (start + sweep * i as f32 / steps as f32).sin_cos();
1172 vec2(c, s)
1173 } else {
1174 vec2(u.x * dc - u.y * ds, u.x * ds + u.y * dc)
1175 };
1176 f(i, u);
1177 }
1178}
1179
1180fn stroke_setup(px: f32, stroke: &Stroke) -> Option<(f32, f32, f32)> {
1181 if !(stroke.width.is_finite() && stroke.width > 0. && Fill::Solid(stroke.color).is_finite()) {
1182 return None;
1183 }
1184 let fringe = px * 0.5;
1185 let core = (stroke.width * 0.5).max(fringe);
1186 let alpha = (stroke.width / px).min(1.);
1187 Some((core, fringe, alpha))
1188}
1189
1190pub fn polyline(points: &[Vec2], stroke: Stroke) {
1204 if points.len() < 2 || !points.iter().all(|p| p.is_finite()) {
1205 return;
1206 }
1207 with_sink(|sink, px| {
1208 let Some((core, fringe, alpha)) = stroke_setup(px, &stroke) else {
1209 return;
1210 };
1211 let steps = quarter_segments(core / px).min(8);
1212 let eps = px * 1e-3;
1213 let n = points.len();
1215 let next_distinct =
1216 |from: usize| (from + 1..n).find(|&j| (points[j] - points[from]).length() > eps);
1217 let mut strokes = Strokes {
1218 sink,
1219 color: stroke.color,
1220 alpha,
1221 core,
1222 fringe,
1223 prev: None,
1224 };
1225 let closed = stroke.closed && n > 2;
1226 let Some(second) = next_distinct(0) else {
1228 return;
1229 };
1230 let last = {
1231 let mut i = 0;
1232 while let Some(j) = next_distinct(i) {
1233 i = j;
1234 }
1235 i
1236 };
1237 let closed = closed && (points[last] - points[0]).length() > eps;
1238 let first_dir = (points[second] - points[0]).normalize_or_zero();
1239 if closed {
1240 let closing = (points[0] - points[last]).normalize_or_zero();
1241 strokes.join(points[0], closing, first_dir, stroke.join, steps);
1242 } else {
1243 strokes.cap(points[0], first_dir, stroke.cap, true, steps);
1244 }
1245 let mut current = 0;
1246 let mut dir = first_dir;
1247 while let Some(next) = next_distinct(current) {
1248 let d_in = (points[next] - points[current]).normalize_or_zero();
1249 if current != 0 {
1250 strokes.join(points[current], dir, d_in, stroke.join, steps);
1251 }
1252 dir = d_in;
1253 current = next;
1254 }
1255 if closed {
1256 let closing = (points[0] - points[last]).normalize_or_zero();
1257 strokes.join(points[last], dir, closing, stroke.join, steps);
1258 strokes.join(points[0], closing, first_dir, stroke.join, steps);
1259 } else {
1260 strokes.cap(points[last], dir, stroke.cap, false, steps);
1261 }
1262 })
1263}
1264
1265pub fn stroke_arc(center: Vec2, radius: f32, start: f32, sweep: f32, stroke: Stroke) {
1277 if !(center.is_finite()
1278 && radius.is_finite()
1279 && radius > 0.
1280 && start.is_finite()
1281 && sweep.is_finite())
1282 || sweep == 0.
1283 {
1284 return;
1285 }
1286 if sweep.abs() >= TAU {
1287 return stroke_circle(center, radius, stroke.width, stroke.color);
1288 }
1289 with_sink(|sink, px| {
1290 let Some((core, fringe, alpha)) = stroke_setup(px, &stroke) else {
1291 return;
1292 };
1293 let cap_steps = quarter_segments(core / px).min(8);
1294 let steps = ((quarter_segments(radius / px) * 4) as f32 * sweep.abs() / TAU)
1295 .ceil()
1296 .clamp(1., 64.) as usize;
1297 let mut strokes = Strokes {
1298 sink,
1299 color: stroke.color,
1300 alpha,
1301 core,
1302 fringe,
1303 prev: None,
1304 };
1305 let sign = sweep.signum();
1306 turn(start, sweep, steps, |i, at| {
1307 if i == 0 || i == steps {
1308 let p = center + at * radius;
1309 strokes.cap(p, at.perp() * sign, stroke.cap, i == 0, cap_steps);
1310 } else {
1311 strokes.section(center + at * radius, at * -sign, 1.);
1312 }
1313 });
1314 })
1315}
1316
1317fn glow_segments(radius: f32, px: f32) -> usize {
1321 (quarter_segments(radius / px) * 4).clamp(12, 48)
1322}
1323
1324fn glow_units(n: usize) -> &'static [Vec2] {
1326 unit_circle(n).expect("glow segment counts are multiples of four in 12..=48")
1327}
1328
1329fn additive(emit: impl FnOnce(&mut Additive)) {
1332 let style = effects::EffectStyle {
1333 blend: effects::EffectBlend::Additive,
1334 depth_test: None,
1335 depth_write: false,
1336 };
1337 effects::write_triangles(style, |writer| emit(&mut Additive(writer)));
1338}
1339
1340struct Additive<'w, 's>(&'w mut effects::TriangleWriter<'s>);
1341
1342impl Additive<'_, '_> {
1343 #[inline]
1345 fn tri(&mut self, t: [(Vec2, Color); 3]) -> bool {
1346 self.0
1347 .push(t.map(|(p, c)| ([p.x, p.y, 0.], [c.r, c.g, c.b, c.a])))
1348 }
1349 fn bands(
1352 &mut self,
1353 rings: std::ops::Range<usize>,
1354 n: usize,
1355 point: impl Fn(usize, usize) -> (Vec2, Color),
1356 ) {
1357 for ring in rings {
1358 let (mut a, mut c) = (point(ring, 0), point(ring + 1, 0));
1359 for i in 0..n {
1360 let (b, d) = (point(ring, i + 1), point(ring + 1, i + 1));
1361 if !(self.tri([a, c, d]) && self.tri([a, d, b])) {
1362 return;
1363 }
1364 (a, c) = (b, d);
1365 }
1366 }
1367 }
1368}
1369
1370fn glow_rings(extent_px: f32) -> usize {
1373 ((extent_px / 14.).ceil() as usize).clamp(4, 12)
1374}
1375
1376pub fn glow_disc(center: Vec2, radius: f32, color: Color) {
1387 if !(center.is_finite() && radius.is_finite() && radius > 0. && Fill::Solid(color).is_finite())
1388 {
1389 return;
1390 }
1391 let px = crate::read(Sink::device_pixel_of);
1392 let n = glow_segments(radius, px);
1393 let rings = glow_rings(radius / px);
1394 let units = glow_units(n);
1395 let point = |ring: usize, i: usize| {
1396 let t = ring as f32 / rings as f32;
1397 (
1398 center + units[i] * radius * t,
1399 fade(color, (1. - t) * (1. - t)),
1400 )
1401 };
1402 additive(|out| {
1404 let hub = point(0, 0);
1405 let mut prev = point(1, 0);
1406 for k in 0..n {
1407 let next = point(1, k + 1);
1408 if !out.tri([hub, prev, next]) {
1409 return;
1410 }
1411 prev = next;
1412 }
1413 out.bands(1..rings, n, point);
1414 });
1415}
1416
1417pub fn glow_ring(center: Vec2, radius: f32, width: f32, color: Color) {
1427 if !(center.is_finite()
1428 && radius.is_finite()
1429 && radius > 0.
1430 && width.is_finite()
1431 && width > 0.
1432 && Fill::Solid(color).is_finite())
1433 {
1434 return;
1435 }
1436 let px = crate::read(Sink::device_pixel_of);
1437 let n = glow_segments(radius + width * 0.5, px);
1438 let side = glow_rings(width * 0.5 / px);
1440 let bands = 2 * side;
1441 let units = glow_units(n);
1442 let point = |band: usize, i: usize| {
1443 let u = band as f32 / side as f32 - 1.;
1444 let r = (radius + u * width * 0.5).max(0.);
1445 let falloff = 1. - u.abs();
1446 (center + units[i] * r, fade(color, falloff * falloff))
1447 };
1448 additive(|out| out.bands(0..bands, n, point));
1449}
1450
1451impl Sink<'_> {
1452 pub(crate) fn device_pixel_of(s: &State) -> f32 {
1453 let m = s.matrix;
1454 let x = vec2(m.x_axis.x * s.w as f32, m.x_axis.y * s.h as f32) * 0.5;
1455 let ppu = x.length();
1456 if ppu.is_finite() && ppu > 1e-6 {
1457 1. / ppu
1458 } else {
1459 1.
1460 }
1461 }
1462}
1463
1464#[cfg(test)]
1465pub(crate) mod tests {
1466 use super::*;
1467 use crate::input::host_frame;
1468
1469 pub(crate) fn capture(w: u32, h: u32, draw: impl FnOnce()) -> Vec<[f32; 8]> {
1471 host_frame(1. / 60., w, h, draw);
1472 crate::read(|s| s.vertices.clone())
1473 }
1474
1475 fn screen(v: &[f32; 8], w: f32, h: f32) -> Vec2 {
1476 vec2((v[0] + 1.) * w * 0.5, (1. - v[1]) * h * 0.5)
1477 }
1478
1479 fn bounds(vertices: &[[f32; 8]], w: f32, h: f32, opaque: bool) -> [f32; 4] {
1480 let mut b = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
1481 for v in vertices.iter().filter(|v| !opaque || v[7] > 0.999) {
1482 let p = screen(v, w, h);
1483 b = [b[0].min(p.x), b[1].min(p.y), b[2].max(p.x), b[3].max(p.y)];
1484 }
1485 b
1486 }
1487
1488 #[test]
1489 fn rounded_rect_core_and_fringe_straddle_the_edge_by_half_a_pixel() {
1490 let v = capture(400, 300, || {
1491 fill_rounded_rect(
1492 Rect::new(10., 20., 100., 50.),
1493 8.,
1494 Color::new(1., 0., 0., 1.),
1495 )
1496 });
1497 assert!(v.len() <= 612 && v.len() % 3 == 0, "{}", v.len());
1498 let outer = bounds(&v, 400., 300., false);
1499 let core = bounds(&v, 400., 300., true);
1500 for (o, e) in outer.iter().zip([9.5, 19.5, 110.5, 70.5]) {
1501 assert!((o - e).abs() < 1e-3, "{outer:?}");
1502 }
1503 for (c, e) in core.iter().zip([10.5, 20.5, 109.5, 69.5]) {
1504 assert!((c - e).abs() < 1e-3, "{core:?}");
1505 }
1506 assert!(v.iter().all(|v| v[7] == 0. || v[7] == 1.));
1508 }
1509
1510 #[test]
1511 fn round_caps_cover_only_the_half_disc_beyond_each_end() {
1512 let area = |v: &[[f32; 8]]| -> f32 {
1515 v.chunks(3)
1516 .filter(|t| t.iter().all(|v| v[7] > 0.999))
1517 .map(|t| {
1518 let [a, b, c] = [t[0], t[1], t[2]].map(|v| screen(&v, 400., 300.));
1519 ((b - a).perp_dot(c - a) * 0.5).abs()
1520 })
1521 .sum()
1522 };
1523 for draw in [
1524 Box::new(|| {
1525 polyline(
1526 &[vec2(100., 150.), vec2(200., 150.)],
1527 Stroke::new(20., Color::new(1., 1., 1., 1.)).cap(Cap::Round),
1528 )
1529 }) as Box<dyn Fn()>,
1530 Box::new(|| {
1531 stroke_arc(
1532 vec2(200., 150.),
1533 80.,
1534 0.,
1535 100. / 80.,
1536 Stroke::new(20., Color::new(1., 1., 1., 1.)).cap(Cap::Round),
1537 )
1538 }),
1539 ] {
1540 let v = capture(400, 300, draw);
1541 let core = 9.5_f32; let expected = 100. * 2. * core + PI * core * core;
1543 let actual = area(&v);
1544 assert!(
1545 (actual - expected).abs() < expected * 0.04,
1546 "core area {actual} vs {expected}"
1547 );
1548 }
1549 }
1550
1551 #[test]
1552 fn polygons_and_sectors_are_smooth_bounded_and_reject_bad_input() {
1553 let white = Color::new(1., 1., 1., 1.);
1554 for winding in [
1556 [
1557 vec2(10., 20.),
1558 vec2(110., 20.),
1559 vec2(110., 70.),
1560 vec2(10., 70.),
1561 ],
1562 [
1563 vec2(10., 70.),
1564 vec2(110., 70.),
1565 vec2(110., 20.),
1566 vec2(10., 20.),
1567 ],
1568 ] {
1569 let v = capture(400, 300, || fill_polygon(&winding, white));
1570 assert!(v.len() <= 9 * 4 && v.len() % 3 == 0, "{}", v.len());
1571 let outer = bounds(&v, 400., 300., false);
1572 let core = bounds(&v, 400., 300., true);
1573 for (o, e) in outer.iter().zip([9.5, 19.5, 110.5, 70.5]) {
1574 assert!((o - e).abs() < 1e-3, "{outer:?}");
1575 }
1576 for (c, e) in core.iter().zip([10.5, 20.5, 109.5, 69.5]) {
1577 assert!((c - e).abs() < 1e-3, "{core:?}");
1578 }
1579 }
1580 let many: Vec<_> = (0..MAX_POLYGON_POINTS)
1581 .map(|i| {
1582 let a = i as f32 * TAU / MAX_POLYGON_POINTS as f32;
1583 vec2(300. + 200. * a.cos(), 300. + 200. * a.sin())
1584 })
1585 .collect();
1586 let v = capture(1280, 800, || fill_polygon(&many, white));
1587 assert_eq!(v.len(), 576);
1588 assert!(v.iter().flatten().all(|x| x.is_finite()));
1589 let sector = capture(1280, 800, || {
1590 fill_sector(vec2(400., 400.), 390., -FRAC_PI_2, 6.2, white)
1591 });
1592 assert!(
1593 !sector.is_empty() && sector.len() <= 588,
1594 "{}",
1595 sector.len()
1596 );
1597 assert!(sector.iter().flatten().all(|x| x.is_finite()));
1598 let quarter = capture(400, 300, || {
1600 fill_sector(vec2(100., 100.), 40., 0., FRAC_PI_2, white)
1601 });
1602 let b = bounds(&quarter, 400., 300., false);
1603 assert!(
1604 b[0] >= 99. && b[1] >= 99. && b[2] <= 141. && b[3] <= 141.,
1605 "{b:?}"
1606 );
1607 let rejected = capture(400, 300, || {
1608 fill_polygon(&[vec2(0., 0.), vec2(10., 0.)], white);
1609 fill_polygon(&[vec2(0., 0.), vec2(10., 0.), vec2(20., 0.)], white);
1610 fill_polygon(&[vec2(0., 0.), vec2(f32::NAN, 0.), vec2(0., 9.)], white);
1611 fill_polygon(&many.repeat(2), white);
1612 fill_triangle(vec2(0., 0.), vec2(5., 5.), vec2(10., 10.), white);
1613 fill_sector(vec2(0., 0.), 10., 0., 0., white);
1614 fill_sector(vec2(0., 0.), -1., 0., 1., white);
1615 fill_sector(vec2(0., 0.), 10., 0., f32::NAN, white);
1616 });
1617 assert!(rejected.is_empty(), "{}", rejected.len());
1618 }
1619
1620 #[test]
1621 fn shapes_respect_documented_vertex_bounds_and_reject_bad_input() {
1622 type Case = (&'static str, usize, Box<dyn Fn()>);
1623 let cases: [Case; 8] = [
1624 (
1625 "rect",
1626 612,
1627 Box::new(|| {
1628 fill_rounded_rect(
1629 Rect::new(0., 0., 900., 900.),
1630 450.,
1631 Color::new(1., 1., 1., 1.),
1632 )
1633 }),
1634 ),
1635 (
1636 "stroke",
1637 1224,
1638 Box::new(|| {
1639 stroke_rounded_rect(
1640 Rect::new(0., 0., 900., 900.),
1641 450.,
1642 3.,
1643 Color::new(1., 1., 1., 1.),
1644 )
1645 }),
1646 ),
1647 (
1648 "shadow",
1649 1836,
1650 Box::new(|| {
1651 drop_shadow(
1652 Rect::new(0., 0., 900., 900.),
1653 400.,
1654 Shadow::soft(Color::new(0., 0., 0., 1.)).blur(200.),
1655 )
1656 }),
1657 ),
1658 (
1659 "capsule",
1660 612,
1661 Box::new(|| {
1662 fill_capsule(
1663 vec2(0., 0.),
1664 vec2(900., 300.),
1665 400.,
1666 Color::new(1., 1., 1., 1.),
1667 )
1668 }),
1669 ),
1670 (
1671 "arc",
1672 1782,
1673 Box::new(|| {
1674 stroke_arc(
1675 vec2(400., 400.),
1676 390.,
1677 0.,
1678 6.2,
1679 Stroke::new(80., Color::new(1., 1., 1., 1.)).cap(Cap::Round),
1680 )
1681 }),
1682 ),
1683 (
1684 "glow",
1685 3312,
1686 Box::new(|| glow_disc(vec2(0., 0.), 2000., Color::new(1., 1., 1., 1.))),
1687 ),
1688 (
1689 "ring",
1690 6912,
1691 Box::new(|| glow_ring(vec2(0., 0.), 2000., 400., Color::new(1., 1., 1., 1.))),
1692 ),
1693 (
1694 "nan",
1695 0,
1696 Box::new(|| {
1697 fill_rounded_rect(
1698 Rect::new(f32::NAN, 0., 1., 1.),
1699 0.,
1700 Color::new(1., 1., 1., 1.),
1701 );
1702 fill_circle(vec2(0., 0.), -1., Color::new(1., 1., 1., 1.));
1703 polyline(&[vec2(0., 0.)], Stroke::new(2., Color::new(1., 1., 1., 1.)));
1704 polyline(
1705 &[vec2(1., 1.), vec2(1., 1.)],
1706 Stroke::new(2., Color::new(1., 1., 1., 1.)),
1707 );
1708 stroke_circle(vec2(0., 0.), 5., f32::INFINITY, Color::new(1., 1., 1., 1.));
1709 glow_disc(vec2(0., 0.), 5., Color::new(f32::NAN, 1., 1., 1.));
1710 }),
1711 ),
1712 ];
1713 for (name, bound, draw) in cases {
1714 let v = capture(1280, 800, draw);
1715 assert!(v.len() <= bound, "{name}: {} > {bound}", v.len());
1716 assert!(v.iter().flatten().all(|x| x.is_finite()), "{name}");
1717 if bound > 0 {
1718 assert!(!v.is_empty(), "{name} drew nothing");
1719 }
1720 }
1721 }
1722
1723 #[test]
1724 fn polyline_joins_cover_corners_and_are_finite() {
1725 let path = [
1726 vec2(10., 10.),
1727 vec2(100., 10.),
1728 vec2(100., 100.),
1729 vec2(10., 100.),
1730 ];
1731 for join in [Join::Miter, Join::Bevel, Join::Round] {
1732 for cap in [Cap::Butt, Cap::Square, Cap::Round] {
1733 let v = capture(200, 200, || {
1734 polyline(
1735 &path,
1736 Stroke::new(6., Color::new(1., 1., 1., 1.))
1737 .join(join)
1738 .cap(cap),
1739 )
1740 });
1741 assert!(!v.is_empty() && v.len() % 3 == 0);
1742 assert!(v.iter().flatten().all(|x| x.is_finite()));
1743 let outer = bounds(&v, 200., 200., false);
1744 assert!(outer[2] <= 103.5 + 1e-3, "{join:?} {cap:?} {outer:?}");
1746 if join == Join::Miter {
1747 assert!((outer[2] - 103.5).abs() < 1e-3);
1748 }
1749 }
1750 }
1751 let closed = capture(200, 200, || {
1752 polyline(
1753 &path,
1754 Stroke::new(2., Color::new(1., 1., 1., 1.)).closed(true),
1755 )
1756 });
1757 let b = bounds(&closed, 200., 200., false);
1758 assert!(
1759 (b[0] - 8.5).abs() < 1e-3 && (b[1] - 8.5).abs() < 1e-3,
1760 "{b:?}"
1761 );
1762 }
1763
1764 fn worst_centroid_error(v: &[[f32; 8]], w: f32, h: f32, fill: Fill) -> f32 {
1767 v.chunks(3)
1768 .filter(|t| t.iter().all(|v| v[7] > 0.999))
1769 .map(|t| {
1770 let p = t
1771 .iter()
1772 .map(|v| screen(v, w, h))
1773 .fold(Vec2::ZERO, |a, b| a + b)
1774 / 3.;
1775 let interpolated = t.iter().map(|v| v[4]).sum::<f32>() / 3.;
1776 (interpolated - fill.at(p).r).abs()
1777 })
1778 .fold(0., f32::max)
1779 }
1780
1781 #[test]
1782 fn radial_fills_on_long_rects_follow_the_gradient_not_the_outline() {
1783 let (black, white) = (Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.));
1784 let rect = Rect::new(40., 40., 520., 120.);
1785 let fill = Fill::radial(rect.center(), 70., white, black);
1786 let v = capture(600, 200, || fill_rounded_rect(rect, 12., fill));
1787 assert!(v.len() <= 2592 && v.len() % 3 == 0, "{}", v.len());
1788 assert!(v.iter().flatten().all(|x| x.is_finite()));
1792 let error = worst_centroid_error(&v, 600., 200., fill);
1793 assert!(error < 0.2, "centroid error {error}");
1794 let c = vec2(100., 100.);
1796 let off = Fill::radial(c + vec2(30., -20.), 50., white, black);
1797 let v = capture(200, 200, || fill_circle(c, 80., off));
1798 assert!(worst_centroid_error(&v, 200., 200., off) < 0.2);
1799 let exact = Fill::radial(c, 80., white, black);
1801 let fan = capture(200, 200, || fill_circle(c, 80., exact));
1802 assert!(fan.len() <= 612, "{}", fan.len());
1803 }
1804
1805 #[test]
1806 fn gradients_interpolate_per_vertex_and_glow_is_additive() {
1807 let rect = Rect::new(0., 0., 100., 100.);
1808 let v = capture(100, 100, || {
1809 fill_rounded_rect(
1810 rect,
1811 0.,
1812 Fill::vertical(rect, Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.)),
1813 )
1814 });
1815 for v in &v {
1816 let p = screen(v, 100., 100.);
1817 assert!((v[4] - (p.y / 100.).clamp(0., 1.)).abs() < 1e-4);
1818 }
1819 host_frame(1. / 60., 100, 100, || {
1820 glow_disc(vec2(50., 50.), 30., Color::new(1., 1., 1., 1.))
1821 });
1822 let (effects, commands) =
1823 crate::read(|s| (s.retained.effects.clone(), s.retained.commands.len()));
1824 assert_eq!(effects.len(), 1);
1825 assert_eq!(effects[0].flags & 4, 4, "additive blend flag");
1826 assert!(commands >= 1);
1827 }
1828}