1use std::rc::Rc;
12
13use crate::geometry::{Color, Point, RRectDef, Rect, Transform2D};
14
15#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct Vertex {
18 pub x: f32,
19 pub y: f32,
20 pub color: Color,
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum TextureMode {
33 Mask,
35 Color,
37}
38
39#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
44pub enum BlendMode {
45 #[default]
47 Normal,
48 Multiply,
50 Screen,
52 Add,
54}
55
56#[derive(Clone, Debug)]
58pub enum PaintCommand {
59 Rect { rect: Rect, color: Color, radius: f32 },
61 TexturedRect {
67 rect: Rect,
68 color: Color,
69 uv: [f32; 4],
70 texture_id: u32,
71 mode: TextureMode,
73 },
74 Triangles { vertices: Vec<Vertex>, indices: Vec<u32> },
79 Text {
87 text: Rc<str>,
90 range: Option<(usize, usize)>,
94 font_size: f32,
95 color: Color,
96 position: Point,
98 max_width: Option<f32>,
100 },
101 BoxShadow {
110 rect: Rect,
111 color: Color,
112 radius: f32,
113 blur_radius: f32,
115 },
116 BackdropBlur { rect: Rect, radius: f32, blur_radius: f32, tint: Color },
122 InsetShadow { rect: Rect, color: Color, radius: f32, blur_radius: f32 },
127 LinearGradient {
129 rect: Rect,
130 start: Point,
132 end: Point,
134 from: Color,
135 to: Color,
136 corner_radius: f32,
137 },
138 RadialGradient { rect: Rect, center: Point, radial_radius: f32, from: Color, to: Color, corner_radius: f32 },
140 MaskRect { rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32 },
146 PushBlendMode(BlendMode),
148 PopBlendMode,
150 PushClip(Rect),
156 PushClipRRect { rect: Rect, radius: f32 },
161 PopClip,
163 PushClipPath { vertices: Vec<Vertex>, indices: Vec<u32> },
169 PopClipPath,
171}
172
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
182pub struct TextureFrameMeta {
183 pub sequence: u64,
184 pub generation: u64,
185 pub taken_at: std::time::Instant,
186 pub synced_seq: u64,
189 pub latest_seq: u64,
191}
192
193#[derive(Clone, Debug)]
195pub struct PendingTexture {
196 pub texture_id: u32,
197 pub data: Rc<crate::image::ImageData>,
198 pub meta: Option<TextureFrameMeta>,
199}
200
201#[derive(Clone, Debug, Default)]
204pub struct PaintList {
205 pub commands: Vec<PaintCommand>,
206 pub pending_textures: Vec<PendingTexture>,
210}
211
212#[derive(Clone, Copy, Debug, Default, PartialEq)]
224pub enum LayerEffect {
225 #[default]
227 None,
228 Transform(Transform2D),
230 Opacity(f32),
232 ClipRRect(RRectDef),
234}
235
236pub mod effect_flags {
244 pub const HAS_TRANSFORM: u32 = 1 << 0;
245 pub const HAS_OPACITY: u32 = 1 << 1;
246 pub const HAS_CLIP: u32 = 1 << 2;
247 pub const HAS_BLUR: u32 = 1 << 3;
249 pub const HAS_DROP_SHADOW: u32 = 1 << 4;
251}
252
253impl PaintList {
254 pub fn new() -> Self {
255 Self { commands: Vec::new(), pending_textures: Vec::new() }
256 }
257
258 pub fn clear(&mut self) {
259 self.commands.clear();
260 self.pending_textures.clear();
261 }
262
263 pub fn push(&mut self, cmd: PaintCommand) {
264 self.commands.push(cmd);
265 }
266
267 pub fn push_texture(&mut self, texture_id: u32, data: std::rc::Rc<crate::image::ImageData>) {
269 self.pending_textures.push(PendingTexture { texture_id, data, meta: None });
270 }
271
272 pub fn push_texture_with_meta(
275 &mut self,
276 texture_id: u32,
277 data: std::rc::Rc<crate::image::ImageData>,
278 meta: TextureFrameMeta,
279 ) {
280 self.pending_textures.push(PendingTexture { texture_id, data, meta: Some(meta) });
281 }
282
283 pub fn extend(&mut self, other: &PaintList) {
285 self.commands.extend(other.commands.iter().cloned());
286 self.pending_textures.extend(other.pending_textures.iter().cloned());
288 }
289
290 pub fn rect(&mut self, rect: Rect, color: Color) {
292 self.commands.push(PaintCommand::Rect { rect, color, radius: 0.0 });
293 }
294
295 pub fn rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
297 self.commands.push(PaintCommand::Rect { rect, color, radius });
298 }
299
300 pub fn text(&mut self, text: impl Into<Rc<str>>, font_size: f32, color: Color, position: Point) {
302 self.commands.push(PaintCommand::Text {
303 text: text.into(),
304 range: None,
305 font_size,
306 color,
307 position,
308 max_width: None,
309 });
310 }
311
312 pub fn text_wrapped(
314 &mut self,
315 text: impl Into<Rc<str>>,
316 font_size: f32,
317 color: Color,
318 position: Point,
319 max_width: Option<f32>,
320 ) {
321 self.commands.push(PaintCommand::Text {
322 text: text.into(),
323 range: None,
324 font_size,
325 color,
326 position,
327 max_width,
328 });
329 }
330
331 pub fn text_span(&mut self, text: &Rc<str>, range: (usize, usize), font_size: f32, color: Color, position: Point) {
336 self.commands.push(PaintCommand::Text {
337 text: Rc::clone(text),
338 range: Some(range),
339 font_size,
340 color,
341 position,
342 max_width: None,
343 });
344 }
345
346 pub fn box_shadow(
359 &mut self,
360 rect: Rect,
361 offset: Point,
362 blur_radius: f32,
363 spread: f32,
364 color: Color,
365 corner_radius: f32,
366 ) {
367 let sh_x = rect.x + offset.x - spread;
369 let sh_y = rect.y + offset.y - spread;
370 let sh_w = (rect.width + spread * 2.0).max(0.0);
371 let sh_h = (rect.height + spread * 2.0).max(0.0);
372 let base_radius = (corner_radius + spread).max(0.0);
374
375 let b = blur_radius.max(0.0);
379 let pad = b * 4.0;
380 let padded = Rect::new(sh_x - pad, sh_y - pad, sh_w + pad * 2.0, sh_h + pad * 2.0);
381
382 self.commands.push(PaintCommand::BoxShadow {
383 rect: padded,
384 color,
385 radius: base_radius, blur_radius: b,
387 });
388 }
389
390 pub fn linear_gradient(
392 &mut self,
393 rect: Rect,
394 start: Point,
395 end: Point,
396 from: Color,
397 to: Color,
398 corner_radius: f32,
399 ) {
400 self.commands.push(PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius });
401 }
402
403 pub fn radial_gradient(
405 &mut self,
406 rect: Rect,
407 center: Point,
408 radial_radius: f32,
409 from: Color,
410 to: Color,
411 corner_radius: f32,
412 ) {
413 self.commands.push(PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius });
414 }
415
416 pub fn mask(&mut self, rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32) {
418 self.commands.push(PaintCommand::MaskRect { rect, texture_id, uv, alpha: alpha.clamp(0.0, 1.0) });
419 }
420
421 pub fn inset_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur_radius: f32) {
423 self.commands.push(PaintCommand::InsetShadow { rect, color, radius, blur_radius: blur_radius.max(0.0) });
424 }
425
426 pub fn backdrop_blur(&mut self, rect: Rect, radius: f32, blur_radius: f32, tint: Color) {
428 self.commands.push(PaintCommand::BackdropBlur {
429 rect,
430 radius: radius.max(0.0),
431 blur_radius: blur_radius.max(0.0),
432 tint,
433 });
434 }
435
436 pub fn push_blend_mode(&mut self, mode: BlendMode) {
438 self.commands.push(PaintCommand::PushBlendMode(mode));
439 }
440
441 pub fn pop_blend_mode(&mut self) {
443 self.commands.push(PaintCommand::PopBlendMode);
444 }
445
446 pub fn push_clip(&mut self, rect: Rect) {
448 self.commands.push(PaintCommand::PushClip(rect));
449 }
450
451 pub fn push_clip_rrect(&mut self, rect: Rect, radius: f32) {
453 self.commands.push(PaintCommand::PushClipRRect { rect, radius });
454 }
455
456 pub fn pop_clip(&mut self) {
458 self.commands.push(PaintCommand::PopClip);
459 }
460
461 pub fn is_empty(&self) -> bool {
462 self.commands.is_empty()
463 }
464 pub fn len(&self) -> usize {
465 self.commands.len()
466 }
467}
468
469#[derive(Clone, Copy, Debug)]
487pub enum PathSeg {
488 Line(f32, f32),
490 Quad { cx: f32, cy: f32, x: f32, y: f32, flat: f32 },
492 Cubic { c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32, flat: f32 },
494}
495
496#[derive(Clone, Debug, Default)]
498struct Contour {
499 start: (f32, f32),
500 segs: Vec<PathSeg>,
501 closed: bool,
502}
503
504impl PathSeg {
505 fn end(&self) -> (f32, f32) {
507 match *self {
508 PathSeg::Line(x, y) => (x, y),
509 PathSeg::Quad { x, y, .. } => (x, y),
510 PathSeg::Cubic { x, y, .. } => (x, y),
511 }
512 }
513
514 fn transform(&mut self, sx: f32, sy: f32, fscale: f32) {
516 match self {
517 PathSeg::Line(x, y) => {
518 *x *= sx;
519 *y *= sy;
520 }
521 PathSeg::Quad { cx, cy, x, y, flat } => {
522 *cx *= sx;
523 *cy *= sy;
524 *x *= sx;
525 *y *= sy;
526 *flat *= fscale;
527 }
528 PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
529 *c1x *= sx;
530 *c1y *= sy;
531 *c2x *= sx;
532 *c2y *= sy;
533 *x *= sx;
534 *y *= sy;
535 *flat *= fscale;
536 }
537 }
538 }
539}
540
541#[derive(Default, Clone, Debug)]
543pub struct PathBuilder {
544 cx: f32,
546 cy: f32,
547 start: (f32, f32),
549 segs: Vec<PathSeg>,
551 contours: Vec<Contour>,
553}
554
555impl PathBuilder {
556 pub fn new() -> Self {
557 Self::default()
558 }
559
560 pub fn transform(&mut self, sx: f32, sy: f32) {
563 let fscale = sx.abs().max(sy.abs());
564 for c in self.contours.iter_mut() {
565 c.start.0 *= sx;
566 c.start.1 *= sy;
567 for seg in c.segs.iter_mut() {
568 seg.transform(sx, sy, fscale);
569 }
570 }
571 self.start.0 *= sx;
572 self.start.1 *= sy;
573 for seg in self.segs.iter_mut() {
574 seg.transform(sx, sy, fscale);
575 }
576 self.cx *= sx;
577 self.cy *= sy;
578 }
579
580 fn flatten_contour(start: (f32, f32), segs: &[PathSeg], out: &mut Vec<(f32, f32)>) {
582 out.push(start);
583 let (mut x0, mut y0) = start;
584 for seg in segs {
585 match *seg {
586 PathSeg::Line(x, y) => out.push((x, y)),
587 PathSeg::Quad { cx, cy, x, y, flat } => flatten_quad_bezier(x0, y0, cx, cy, x, y, flat, out),
588 PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
589 flatten_cubic_bezier(x0, y0, c1x, c1y, c2x, c2y, x, y, flat, out)
590 }
591 }
592 x0 = seg.end().0;
593 y0 = seg.end().1;
594 }
595 }
596
597 pub fn move_to(&mut self, x: f32, y: f32) {
598 if !self.segs.is_empty() {
600 let segs = std::mem::take(&mut self.segs);
601 self.contours.push(Contour { start: self.start, segs, closed: false });
602 }
603 self.start = (x, y);
604 self.cx = x;
605 self.cy = y;
606 }
607
608 pub fn line_to(&mut self, x: f32, y: f32) {
609 self.segs.push(PathSeg::Line(x, y));
610 self.cx = x;
611 self.cy = y;
612 }
613
614 pub fn quad_to(&mut self, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32) {
617 self.segs.push(PathSeg::Quad { cx, cy, x: ex, y: ey, flat });
618 self.cx = ex;
619 self.cy = ey;
620 }
621
622 #[allow(clippy::too_many_arguments)]
624 pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, ex: f32, ey: f32, flat: f32) {
625 self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: ex, y: ey, flat });
626 self.cx = ex;
627 self.cy = ey;
628 }
629
630 pub fn arc_to(&mut self, cx: f32, cy: f32, r: f32, start_angle: f32, end_angle: f32, num_segments: u32) {
637 if r <= 0.0 {
638 return;
639 }
640 let sweep = end_angle - start_angle;
641 let sweep = if sweep.abs() >= std::f32::consts::TAU { sweep * 0.999 } else { sweep };
643
644 let segs = (((sweep.abs() / std::f32::consts::FRAC_PI_2).ceil()) as u32).clamp(1, num_segments.max(1));
649 let step = sweep / segs as f32;
650 let flat = (r * step).abs() * 0.05;
651
652 let (sx, sy) = (cx + r * start_angle.cos(), cy + r * start_angle.sin());
657 let dcx = sx - self.cx;
658 let dcy = sy - self.cy;
659 if dcx * dcx + dcy * dcy > 1e-12 {
660 self.segs.push(PathSeg::Line(sx, sy));
661 self.cx = sx;
662 self.cy = sy;
663 }
664
665 let k = (4.0 / 3.0) * (step / 4.0).tan() * r; let mut a0 = start_angle;
667 for _ in 0..segs {
668 let a1 = a0 + step;
669 let (x0, y0) = (cx + r * a0.cos(), cy + r * a0.sin());
670 let (x1, y1) = (cx + r * a1.cos(), cy + r * a1.sin());
671 let c1x = x0 - k * a0.sin();
673 let c1y = y0 + k * a0.cos();
674 let c2x = x1 + k * a1.sin();
675 let c2y = y1 - k * a1.cos();
676 self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: x1, y: y1, flat });
677 self.cx = x1;
678 self.cy = y1;
679 a0 = a1;
680 }
681 }
682
683 pub fn close(&mut self) {
684 if !self.segs.is_empty() {
685 let segs = std::mem::take(&mut self.segs);
686 self.contours.push(Contour { start: self.start, segs, closed: true });
688 }
689 }
690
691 pub fn paths(&self) -> Vec<Vec<(f32, f32)>> {
694 let mut out = Vec::with_capacity(self.contours.len());
695 for c in &self.contours {
696 let mut pts = Vec::new();
697 Self::flatten_contour(c.start, &c.segs, &mut pts);
698 if pts.first() == pts.last() && pts.len() > 1 {
699 pts.pop();
700 }
701 if pts.len() >= 2 {
702 out.push(pts);
703 }
704 }
705 if !self.segs.is_empty() {
707 let mut pts = Vec::new();
708 Self::flatten_contour(self.start, &self.segs, &mut pts);
709 if pts.first() == pts.last() && pts.len() > 1 {
710 pts.pop();
711 }
712 if pts.len() >= 2 {
713 out.push(pts);
714 }
715 }
716 out
717 }
718
719 pub fn curve_contours(&self) -> Vec<((f32, f32), Vec<PathSeg>, bool)> {
725 let mut out = Vec::with_capacity(self.contours.len() + 1);
726 for c in &self.contours {
727 out.push((c.start, c.segs.clone(), c.closed));
728 }
729 if !self.segs.is_empty() {
730 out.push((self.start, self.segs.clone(), false));
731 }
732 out
733 }
734
735 pub fn paths_with_closed(&self) -> Vec<(Vec<(f32, f32)>, bool)> {
740 let mut out = Vec::with_capacity(self.contours.len() + 1);
741 for c in &self.contours {
742 let mut pts = Vec::new();
743 Self::flatten_contour(c.start, &c.segs, &mut pts);
744 if pts.first() == pts.last() && pts.len() > 1 {
745 pts.pop();
746 }
747 if pts.len() >= 2 {
748 out.push((pts, c.closed));
749 }
750 }
751 if !self.segs.is_empty() {
752 let mut pts = Vec::new();
753 Self::flatten_contour(self.start, &self.segs, &mut pts);
754 if pts.first() == pts.last() && pts.len() > 1 {
755 pts.pop();
756 }
757 if pts.len() >= 2 {
758 out.push((pts, false));
759 }
760 }
761 out
762 }
763
764 pub fn fill(self, color: Color, list: &mut PaintList) {
767 if self.contours.is_empty() && self.segs.is_empty() {
768 return;
769 }
770 let mut clean_contours: Vec<Vec<(f32, f32)>> = Vec::with_capacity(self.contours.len());
772 for c in self.contours.iter() {
773 let mut pts = Vec::new();
774 Self::flatten_contour(c.start, &c.segs, &mut pts);
775 if pts.first() == pts.last() && pts.len() > 1 {
776 pts.pop();
777 }
778 if pts.len() >= 3 {
779 clean_contours.push(pts);
780 }
781 }
782 if clean_contours.is_empty() {
783 return;
784 }
785
786 let mut flat: Vec<(f32, f32)> = Vec::new();
788 let mut hole_offsets: Vec<usize> = Vec::new();
789 let mut first = true;
790 for contour in clean_contours.iter() {
791 if !first {
792 hole_offsets.push(flat.len());
793 }
794 first = false;
795 for &p in contour {
796 flat.push(p);
797 }
798 }
799 let (tri_points, indices) = earcut(&flat, if hole_offsets.is_empty() { None } else { Some(&hole_offsets) });
803 if indices.len() < 3 {
804 return;
805 }
806 let vertices: Vec<Vertex> = tri_points.iter().map(|&(x, y)| Vertex { x, y, color }).collect();
807 list.push(PaintCommand::Triangles { vertices, indices });
808 }
809}
810
811#[allow(dead_code)]
816const MAX_FLATTEN_DEPTH: u32 = 10;
817
818#[allow(clippy::too_many_arguments)]
819fn flatten_quad_bezier(x0: f32, y0: f32, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32, out: &mut Vec<(f32, f32)>) {
820 let dx = ex - x0;
822 let dy = ey - y0;
823 let len_sq = dx * dx + dy * dy;
824 if len_sq < 1e-6 {
825 out.push((ex, ey));
826 return;
827 }
828 let cross = dx * (cy - y0) - dy * (cx - x0);
830 let dist = (cross / len_sq.sqrt().max(1e-6)).abs();
831 if dist < flat {
832 out.push((ex, ey));
833 return;
834 }
835 let mx0 = (x0 + cx) / 2.0;
837 let my0 = (y0 + cy) / 2.0;
838 let mx1 = (cx + ex) / 2.0;
839 let my1 = (cy + ey) / 2.0;
840 let mx = (mx0 + mx1) / 2.0;
841 let my = (my0 + my1) / 2.0;
842 flatten_quad_bezier(x0, y0, mx0, my0, mx, my, flat, out);
843 flatten_quad_bezier(mx, my, mx1, my1, ex, ey, flat, out);
844}
845
846#[allow(dead_code, clippy::too_many_arguments)]
848fn flatten_cubic_bezier(
849 x0: f32,
850 y0: f32,
851 x1: f32,
852 y1: f32,
853 x2: f32,
854 y2: f32,
855 x3: f32,
856 y3: f32,
857 flat: f32,
858 out: &mut Vec<(f32, f32)>,
859) {
860 let dx = x3 - x0;
862 let dy = y3 - y0;
863 let len = (dx * dx + dy * dy).sqrt().max(1e-6);
864 let d1 = (dx * (y1 - y0) - dy * (x1 - x0)).abs() / len;
865 let d2 = (dx * (y2 - y0) - dy * (x2 - x0)).abs() / len;
866 if d1.max(d2) < flat {
867 out.push((x3, y3));
868 return;
869 }
870 let (mx01x, mx01y) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
871 let (mx12x, mx12y) = ((x1 + x2) / 2.0, (y1 + y2) / 2.0);
872 let (mx23x, mx23y) = ((x2 + x3) / 2.0, (y2 + y3) / 2.0);
873 let (mxx, mxy) = ((mx01x + mx12x) / 2.0, (mx01y + mx12y) / 2.0);
874 let (myy, myz) = ((mx12x + mx23x) / 2.0, (mx12y + mx23y) / 2.0);
875 let (midx, midy) = ((mxx + myy) / 2.0, (mxy + myz) / 2.0);
876 flatten_cubic_bezier(x0, y0, mx01x, mx01y, mxx, mxy, midx, midy, flat, out);
877 flatten_cubic_bezier(midx, midy, myy, myz, mx23x, mx23y, x3, y3, flat, out);
878}
879
880fn earcut(points: &[(f32, f32)], hole_offsets: Option<&[usize]>) -> (Vec<(f32, f32)>, Vec<u32>) {
886 let n = points.len();
887 if n < 3 {
888 return (Vec::new(), Vec::new());
889 }
890 if hole_offsets.is_none() {
892 return (points.to_vec(), earcut_single(points));
893 }
894 let hole_offsets = hole_offsets.unwrap();
897 let mut merged: Vec<(f32, f32)> = Vec::with_capacity(n + hole_offsets.len());
898 let first_end = hole_offsets.first().copied().unwrap_or(n);
900 merged.extend_from_slice(&points[0..first_end]);
901 let mut contour_start = first_end;
903 for &end_idx in hole_offsets.iter().skip(1) {
904 let hole = &points[contour_start..end_idx];
905 bridge_hole(&mut merged, hole);
906 contour_start = end_idx;
907 }
908 if contour_start < n {
909 let last = &points[contour_start..n];
910 bridge_hole(&mut merged, last);
911 }
912 let indices = earcut_single(&merged);
913 (merged, indices)
914}
915
916fn bridge_hole(outer: &mut Vec<(f32, f32)>, hole: &[(f32, f32)]) {
918 if hole.is_empty() {
919 return;
920 }
921 let mut hole = hole.to_vec();
923 let outer_ccw = area2(outer) > 0.0;
924 let hole_ccw = area2(&hole) > 0.0;
925 if hole_ccw == outer_ccw {
926 hole.reverse();
927 }
928 let hole_pt = hole[0];
930 let mut best_i = 0usize;
931 let mut best_d = f32::INFINITY;
932 for (i, &p) in outer.iter().enumerate() {
933 let d = (p.0 - hole_pt.0).powi(2) + (p.1 - hole_pt.1).powi(2);
934 if d < best_d {
935 best_d = d;
936 best_i = i;
937 }
938 }
939 let insert_pos = best_i + 1;
940 let skip_last = if hole.first() == hole.last() { hole.len() - 1 } else { hole.len() };
941 let bridge = outer[best_i];
942 outer.insert(insert_pos, bridge);
946 outer.splice(insert_pos + 1..insert_pos + 1, hole[..skip_last].iter().copied());
947 let close_pos = insert_pos + 1 + skip_last;
948 if let Some(&first) = hole.first() {
949 outer.insert(close_pos, first);
950 outer.insert(close_pos + 1, bridge);
951 }
952}
953
954fn earcut_single(points: &[(f32, f32)]) -> Vec<u32> {
956 let n = points.len();
957 let points = if points.first() == points.last() { &points[..n - 1] } else { points };
959 let n = points.len();
960 if n < 3 {
961 return Vec::new();
962 }
963
964 let mut result = Vec::with_capacity((n - 2) * 3);
965 let mut active: Vec<usize> = (0..n).collect();
967 let ccw = area2(points) > 0.0;
969
970 let mut safety = n * n; while active.len() >= 3 && safety > 0 {
973 safety -= 1;
974 if active.len() == 3 {
975 let (a, b, c) = (active[0], active[1], active[2]);
979 let (ax, ay) = points[a];
980 let (bx, by) = points[b];
981 let (cx, cy) = points[c];
982 let cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
983 if cross.abs() > 1e-6 {
984 result.push(a as u32);
985 result.push(b as u32);
986 result.push(c as u32);
987 }
988 break;
989 }
990 let m = active.len();
991 let mut found = None;
992 for j in 0..m {
993 let prev = active[(j + m - 1) % m];
994 let curr = active[j];
995 let next = active[(j + 1) % m];
996 if is_ear(points, prev, curr, next, ccw) {
997 found = Some(j);
998 break;
999 }
1000 }
1001 match found {
1002 Some(j) => {
1003 let prev = active[(j + m - 1) % m];
1004 let curr = active[j];
1005 let next = active[(j + 1) % m];
1006 result.push(prev as u32);
1007 result.push(curr as u32);
1008 result.push(next as u32);
1009 active.remove(j);
1010 }
1011 None => {
1012 return fan_triangulation(points);
1014 }
1015 }
1016 }
1017 if result.is_empty() {
1018 fan_triangulation(points)
1019 } else {
1020 result
1021 }
1022}
1023
1024fn area2(points: &[(f32, f32)]) -> f32 {
1025 let mut a = 0.0f32;
1026 for w in points.windows(2) {
1027 a += w[0].0 * w[1].1 - w[1].0 * w[0].1;
1028 }
1029 if points.len() >= 2 {
1030 a += points.last().unwrap().0 * points[0].1 - points[0].0 * points.last().unwrap().1;
1031 }
1032 a
1033}
1034
1035fn is_ear(points: &[(f32, f32)], a: usize, b: usize, c: usize, ccw: bool) -> bool {
1036 let (ax, ay) = points[a];
1037 let (bx, by) = points[b];
1038 let (cx, cy) = points[c];
1039 let abc_cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
1042 if (abc_cross > 0.0) != ccw {
1043 return false;
1044 }
1045 for (i, &(px, py)) in points.iter().enumerate() {
1047 if i == a || i == b || i == c {
1048 continue;
1049 }
1050 if point_in_triangle(px, py, ax, ay, bx, by, cx, cy) {
1051 return false;
1052 }
1053 }
1054 true
1055}
1056
1057#[allow(clippy::too_many_arguments)]
1058fn point_in_triangle(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32, cx: f32, cy: f32) -> bool {
1059 let v0x = cx - ax;
1060 let v0y = cy - ay;
1061 let v1x = bx - ax;
1062 let v1y = by - ay;
1063 let v2x = px - ax;
1064 let v2y = py - ay;
1065
1066 let dot00 = v0x * v0x + v0y * v0y;
1067 let dot01 = v0x * v1x + v0y * v1y;
1068 let dot02 = v0x * v2x + v0y * v2y;
1069 let dot11 = v1x * v1x + v1y * v1y;
1070 let dot12 = v1x * v2x + v1y * v2y;
1071
1072 let inv_denom = 1.0 / (dot00 * dot11 - dot01 * dot01).max(1e-9);
1073 let u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
1074 let v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
1075 const EPS: f32 = 1e-6;
1078 u > EPS && v > EPS && (u + v) < 1.0 - EPS
1079}
1080
1081fn fan_triangulation(points: &[(f32, f32)]) -> Vec<u32> {
1083 let mut result = Vec::new();
1084 if points.len() < 3 {
1085 return result;
1086 }
1087 let base = points[0];
1088 for i in 2..points.len() {
1090 let mut ok = true;
1092 for j in 1..points.len() {
1093 if j == i || j == 0 {
1094 continue;
1095 }
1096 if point_in_triangle(
1097 points[j].0,
1098 points[j].1,
1099 base.0,
1100 base.1,
1101 points[1].0,
1102 points[1].1,
1103 points[i].0,
1104 points[i].1,
1105 ) {
1106 ok = false;
1107 break;
1108 }
1109 }
1110 if ok {
1111 result.push(0u32);
1112 result.push(1u32);
1113 result.push(i as u32);
1114 }
1115 }
1116 if result.len() < 3 && points.len() >= 3 {
1118 let n = points.len() as u32;
1119 for i in 1..n - 1 {
1120 result.push(0);
1121 result.push(i);
1122 result.push(i + 1);
1123 }
1124 }
1125 result
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130 use super::*;
1131 use crate::Color;
1132
1133 #[test]
1134 fn path_builder_triangulates_square() {
1135 let mut pb = PathBuilder::new();
1136 pb.move_to(0.0, 0.0);
1137 pb.line_to(100.0, 0.0);
1138 pb.line_to(100.0, 100.0);
1139 pb.line_to(0.0, 100.0);
1140 pb.close();
1141 let mut list = PaintList::new();
1142 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1143 assert_eq!(list.commands.len(), 1);
1144 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1145 assert_eq!(vertices.len(), 4);
1147 assert_eq!(indices.len(), 6);
1148 } else {
1149 panic!("expected Triangles");
1150 }
1151 }
1152
1153 #[test]
1154 fn path_builder_quadbezier_flattens() {
1155 let mut pb = PathBuilder::new();
1156 pb.move_to(0.0, 50.0);
1157 pb.quad_to(50.0, 0.0, 100.0, 50.0, 0.5);
1158 pb.quad_to(50.0, 100.0, 0.0, 50.0, 0.5);
1159 pb.close();
1160 let mut list = PaintList::new();
1161 pb.fill(Color::rgb(0.0, 1.0, 0.0), &mut list);
1162 assert_eq!(list.commands.len(), 1);
1163 if let PaintCommand::Triangles { indices, .. } = &list.commands[0] {
1164 assert!(indices.len() >= 6, "bezier triangulation should produce >= 6 indices, got {}", indices.len());
1165 }
1166 }
1167
1168 #[test]
1169 fn path_builder_arc_to_produces_points() {
1170 let mut pb = PathBuilder::new();
1171 pb.move_to(100.0, 100.0);
1173 pb.arc_to(100.0, 100.0, 50.0, 0.0, std::f32::consts::FRAC_PI_2, 16);
1174 pb.close();
1175 let mut list = PaintList::new();
1176 pb.fill(Color::WHITE, &mut list);
1177
1178 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1179 assert!(vertices.len() >= 4, "arc + close → 至少 4 vertices");
1180 assert!(indices.len() >= 6, "earcut → 至少 1 triangle(3 indices)");
1181 for v in vertices {
1183 let dx = v.x - 100.0;
1184 let dy = v.y - 100.0;
1185 let d = (dx * dx + dy * dy).sqrt();
1186 assert!((d - 50.0).abs() < 1.0 || d < 1.0, "vertex ({}, {}) should be at r≈50 or center", v.x, v.y);
1187 }
1188 }
1189 }
1190
1191 #[test]
1192 fn path_builder_annulus_sector_triangulates() {
1193 let cx = 100.0;
1195 let cy = 100.0;
1196 let outer_r = 80.0;
1197 let inner_r = 60.0;
1198 let start_a = -std::f32::consts::FRAC_PI_2;
1199 let end_a = start_a + std::f32::consts::TAU * 0.75; let segs = 32u32;
1201
1202 let mut pb = PathBuilder::new();
1203 pb.move_to(cx + outer_r * start_a.cos(), cy + outer_r * start_a.sin());
1204 pb.arc_to(cx, cy, outer_r, start_a, end_a, segs);
1205 pb.line_to(cx + inner_r * end_a.cos(), cy + inner_r * end_a.sin());
1206 pb.arc_to(cx, cy, inner_r, end_a, start_a, segs);
1207 pb.close();
1208
1209 let mut list = PaintList::new();
1210 pb.fill(Color::rgb(0.2, 0.6, 1.0), &mut list);
1211
1212 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1213 assert!(vertices.len() >= 20, "annulus sector should have many vertices, got {}", vertices.len());
1215 assert!(indices.len() >= 6, "should produce triangles");
1216
1217 for v in vertices {
1219 let dx = v.x - cx;
1220 let dy = v.y - cy;
1221 let d = (dx * dx + dy * dy).sqrt();
1222 let on_outer = (d - outer_r).abs() < 1.0;
1223 let on_inner = (d - inner_r).abs() < 1.0;
1224 let on_radial = v.y == cy; assert!(
1226 on_outer || on_inner || on_radial,
1227 "vertex ({}, {}) d={} not on inner/outer/radial",
1228 v.x,
1229 v.y,
1230 d
1231 );
1232 }
1233 }
1234 }
1235
1236 #[test]
1237 fn box_shadow_pads_four_sigma_and_shrinks_radius_on_negative_spread() {
1238 let mut list = PaintList::new();
1239 list.box_shadow(Rect::new(10.0, 20.0, 100.0, 50.0), Point::new(2.0, 3.0), 5.0, 1.0, Color::BLACK, 8.0);
1240 match &list.commands[0] {
1241 PaintCommand::BoxShadow { rect, radius, blur_radius, .. } => {
1242 assert_eq!(*rect, Rect::new(-9.0, 2.0, 142.0, 92.0));
1244 assert_eq!(*radius, 9.0, "正 spread 圆角增大");
1245 assert_eq!(*blur_radius, 5.0);
1246 }
1247 other => panic!("expected BoxShadow, got {other:?}"),
1248 }
1249
1250 let mut list = PaintList::new();
1251 list.box_shadow(Rect::new(0.0, 0.0, 100.0, 50.0), Point::ZERO, 0.0, -4.0, Color::BLACK, 10.0);
1252 match &list.commands[0] {
1253 PaintCommand::BoxShadow { rect, radius, .. } => {
1254 assert_eq!(*rect, Rect::new(4.0, 4.0, 92.0, 42.0));
1255 assert_eq!(*radius, 6.0, "负 spread 圆角应收缩");
1256 }
1257 other => panic!("expected BoxShadow, got {other:?}"),
1258 }
1259 }
1260
1261 #[test]
1262 fn path_builder_empty_nop() {
1263 let pb = PathBuilder::new();
1264 let mut list = PaintList::new();
1265 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1266 assert!(list.is_empty());
1267 }
1268
1269 #[test]
1270 fn earcut_simple_triangle() {
1271 let pts = vec![(0.0, 0.0), (10.0, 0.0), (5.0, 10.0), (0.0, 0.0)];
1272 let (points, indices) = earcut(&pts, None);
1273 assert_eq!(indices.len(), 3);
1275 let unique: std::collections::HashSet<&u32> = indices.iter().collect();
1276 assert_eq!(unique.len(), 3); assert!(indices.iter().all(|&i| (i as usize) < points.len()));
1279 }
1280
1281 fn tri_area_sum(points: &[(f32, f32)], indices: &[u32]) -> f32 {
1282 let mut area = 0.0;
1283 for t in indices.as_chunks::<3>().0 {
1284 let (ax, ay) = points[t[0] as usize];
1285 let (bx, by) = points[t[1] as usize];
1286 let (cx, cy) = points[t[2] as usize];
1287 area += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() * 0.5;
1288 }
1289 area
1290 }
1291
1292 #[test]
1294 fn earcut_concave_polygon_area_matches() {
1295 let pts = vec![(0.0, 0.0), (60.0, 0.0), (60.0, 20.0), (20.0, 20.0), (20.0, 60.0), (0.0, 60.0)];
1297 let (points, indices) = earcut(&pts, None);
1298 assert_eq!(indices.len(), 12, "6 顶点凹多边形 → 4 个三角形");
1299 assert!(indices.iter().all(|&i| (i as usize) < points.len()));
1300 let expected = area2(&pts).abs() * 0.5;
1301 let got = tri_area_sum(&points, &indices);
1302 assert!((got - expected).abs() < 0.5, "凹多边形面积: expected={expected}, got={got}");
1303 }
1304
1305 #[test]
1307 fn earcut_donut_hole_area_subtracted() {
1308 let outer = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
1309 let hole = vec![(25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0)];
1310 let mut pts = outer.clone();
1311 pts.extend_from_slice(&hole);
1312 let (points, indices) = earcut(&pts, Some(&[outer.len()]));
1313 assert!(!indices.is_empty());
1314 assert!(indices.iter().all(|&i| (i as usize) < points.len()), "索引不得越界");
1315 let got = tri_area_sum(&points, &indices);
1316 let expected = 100.0 * 100.0 - 50.0 * 50.0;
1317 assert!((got - expected).abs() < 1.0, "带洞面积: expected={expected}, got={got}");
1318 }
1319
1320 #[test]
1324 fn fill_multi_contour_indices_in_range() {
1325 let mut pb = PathBuilder::new();
1326 pb.move_to(0.0, 0.0);
1328 pb.line_to(100.0, 0.0);
1329 pb.line_to(100.0, 100.0);
1330 pb.line_to(0.0, 100.0);
1331 pb.close();
1332 pb.move_to(40.0, 40.0);
1334 pb.line_to(60.0, 40.0);
1335 pb.line_to(50.0, 60.0);
1336 pb.close();
1337 let mut list = PaintList::new();
1338 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1339 assert_eq!(list.commands.len(), 1);
1340 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1341 assert!(
1342 indices.iter().all(|&i| (i as usize) < vertices.len()),
1343 "索引 {} 越界(vertices.len={})",
1344 indices.iter().max().unwrap(),
1345 vertices.len()
1346 );
1347 } else {
1348 panic!("expected Triangles");
1349 }
1350 }
1351}