1use std::collections::hash_map::DefaultHasher;
12use std::hash::{Hash, Hasher};
13use std::rc::Rc;
14
15use crate::geometry::{Color, Point, RRectDef, Rect, Transform2D};
16
17#[derive(Clone, Copy, Debug, PartialEq)]
19pub struct Vertex {
20 pub x: f32,
21 pub y: f32,
22 pub color: Color,
23}
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum TextureMode {
35 Mask,
37 Color,
39}
40
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
46pub enum BlendMode {
47 #[default]
49 Normal,
50 Multiply,
52 Screen,
54 Add,
56}
57
58#[derive(Clone, Debug)]
60pub enum PaintCommand {
61 Rect { rect: Rect, color: Color, radius: f32 },
63 TexturedRect {
69 rect: Rect,
70 color: Color,
71 uv: [f32; 4],
72 texture_id: u32,
73 mode: TextureMode,
75 },
76 Triangles { vertices: Vec<Vertex>, indices: Vec<u32> },
81 Text {
89 text: Rc<str>,
92 range: Option<(usize, usize)>,
96 font_size: f32,
97 color: Color,
98 position: Point,
100 max_width: Option<f32>,
102 },
103 BoxShadow {
112 rect: Rect,
113 color: Color,
114 radius: f32,
115 blur_radius: f32,
117 },
118 BackdropBlur { rect: Rect, radius: f32, blur_radius: f32, tint: Color },
124 InsetShadow { rect: Rect, color: Color, radius: f32, blur_radius: f32 },
129 LinearGradient {
131 rect: Rect,
132 start: Point,
134 end: Point,
136 from: Color,
137 to: Color,
138 corner_radius: f32,
139 },
140 RadialGradient { rect: Rect, center: Point, radial_radius: f32, from: Color, to: Color, corner_radius: f32 },
142 MaskRect { rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32 },
148 PushBlendMode(BlendMode),
150 PopBlendMode,
152 PushClip(Rect),
158 PushClipRRect { rect: Rect, radius: f32 },
163 PopClip,
165 PushClipPath { vertices: Vec<Vertex>, indices: Vec<u32> },
171 PopClipPath,
173}
174
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
184pub struct TextureFrameMeta {
185 pub sequence: u64,
186 pub generation: u64,
187 pub taken_at: std::time::Instant,
188 pub synced_seq: u64,
191 pub latest_seq: u64,
193}
194
195#[derive(Clone, Debug)]
197pub struct PendingTexture {
198 pub texture_id: u32,
199 pub data: Rc<crate::image::ImageData>,
200 pub meta: Option<TextureFrameMeta>,
201}
202
203#[derive(Clone, Debug, Default)]
206pub struct PaintList {
207 pub commands: Vec<PaintCommand>,
208 pub pending_textures: Vec<PendingTexture>,
212}
213
214#[derive(Clone, Copy, Debug, Default, PartialEq)]
226pub enum LayerEffect {
227 #[default]
229 None,
230 Transform(Transform2D),
232 Opacity(f32),
234 ClipRRect(RRectDef),
236}
237
238pub mod effect_flags {
246 pub const HAS_TRANSFORM: u32 = 1 << 0;
247 pub const HAS_OPACITY: u32 = 1 << 1;
248 pub const HAS_CLIP: u32 = 1 << 2;
249 pub const HAS_BLUR: u32 = 1 << 3;
251 pub const HAS_DROP_SHADOW: u32 = 1 << 4;
253}
254
255fn hash_f32(hasher: &mut DefaultHasher, value: f32) {
256 value.to_bits().hash(hasher);
257}
258
259fn hash_color(hasher: &mut DefaultHasher, color: Color) {
260 hash_f32(hasher, color.r);
261 hash_f32(hasher, color.g);
262 hash_f32(hasher, color.b);
263 hash_f32(hasher, color.a);
264}
265
266fn hash_rect(hasher: &mut DefaultHasher, rect: Rect) {
267 hash_f32(hasher, rect.x);
268 hash_f32(hasher, rect.y);
269 hash_f32(hasher, rect.width);
270 hash_f32(hasher, rect.height);
271}
272
273fn hash_point(hasher: &mut DefaultHasher, point: Point) {
274 hash_f32(hasher, point.x);
275 hash_f32(hasher, point.y);
276}
277
278fn hash_vertices(hasher: &mut DefaultHasher, vertices: &[Vertex], indices: &[u32]) {
279 vertices.len().hash(hasher);
280 for vertex in vertices {
281 hash_f32(hasher, vertex.x);
282 hash_f32(hasher, vertex.y);
283 hash_color(hasher, vertex.color);
284 }
285 indices.hash(hasher);
286}
287
288impl PaintList {
289 pub fn new() -> Self {
290 Self { commands: Vec::new(), pending_textures: Vec::new() }
291 }
292
293 pub fn content_digest(&self) -> u64 {
299 let mut hasher = DefaultHasher::new();
300 self.commands.len().hash(&mut hasher);
301 for command in &self.commands {
302 std::mem::discriminant(command).hash(&mut hasher);
303 match command {
304 PaintCommand::Rect { rect, color, radius } => {
305 hash_rect(&mut hasher, *rect);
306 hash_color(&mut hasher, *color);
307 hash_f32(&mut hasher, *radius);
308 }
309 PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
310 hash_rect(&mut hasher, *rect);
311 hash_color(&mut hasher, *color);
312 for value in uv {
313 hash_f32(&mut hasher, *value);
314 }
315 texture_id.hash(&mut hasher);
316 mode.hash(&mut hasher);
317 }
318 PaintCommand::Triangles { vertices, indices } => hash_vertices(&mut hasher, vertices, indices),
319 PaintCommand::Text { text, range, font_size, color, position, max_width } => {
320 text.as_bytes().hash(&mut hasher);
321 range.hash(&mut hasher);
322 hash_f32(&mut hasher, *font_size);
323 hash_color(&mut hasher, *color);
324 hash_point(&mut hasher, *position);
325 max_width.map(f32::to_bits).hash(&mut hasher);
326 }
327 PaintCommand::BoxShadow { rect, color, radius, blur_radius }
328 | PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
329 hash_rect(&mut hasher, *rect);
330 hash_color(&mut hasher, *color);
331 hash_f32(&mut hasher, *radius);
332 hash_f32(&mut hasher, *blur_radius);
333 }
334 PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
335 hash_rect(&mut hasher, *rect);
336 hash_f32(&mut hasher, *radius);
337 hash_f32(&mut hasher, *blur_radius);
338 hash_color(&mut hasher, *tint);
339 }
340 PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
341 hash_rect(&mut hasher, *rect);
342 hash_point(&mut hasher, *start);
343 hash_point(&mut hasher, *end);
344 hash_color(&mut hasher, *from);
345 hash_color(&mut hasher, *to);
346 hash_f32(&mut hasher, *corner_radius);
347 }
348 PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
349 hash_rect(&mut hasher, *rect);
350 hash_point(&mut hasher, *center);
351 hash_f32(&mut hasher, *radial_radius);
352 hash_color(&mut hasher, *from);
353 hash_color(&mut hasher, *to);
354 hash_f32(&mut hasher, *corner_radius);
355 }
356 PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
357 hash_rect(&mut hasher, *rect);
358 texture_id.hash(&mut hasher);
359 for value in uv {
360 hash_f32(&mut hasher, *value);
361 }
362 hash_f32(&mut hasher, *alpha);
363 }
364 PaintCommand::PushBlendMode(mode) => mode.hash(&mut hasher),
365 PaintCommand::PopBlendMode | PaintCommand::PopClip | PaintCommand::PopClipPath => {}
366 PaintCommand::PushClip(rect) => hash_rect(&mut hasher, *rect),
367 PaintCommand::PushClipRRect { rect, radius } => {
368 hash_rect(&mut hasher, *rect);
369 hash_f32(&mut hasher, *radius);
370 }
371 PaintCommand::PushClipPath { vertices, indices } => hash_vertices(&mut hasher, vertices, indices),
372 }
373 }
374 self.pending_textures.len().hash(&mut hasher);
375 for pending in &self.pending_textures {
376 pending.texture_id.hash(&mut hasher);
377 (Rc::as_ptr(&pending.data) as usize).hash(&mut hasher);
378 match &pending.meta {
379 None => 0u8.hash(&mut hasher),
380 Some(meta) => {
381 1u8.hash(&mut hasher);
382 meta.sequence.hash(&mut hasher);
383 meta.generation.hash(&mut hasher);
384 meta.synced_seq.hash(&mut hasher);
385 meta.latest_seq.hash(&mut hasher);
386 }
387 }
388 }
389 hasher.finish()
390 }
391
392 pub fn clear(&mut self) {
393 self.commands.clear();
394 self.pending_textures.clear();
395 }
396
397 pub fn push(&mut self, cmd: PaintCommand) {
398 self.commands.push(cmd);
399 }
400
401 pub fn push_texture(&mut self, texture_id: u32, data: std::rc::Rc<crate::image::ImageData>) {
403 self.pending_textures.push(PendingTexture { texture_id, data, meta: None });
404 }
405
406 pub fn push_texture_with_meta(
409 &mut self,
410 texture_id: u32,
411 data: std::rc::Rc<crate::image::ImageData>,
412 meta: TextureFrameMeta,
413 ) {
414 self.pending_textures.push(PendingTexture { texture_id, data, meta: Some(meta) });
415 }
416
417 pub fn extend(&mut self, other: &PaintList) {
419 self.commands.extend(other.commands.iter().cloned());
420 self.pending_textures.extend(other.pending_textures.iter().cloned());
422 }
423
424 pub fn rect(&mut self, rect: Rect, color: Color) {
426 self.commands.push(PaintCommand::Rect { rect, color, radius: 0.0 });
427 }
428
429 pub fn rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
431 self.commands.push(PaintCommand::Rect { rect, color, radius });
432 }
433
434 pub fn text(&mut self, text: impl Into<Rc<str>>, font_size: f32, color: Color, position: Point) {
436 self.commands.push(PaintCommand::Text {
437 text: text.into(),
438 range: None,
439 font_size,
440 color,
441 position,
442 max_width: None,
443 });
444 }
445
446 pub fn text_wrapped(
448 &mut self,
449 text: impl Into<Rc<str>>,
450 font_size: f32,
451 color: Color,
452 position: Point,
453 max_width: Option<f32>,
454 ) {
455 self.commands.push(PaintCommand::Text {
456 text: text.into(),
457 range: None,
458 font_size,
459 color,
460 position,
461 max_width,
462 });
463 }
464
465 pub fn text_span(&mut self, text: &Rc<str>, range: (usize, usize), font_size: f32, color: Color, position: Point) {
470 self.commands.push(PaintCommand::Text {
471 text: Rc::clone(text),
472 range: Some(range),
473 font_size,
474 color,
475 position,
476 max_width: None,
477 });
478 }
479
480 pub fn box_shadow(
493 &mut self,
494 rect: Rect,
495 offset: Point,
496 blur_radius: f32,
497 spread: f32,
498 color: Color,
499 corner_radius: f32,
500 ) {
501 let sh_x = rect.x + offset.x - spread;
503 let sh_y = rect.y + offset.y - spread;
504 let sh_w = (rect.width + spread * 2.0).max(0.0);
505 let sh_h = (rect.height + spread * 2.0).max(0.0);
506 let base_radius = (corner_radius + spread).max(0.0);
508
509 let b = blur_radius.max(0.0);
513 let pad = b * 4.0;
514 let padded = Rect::new(sh_x - pad, sh_y - pad, sh_w + pad * 2.0, sh_h + pad * 2.0);
515
516 self.commands.push(PaintCommand::BoxShadow {
517 rect: padded,
518 color,
519 radius: base_radius, blur_radius: b,
521 });
522 }
523
524 pub fn linear_gradient(
526 &mut self,
527 rect: Rect,
528 start: Point,
529 end: Point,
530 from: Color,
531 to: Color,
532 corner_radius: f32,
533 ) {
534 self.commands.push(PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius });
535 }
536
537 pub fn radial_gradient(
539 &mut self,
540 rect: Rect,
541 center: Point,
542 radial_radius: f32,
543 from: Color,
544 to: Color,
545 corner_radius: f32,
546 ) {
547 self.commands.push(PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius });
548 }
549
550 pub fn mask(&mut self, rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32) {
552 self.commands.push(PaintCommand::MaskRect { rect, texture_id, uv, alpha: alpha.clamp(0.0, 1.0) });
553 }
554
555 pub fn inset_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur_radius: f32) {
557 self.commands.push(PaintCommand::InsetShadow { rect, color, radius, blur_radius: blur_radius.max(0.0) });
558 }
559
560 pub fn backdrop_blur(&mut self, rect: Rect, radius: f32, blur_radius: f32, tint: Color) {
562 self.commands.push(PaintCommand::BackdropBlur {
563 rect,
564 radius: radius.max(0.0),
565 blur_radius: blur_radius.max(0.0),
566 tint,
567 });
568 }
569
570 pub fn push_blend_mode(&mut self, mode: BlendMode) {
572 self.commands.push(PaintCommand::PushBlendMode(mode));
573 }
574
575 pub fn pop_blend_mode(&mut self) {
577 self.commands.push(PaintCommand::PopBlendMode);
578 }
579
580 pub fn push_clip(&mut self, rect: Rect) {
582 self.commands.push(PaintCommand::PushClip(rect));
583 }
584
585 pub fn push_clip_rrect(&mut self, rect: Rect, radius: f32) {
587 self.commands.push(PaintCommand::PushClipRRect { rect, radius });
588 }
589
590 pub fn pop_clip(&mut self) {
592 self.commands.push(PaintCommand::PopClip);
593 }
594
595 pub fn is_empty(&self) -> bool {
596 self.commands.is_empty()
597 }
598 pub fn len(&self) -> usize {
599 self.commands.len()
600 }
601}
602
603#[derive(Clone, Copy, Debug)]
621pub enum PathSeg {
622 Line(f32, f32),
624 Quad { cx: f32, cy: f32, x: f32, y: f32, flat: f32 },
626 Cubic { c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32, flat: f32 },
628}
629
630#[derive(Clone, Debug, Default)]
632struct Contour {
633 start: (f32, f32),
634 segs: Vec<PathSeg>,
635 closed: bool,
636}
637
638impl PathSeg {
639 fn end(&self) -> (f32, f32) {
641 match *self {
642 PathSeg::Line(x, y) => (x, y),
643 PathSeg::Quad { x, y, .. } => (x, y),
644 PathSeg::Cubic { x, y, .. } => (x, y),
645 }
646 }
647
648 fn transform(&mut self, sx: f32, sy: f32, fscale: f32) {
650 match self {
651 PathSeg::Line(x, y) => {
652 *x *= sx;
653 *y *= sy;
654 }
655 PathSeg::Quad { cx, cy, x, y, flat } => {
656 *cx *= sx;
657 *cy *= sy;
658 *x *= sx;
659 *y *= sy;
660 *flat *= fscale;
661 }
662 PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
663 *c1x *= sx;
664 *c1y *= sy;
665 *c2x *= sx;
666 *c2y *= sy;
667 *x *= sx;
668 *y *= sy;
669 *flat *= fscale;
670 }
671 }
672 }
673}
674
675#[derive(Default, Clone, Debug)]
677pub struct PathBuilder {
678 cx: f32,
680 cy: f32,
681 start: (f32, f32),
683 segs: Vec<PathSeg>,
685 contours: Vec<Contour>,
687}
688
689impl PathBuilder {
690 pub fn new() -> Self {
691 Self::default()
692 }
693
694 pub fn transform(&mut self, sx: f32, sy: f32) {
697 let fscale = sx.abs().max(sy.abs());
698 for c in self.contours.iter_mut() {
699 c.start.0 *= sx;
700 c.start.1 *= sy;
701 for seg in c.segs.iter_mut() {
702 seg.transform(sx, sy, fscale);
703 }
704 }
705 self.start.0 *= sx;
706 self.start.1 *= sy;
707 for seg in self.segs.iter_mut() {
708 seg.transform(sx, sy, fscale);
709 }
710 self.cx *= sx;
711 self.cy *= sy;
712 }
713
714 fn flatten_contour(start: (f32, f32), segs: &[PathSeg], out: &mut Vec<(f32, f32)>) {
716 out.push(start);
717 let (mut x0, mut y0) = start;
718 for seg in segs {
719 match *seg {
720 PathSeg::Line(x, y) => out.push((x, y)),
721 PathSeg::Quad { cx, cy, x, y, flat } => flatten_quad_bezier(x0, y0, cx, cy, x, y, flat, out),
722 PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
723 flatten_cubic_bezier(x0, y0, c1x, c1y, c2x, c2y, x, y, flat, out)
724 }
725 }
726 x0 = seg.end().0;
727 y0 = seg.end().1;
728 }
729 }
730
731 pub fn move_to(&mut self, x: f32, y: f32) {
732 if !self.segs.is_empty() {
734 let segs = std::mem::take(&mut self.segs);
735 self.contours.push(Contour { start: self.start, segs, closed: false });
736 }
737 self.start = (x, y);
738 self.cx = x;
739 self.cy = y;
740 }
741
742 pub fn line_to(&mut self, x: f32, y: f32) {
743 self.segs.push(PathSeg::Line(x, y));
744 self.cx = x;
745 self.cy = y;
746 }
747
748 pub fn quad_to(&mut self, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32) {
751 self.segs.push(PathSeg::Quad { cx, cy, x: ex, y: ey, flat });
752 self.cx = ex;
753 self.cy = ey;
754 }
755
756 #[allow(clippy::too_many_arguments)]
758 pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, ex: f32, ey: f32, flat: f32) {
759 self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: ex, y: ey, flat });
760 self.cx = ex;
761 self.cy = ey;
762 }
763
764 pub fn arc_to(&mut self, cx: f32, cy: f32, r: f32, start_angle: f32, end_angle: f32, num_segments: u32) {
771 if r <= 0.0 {
772 return;
773 }
774 let sweep = end_angle - start_angle;
775 let sweep = if sweep.abs() >= std::f32::consts::TAU { sweep * 0.999 } else { sweep };
777
778 let segs = (((sweep.abs() / std::f32::consts::FRAC_PI_2).ceil()) as u32).clamp(1, num_segments.max(1));
783 let step = sweep / segs as f32;
784 let flat = (r * step).abs() * 0.05;
785
786 let (sx, sy) = (cx + r * start_angle.cos(), cy + r * start_angle.sin());
791 let dcx = sx - self.cx;
792 let dcy = sy - self.cy;
793 if dcx * dcx + dcy * dcy > 1e-12 {
794 self.segs.push(PathSeg::Line(sx, sy));
795 self.cx = sx;
796 self.cy = sy;
797 }
798
799 let k = (4.0 / 3.0) * (step / 4.0).tan() * r; let mut a0 = start_angle;
801 for _ in 0..segs {
802 let a1 = a0 + step;
803 let (x0, y0) = (cx + r * a0.cos(), cy + r * a0.sin());
804 let (x1, y1) = (cx + r * a1.cos(), cy + r * a1.sin());
805 let c1x = x0 - k * a0.sin();
807 let c1y = y0 + k * a0.cos();
808 let c2x = x1 + k * a1.sin();
809 let c2y = y1 - k * a1.cos();
810 self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: x1, y: y1, flat });
811 self.cx = x1;
812 self.cy = y1;
813 a0 = a1;
814 }
815 }
816
817 pub fn close(&mut self) {
818 if !self.segs.is_empty() {
819 let segs = std::mem::take(&mut self.segs);
820 self.contours.push(Contour { start: self.start, segs, closed: true });
822 }
823 }
824
825 pub fn paths(&self) -> Vec<Vec<(f32, f32)>> {
828 let mut out = Vec::with_capacity(self.contours.len());
829 for c in &self.contours {
830 let mut pts = Vec::new();
831 Self::flatten_contour(c.start, &c.segs, &mut pts);
832 if pts.first() == pts.last() && pts.len() > 1 {
833 pts.pop();
834 }
835 if pts.len() >= 2 {
836 out.push(pts);
837 }
838 }
839 if !self.segs.is_empty() {
841 let mut pts = Vec::new();
842 Self::flatten_contour(self.start, &self.segs, &mut pts);
843 if pts.first() == pts.last() && pts.len() > 1 {
844 pts.pop();
845 }
846 if pts.len() >= 2 {
847 out.push(pts);
848 }
849 }
850 out
851 }
852
853 pub fn curve_contours(&self) -> Vec<((f32, f32), Vec<PathSeg>, bool)> {
859 let mut out = Vec::with_capacity(self.contours.len() + 1);
860 for c in &self.contours {
861 out.push((c.start, c.segs.clone(), c.closed));
862 }
863 if !self.segs.is_empty() {
864 out.push((self.start, self.segs.clone(), false));
865 }
866 out
867 }
868
869 pub fn paths_with_closed(&self) -> Vec<(Vec<(f32, f32)>, bool)> {
874 let mut out = Vec::with_capacity(self.contours.len() + 1);
875 for c in &self.contours {
876 let mut pts = Vec::new();
877 Self::flatten_contour(c.start, &c.segs, &mut pts);
878 if pts.first() == pts.last() && pts.len() > 1 {
879 pts.pop();
880 }
881 if pts.len() >= 2 {
882 out.push((pts, c.closed));
883 }
884 }
885 if !self.segs.is_empty() {
886 let mut pts = Vec::new();
887 Self::flatten_contour(self.start, &self.segs, &mut pts);
888 if pts.first() == pts.last() && pts.len() > 1 {
889 pts.pop();
890 }
891 if pts.len() >= 2 {
892 out.push((pts, false));
893 }
894 }
895 out
896 }
897
898 pub fn fill(self, color: Color, list: &mut PaintList) {
901 if self.contours.is_empty() && self.segs.is_empty() {
902 return;
903 }
904 let mut clean_contours: Vec<Vec<(f32, f32)>> = Vec::with_capacity(self.contours.len());
906 for c in self.contours.iter() {
907 let mut pts = Vec::new();
908 Self::flatten_contour(c.start, &c.segs, &mut pts);
909 if pts.first() == pts.last() && pts.len() > 1 {
910 pts.pop();
911 }
912 if pts.len() >= 3 {
913 clean_contours.push(pts);
914 }
915 }
916 if clean_contours.is_empty() {
917 return;
918 }
919
920 let mut flat: Vec<(f32, f32)> = Vec::new();
922 let mut hole_offsets: Vec<usize> = Vec::new();
923 let mut first = true;
924 for contour in clean_contours.iter() {
925 if !first {
926 hole_offsets.push(flat.len());
927 }
928 first = false;
929 for &p in contour {
930 flat.push(p);
931 }
932 }
933 let (tri_points, indices) = earcut(&flat, if hole_offsets.is_empty() { None } else { Some(&hole_offsets) });
937 if indices.len() < 3 {
938 return;
939 }
940 let vertices: Vec<Vertex> = tri_points.iter().map(|&(x, y)| Vertex { x, y, color }).collect();
941 list.push(PaintCommand::Triangles { vertices, indices });
942 }
943}
944
945#[allow(dead_code)]
950const MAX_FLATTEN_DEPTH: u32 = 10;
951
952#[allow(clippy::too_many_arguments)]
953fn flatten_quad_bezier(x0: f32, y0: f32, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32, out: &mut Vec<(f32, f32)>) {
954 let dx = ex - x0;
956 let dy = ey - y0;
957 let len_sq = dx * dx + dy * dy;
958 if len_sq < 1e-6 {
959 out.push((ex, ey));
960 return;
961 }
962 let cross = dx * (cy - y0) - dy * (cx - x0);
964 let dist = (cross / len_sq.sqrt().max(1e-6)).abs();
965 if dist < flat {
966 out.push((ex, ey));
967 return;
968 }
969 let mx0 = (x0 + cx) / 2.0;
971 let my0 = (y0 + cy) / 2.0;
972 let mx1 = (cx + ex) / 2.0;
973 let my1 = (cy + ey) / 2.0;
974 let mx = (mx0 + mx1) / 2.0;
975 let my = (my0 + my1) / 2.0;
976 flatten_quad_bezier(x0, y0, mx0, my0, mx, my, flat, out);
977 flatten_quad_bezier(mx, my, mx1, my1, ex, ey, flat, out);
978}
979
980#[allow(dead_code, clippy::too_many_arguments)]
982fn flatten_cubic_bezier(
983 x0: f32,
984 y0: f32,
985 x1: f32,
986 y1: f32,
987 x2: f32,
988 y2: f32,
989 x3: f32,
990 y3: f32,
991 flat: f32,
992 out: &mut Vec<(f32, f32)>,
993) {
994 let dx = x3 - x0;
996 let dy = y3 - y0;
997 let len = (dx * dx + dy * dy).sqrt().max(1e-6);
998 let d1 = (dx * (y1 - y0) - dy * (x1 - x0)).abs() / len;
999 let d2 = (dx * (y2 - y0) - dy * (x2 - x0)).abs() / len;
1000 if d1.max(d2) < flat {
1001 out.push((x3, y3));
1002 return;
1003 }
1004 let (mx01x, mx01y) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
1005 let (mx12x, mx12y) = ((x1 + x2) / 2.0, (y1 + y2) / 2.0);
1006 let (mx23x, mx23y) = ((x2 + x3) / 2.0, (y2 + y3) / 2.0);
1007 let (mxx, mxy) = ((mx01x + mx12x) / 2.0, (mx01y + mx12y) / 2.0);
1008 let (myy, myz) = ((mx12x + mx23x) / 2.0, (mx12y + mx23y) / 2.0);
1009 let (midx, midy) = ((mxx + myy) / 2.0, (mxy + myz) / 2.0);
1010 flatten_cubic_bezier(x0, y0, mx01x, mx01y, mxx, mxy, midx, midy, flat, out);
1011 flatten_cubic_bezier(midx, midy, myy, myz, mx23x, mx23y, x3, y3, flat, out);
1012}
1013
1014fn earcut(points: &[(f32, f32)], hole_offsets: Option<&[usize]>) -> (Vec<(f32, f32)>, Vec<u32>) {
1020 let n = points.len();
1021 if n < 3 {
1022 return (Vec::new(), Vec::new());
1023 }
1024 if hole_offsets.is_none() {
1026 return (points.to_vec(), earcut_single(points));
1027 }
1028 let hole_offsets = hole_offsets.unwrap();
1031 let mut merged: Vec<(f32, f32)> = Vec::with_capacity(n + hole_offsets.len());
1032 let first_end = hole_offsets.first().copied().unwrap_or(n);
1034 merged.extend_from_slice(&points[0..first_end]);
1035 let mut contour_start = first_end;
1037 for &end_idx in hole_offsets.iter().skip(1) {
1038 let hole = &points[contour_start..end_idx];
1039 bridge_hole(&mut merged, hole);
1040 contour_start = end_idx;
1041 }
1042 if contour_start < n {
1043 let last = &points[contour_start..n];
1044 bridge_hole(&mut merged, last);
1045 }
1046 let indices = earcut_single(&merged);
1047 (merged, indices)
1048}
1049
1050fn bridge_hole(outer: &mut Vec<(f32, f32)>, hole: &[(f32, f32)]) {
1052 if hole.is_empty() {
1053 return;
1054 }
1055 let mut hole = hole.to_vec();
1057 let outer_ccw = area2(outer) > 0.0;
1058 let hole_ccw = area2(&hole) > 0.0;
1059 if hole_ccw == outer_ccw {
1060 hole.reverse();
1061 }
1062 let hole_pt = hole[0];
1064 let mut best_i = 0usize;
1065 let mut best_d = f32::INFINITY;
1066 for (i, &p) in outer.iter().enumerate() {
1067 let d = (p.0 - hole_pt.0).powi(2) + (p.1 - hole_pt.1).powi(2);
1068 if d < best_d {
1069 best_d = d;
1070 best_i = i;
1071 }
1072 }
1073 let insert_pos = best_i + 1;
1074 let skip_last = if hole.first() == hole.last() { hole.len() - 1 } else { hole.len() };
1075 let bridge = outer[best_i];
1076 outer.insert(insert_pos, bridge);
1080 outer.splice(insert_pos + 1..insert_pos + 1, hole[..skip_last].iter().copied());
1081 let close_pos = insert_pos + 1 + skip_last;
1082 if let Some(&first) = hole.first() {
1083 outer.insert(close_pos, first);
1084 outer.insert(close_pos + 1, bridge);
1085 }
1086}
1087
1088fn earcut_single(points: &[(f32, f32)]) -> Vec<u32> {
1090 let n = points.len();
1091 let points = if points.first() == points.last() { &points[..n - 1] } else { points };
1093 let n = points.len();
1094 if n < 3 {
1095 return Vec::new();
1096 }
1097
1098 let mut result = Vec::with_capacity((n - 2) * 3);
1099 let mut active: Vec<usize> = (0..n).collect();
1101 let ccw = area2(points) > 0.0;
1103
1104 let mut safety = n * n; while active.len() >= 3 && safety > 0 {
1107 safety -= 1;
1108 if active.len() == 3 {
1109 let (a, b, c) = (active[0], active[1], active[2]);
1113 let (ax, ay) = points[a];
1114 let (bx, by) = points[b];
1115 let (cx, cy) = points[c];
1116 let cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
1117 if cross.abs() > 1e-6 {
1118 result.push(a as u32);
1119 result.push(b as u32);
1120 result.push(c as u32);
1121 }
1122 break;
1123 }
1124 let m = active.len();
1125 let mut found = None;
1126 for j in 0..m {
1127 let prev = active[(j + m - 1) % m];
1128 let curr = active[j];
1129 let next = active[(j + 1) % m];
1130 if is_ear(points, prev, curr, next, ccw) {
1131 found = Some(j);
1132 break;
1133 }
1134 }
1135 match found {
1136 Some(j) => {
1137 let prev = active[(j + m - 1) % m];
1138 let curr = active[j];
1139 let next = active[(j + 1) % m];
1140 result.push(prev as u32);
1141 result.push(curr as u32);
1142 result.push(next as u32);
1143 active.remove(j);
1144 }
1145 None => {
1146 return fan_triangulation(points);
1148 }
1149 }
1150 }
1151 if result.is_empty() {
1152 fan_triangulation(points)
1153 } else {
1154 result
1155 }
1156}
1157
1158fn area2(points: &[(f32, f32)]) -> f32 {
1159 let mut a = 0.0f32;
1160 for w in points.windows(2) {
1161 a += w[0].0 * w[1].1 - w[1].0 * w[0].1;
1162 }
1163 if points.len() >= 2 {
1164 a += points.last().unwrap().0 * points[0].1 - points[0].0 * points.last().unwrap().1;
1165 }
1166 a
1167}
1168
1169fn is_ear(points: &[(f32, f32)], a: usize, b: usize, c: usize, ccw: bool) -> bool {
1170 let (ax, ay) = points[a];
1171 let (bx, by) = points[b];
1172 let (cx, cy) = points[c];
1173 let abc_cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
1176 if (abc_cross > 0.0) != ccw {
1177 return false;
1178 }
1179 for (i, &(px, py)) in points.iter().enumerate() {
1181 if i == a || i == b || i == c {
1182 continue;
1183 }
1184 if point_in_triangle(px, py, ax, ay, bx, by, cx, cy) {
1185 return false;
1186 }
1187 }
1188 true
1189}
1190
1191#[allow(clippy::too_many_arguments)]
1192fn point_in_triangle(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32, cx: f32, cy: f32) -> bool {
1193 let v0x = cx - ax;
1194 let v0y = cy - ay;
1195 let v1x = bx - ax;
1196 let v1y = by - ay;
1197 let v2x = px - ax;
1198 let v2y = py - ay;
1199
1200 let dot00 = v0x * v0x + v0y * v0y;
1201 let dot01 = v0x * v1x + v0y * v1y;
1202 let dot02 = v0x * v2x + v0y * v2y;
1203 let dot11 = v1x * v1x + v1y * v1y;
1204 let dot12 = v1x * v2x + v1y * v2y;
1205
1206 let inv_denom = 1.0 / (dot00 * dot11 - dot01 * dot01).max(1e-9);
1207 let u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
1208 let v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
1209 const EPS: f32 = 1e-6;
1212 u > EPS && v > EPS && (u + v) < 1.0 - EPS
1213}
1214
1215fn fan_triangulation(points: &[(f32, f32)]) -> Vec<u32> {
1217 let mut result = Vec::new();
1218 if points.len() < 3 {
1219 return result;
1220 }
1221 let base = points[0];
1222 for i in 2..points.len() {
1224 let mut ok = true;
1226 for j in 1..points.len() {
1227 if j == i || j == 0 {
1228 continue;
1229 }
1230 if point_in_triangle(
1231 points[j].0,
1232 points[j].1,
1233 base.0,
1234 base.1,
1235 points[1].0,
1236 points[1].1,
1237 points[i].0,
1238 points[i].1,
1239 ) {
1240 ok = false;
1241 break;
1242 }
1243 }
1244 if ok {
1245 result.push(0u32);
1246 result.push(1u32);
1247 result.push(i as u32);
1248 }
1249 }
1250 if result.len() < 3 && points.len() >= 3 {
1252 let n = points.len() as u32;
1253 for i in 1..n - 1 {
1254 result.push(0);
1255 result.push(i);
1256 result.push(i + 1);
1257 }
1258 }
1259 result
1260}
1261
1262#[cfg(test)]
1263mod tests {
1264 use super::*;
1265 use crate::Color;
1266
1267 #[test]
1268 fn content_digest_is_stable_and_sensitive_to_pixel_inputs() {
1269 let mut a = PaintList::new();
1270 a.rect(Rect::new(1.0, 2.0, 30.0, 40.0), Color::rgb(0.1, 0.2, 0.3));
1271 a.text("你好", 14.0, Color::WHITE, Point::new(3.0, 4.0));
1272 let b = a.clone();
1273 assert_eq!(a.content_digest(), b.content_digest());
1274
1275 let mut changed = a.clone();
1276 if let PaintCommand::Rect { color, .. } = &mut changed.commands[0] {
1277 color.r = 0.9;
1278 }
1279 assert_ne!(a.content_digest(), changed.content_digest(), "颜色变化必须改变 key");
1280
1281 let mut changed = a.clone();
1282 changed.text("你坏", 14.0, Color::WHITE, Point::new(3.0, 4.0));
1283 assert_ne!(a.content_digest(), changed.content_digest(), "文本变化必须改变 key");
1284 }
1285
1286 #[test]
1287 fn path_builder_triangulates_square() {
1288 let mut pb = PathBuilder::new();
1289 pb.move_to(0.0, 0.0);
1290 pb.line_to(100.0, 0.0);
1291 pb.line_to(100.0, 100.0);
1292 pb.line_to(0.0, 100.0);
1293 pb.close();
1294 let mut list = PaintList::new();
1295 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1296 assert_eq!(list.commands.len(), 1);
1297 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1298 assert_eq!(vertices.len(), 4);
1300 assert_eq!(indices.len(), 6);
1301 } else {
1302 panic!("expected Triangles");
1303 }
1304 }
1305
1306 #[test]
1307 fn path_builder_quadbezier_flattens() {
1308 let mut pb = PathBuilder::new();
1309 pb.move_to(0.0, 50.0);
1310 pb.quad_to(50.0, 0.0, 100.0, 50.0, 0.5);
1311 pb.quad_to(50.0, 100.0, 0.0, 50.0, 0.5);
1312 pb.close();
1313 let mut list = PaintList::new();
1314 pb.fill(Color::rgb(0.0, 1.0, 0.0), &mut list);
1315 assert_eq!(list.commands.len(), 1);
1316 if let PaintCommand::Triangles { indices, .. } = &list.commands[0] {
1317 assert!(indices.len() >= 6, "bezier triangulation should produce >= 6 indices, got {}", indices.len());
1318 }
1319 }
1320
1321 #[test]
1322 fn path_builder_arc_to_produces_points() {
1323 let mut pb = PathBuilder::new();
1324 pb.move_to(100.0, 100.0);
1326 pb.arc_to(100.0, 100.0, 50.0, 0.0, std::f32::consts::FRAC_PI_2, 16);
1327 pb.close();
1328 let mut list = PaintList::new();
1329 pb.fill(Color::WHITE, &mut list);
1330
1331 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1332 assert!(vertices.len() >= 4, "arc + close → 至少 4 vertices");
1333 assert!(indices.len() >= 6, "earcut → 至少 1 triangle(3 indices)");
1334 for v in vertices {
1336 let dx = v.x - 100.0;
1337 let dy = v.y - 100.0;
1338 let d = (dx * dx + dy * dy).sqrt();
1339 assert!((d - 50.0).abs() < 1.0 || d < 1.0, "vertex ({}, {}) should be at r≈50 or center", v.x, v.y);
1340 }
1341 }
1342 }
1343
1344 #[test]
1345 fn path_builder_annulus_sector_triangulates() {
1346 let cx = 100.0;
1348 let cy = 100.0;
1349 let outer_r = 80.0;
1350 let inner_r = 60.0;
1351 let start_a = -std::f32::consts::FRAC_PI_2;
1352 let end_a = start_a + std::f32::consts::TAU * 0.75; let segs = 32u32;
1354
1355 let mut pb = PathBuilder::new();
1356 pb.move_to(cx + outer_r * start_a.cos(), cy + outer_r * start_a.sin());
1357 pb.arc_to(cx, cy, outer_r, start_a, end_a, segs);
1358 pb.line_to(cx + inner_r * end_a.cos(), cy + inner_r * end_a.sin());
1359 pb.arc_to(cx, cy, inner_r, end_a, start_a, segs);
1360 pb.close();
1361
1362 let mut list = PaintList::new();
1363 pb.fill(Color::rgb(0.2, 0.6, 1.0), &mut list);
1364
1365 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1366 assert!(vertices.len() >= 20, "annulus sector should have many vertices, got {}", vertices.len());
1368 assert!(indices.len() >= 6, "should produce triangles");
1369
1370 for v in vertices {
1372 let dx = v.x - cx;
1373 let dy = v.y - cy;
1374 let d = (dx * dx + dy * dy).sqrt();
1375 let on_outer = (d - outer_r).abs() < 1.0;
1376 let on_inner = (d - inner_r).abs() < 1.0;
1377 let on_radial = v.y == cy; assert!(
1379 on_outer || on_inner || on_radial,
1380 "vertex ({}, {}) d={} not on inner/outer/radial",
1381 v.x,
1382 v.y,
1383 d
1384 );
1385 }
1386 }
1387 }
1388
1389 #[test]
1390 fn box_shadow_pads_four_sigma_and_shrinks_radius_on_negative_spread() {
1391 let mut list = PaintList::new();
1392 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);
1393 match &list.commands[0] {
1394 PaintCommand::BoxShadow { rect, radius, blur_radius, .. } => {
1395 assert_eq!(*rect, Rect::new(-9.0, 2.0, 142.0, 92.0));
1397 assert_eq!(*radius, 9.0, "正 spread 圆角增大");
1398 assert_eq!(*blur_radius, 5.0);
1399 }
1400 other => panic!("expected BoxShadow, got {other:?}"),
1401 }
1402
1403 let mut list = PaintList::new();
1404 list.box_shadow(Rect::new(0.0, 0.0, 100.0, 50.0), Point::ZERO, 0.0, -4.0, Color::BLACK, 10.0);
1405 match &list.commands[0] {
1406 PaintCommand::BoxShadow { rect, radius, .. } => {
1407 assert_eq!(*rect, Rect::new(4.0, 4.0, 92.0, 42.0));
1408 assert_eq!(*radius, 6.0, "负 spread 圆角应收缩");
1409 }
1410 other => panic!("expected BoxShadow, got {other:?}"),
1411 }
1412 }
1413
1414 #[test]
1415 fn path_builder_empty_nop() {
1416 let pb = PathBuilder::new();
1417 let mut list = PaintList::new();
1418 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1419 assert!(list.is_empty());
1420 }
1421
1422 #[test]
1423 fn earcut_simple_triangle() {
1424 let pts = vec![(0.0, 0.0), (10.0, 0.0), (5.0, 10.0), (0.0, 0.0)];
1425 let (points, indices) = earcut(&pts, None);
1426 assert_eq!(indices.len(), 3);
1428 let unique: std::collections::HashSet<&u32> = indices.iter().collect();
1429 assert_eq!(unique.len(), 3); assert!(indices.iter().all(|&i| (i as usize) < points.len()));
1432 }
1433
1434 fn tri_area_sum(points: &[(f32, f32)], indices: &[u32]) -> f32 {
1435 let mut area = 0.0;
1436 for t in indices.as_chunks::<3>().0 {
1437 let (ax, ay) = points[t[0] as usize];
1438 let (bx, by) = points[t[1] as usize];
1439 let (cx, cy) = points[t[2] as usize];
1440 area += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() * 0.5;
1441 }
1442 area
1443 }
1444
1445 #[test]
1447 fn earcut_concave_polygon_area_matches() {
1448 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)];
1450 let (points, indices) = earcut(&pts, None);
1451 assert_eq!(indices.len(), 12, "6 顶点凹多边形 → 4 个三角形");
1452 assert!(indices.iter().all(|&i| (i as usize) < points.len()));
1453 let expected = area2(&pts).abs() * 0.5;
1454 let got = tri_area_sum(&points, &indices);
1455 assert!((got - expected).abs() < 0.5, "凹多边形面积: expected={expected}, got={got}");
1456 }
1457
1458 #[test]
1460 fn earcut_donut_hole_area_subtracted() {
1461 let outer = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
1462 let hole = vec![(25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0)];
1463 let mut pts = outer.clone();
1464 pts.extend_from_slice(&hole);
1465 let (points, indices) = earcut(&pts, Some(&[outer.len()]));
1466 assert!(!indices.is_empty());
1467 assert!(indices.iter().all(|&i| (i as usize) < points.len()), "索引不得越界");
1468 let got = tri_area_sum(&points, &indices);
1469 let expected = 100.0 * 100.0 - 50.0 * 50.0;
1470 assert!((got - expected).abs() < 1.0, "带洞面积: expected={expected}, got={got}");
1471 }
1472
1473 #[test]
1477 fn fill_multi_contour_indices_in_range() {
1478 let mut pb = PathBuilder::new();
1479 pb.move_to(0.0, 0.0);
1481 pb.line_to(100.0, 0.0);
1482 pb.line_to(100.0, 100.0);
1483 pb.line_to(0.0, 100.0);
1484 pb.close();
1485 pb.move_to(40.0, 40.0);
1487 pb.line_to(60.0, 40.0);
1488 pb.line_to(50.0, 60.0);
1489 pb.close();
1490 let mut list = PaintList::new();
1491 pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
1492 assert_eq!(list.commands.len(), 1);
1493 if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
1494 assert!(
1495 indices.iter().all(|&i| (i as usize) < vertices.len()),
1496 "索引 {} 越界(vertices.len={})",
1497 indices.iter().max().unwrap(),
1498 vertices.len()
1499 );
1500 } else {
1501 panic!("expected Triangles");
1502 }
1503 }
1504}