mgui-core 0.3.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
//! 绘制命令 + Layer 效果 —— 原 mgui-paint crate,已合入 mgui-core
//!
//! PaintCommand / PaintList / LayerEffect / effect_flags
//! 作为 RenderObject → Renderer 之间的中间协议。
//!
//! 版本演进:
//! v1: Rect / TexturedRect / PushClip / PopClip
//! v2: + Triangles(Path CPU tessellation) + PathBuilder
//! v3: + ClipRRect / 纹理 alpha mask / BlendMode

use std::rc::Rc;

use crate::geometry::{Color, Point, RRectDef, Rect, Transform2D};

/// 路径三角化后的顶点(wgpu VertexBuffer 零拷贝兼容)
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vertex {
    pub x: f32,
    pub y: f32,
    pub color: Color,
}

/// 纹理矩形(文字字形 / 图片)的采样模式
///
/// TexturedRect 与 text pipeline 共用一个 shader(text.wgsl),instance 里带
/// `mode` 标志,fragment 按模式选 alpha 来源:
/// - `Mask`:alpha 取纹理 **R 通道**(glyph atlas R8 / SVG 单色 tint coverage),
///   输出 `color.rgb`,alpha = `color.a × tex.r` — 一份 coverage 纹理任意着色
/// - `Color`:纹理是**直通(straight)RGBA 彩色位图**(SVG 全彩 / PNG 图片),
///   输出 `tex.rgb × color.rgb`,alpha = `tex.a × color.a`
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextureMode {
    /// 单色 mask:alpha 在纹理 R 通道
    Mask,
    /// 彩色 RGBA(straight alpha,非预乘)
    Color,
}

/// **P2-1.3** 绘制混合模式(固定功能可实现子集)。
///
/// 作用于后续的矩形族命令(`Rect` / `BoxShadow` / 渐变),配对
/// `PopBlendMode` 恢复。文字/图片/三角形当前固定 SrcOver。
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BlendMode {
    /// 常规 alpha 混合
    #[default]
    Normal,
    /// 正片叠底:src × dst
    Multiply,
    /// 滤色:src + dst − src × dst
    Screen,
    /// 线性相加:src + dst
    Add,
}

/// 单条绘制指令。
#[derive(Clone, Debug)]
pub enum PaintCommand {
    /// 填充矩形(可带圆角)
    Rect { rect: Rect, color: Color, radius: f32 },
    /// 纹理矩形(文字字形 / 图片)
    ///
    /// `uv` 是归一化纹理坐标 `(u0, v0, u1, v1)`,左上角原点。
    /// `texture_id` 在 0..n 范围内,具体含义由 renderer 决定
    /// (本阶段固定为 0 = glyph atlas)。
    TexturedRect {
        rect: Rect,
        color: Color,
        uv: [f32; 4],
        texture_id: u32,
        /// 纹理采样模式(glyph/SVG tint = Mask;全彩 SVG/PNG = Color)
        mode: TextureMode,
    },
    /// 三角网格(路径 CPU 三角化结果,PathBuilder → earcut → 本命令)
    ///
    /// vertices 按 indices 索引渲染 triangles,与 wgpu vertex pipeline 零拷贝兼容。
    /// renderer 按 `vertex[i]` 的 x/y 作为屏幕坐标(逻辑像素),color 直接来自 vertex。
    Triangles { vertices: Vec<Vertex>, indices: Vec<u32> },
    /// **Stage T2**:核心层 Widget 要画文字时用的高层命令
    ///
    /// 与 `TexturedRect`(低层 glyph quad)不同 — `Text` 让 renderer 自己调
    /// parley shaping + swash 栅格化。核心层 Widget 不需要知道 glyph 细节。
    ///
    /// renderer 在 collect_instances_segmented 里会 `paint_text_line(...)`
    /// 把它展开成 N 个 TexturedRect instances(每个 glyph 一个)。
    Text {
        /// 文本(`Rc<str>` 共享:同一整串被多条命令引用时零拷贝,
        /// runtime shaping 缓存也直接以它作 key,命中路径不再克隆全文)
        text: Rc<str>,
        /// 可选绘制子区间(字节,相对 `text`;None = 绘制全文)。
        /// 编辑器逐语法 span 绘制时复用整行 `Rc<str>`,只带区间,
        /// 避免"每个 span 一次子串 String 分配"。
        range: Option<(usize, usize)>,
        font_size: f32,
        color: Color,
        /// 绘制起点(逻辑像素,layer 本地坐标)
        position: Point,
        /// 可选 soft wrap 宽度(None = 单行)
        max_width: Option<f32>,
    },
    /// **T0-2:BoxShadow** — 带 GPU SDF blur 的圆角矩形阴影
    ///
    /// 与 `Rect { radius }` 的区别:额外携带 `blur_radius`(高斯模糊半径)。
    /// renderer 复用 Rect pipeline,shader 里 smoothstep AA 区间从 1px 扩展到 `1 + blur_radius`,
    /// 实现单 pass SDF blur(无需额外 render pass 或临时纹理)。
    ///
    /// **注意**:rect 应该已经包含 blur padding(即调用方负责外扩 blur_radius)。
    /// PaintList::box_shadow() helper 已自动处理 rect + offset + spread + blur padding。
    BoxShadow {
        rect: Rect,
        color: Color,
        radius: f32,
        /// 高斯模糊半径(逻辑像素);0 = 无 blur(等价普通 Rect)
        blur_radius: f32,
    },
    /// **P2-1.4b:背景模糊** — 对 rect 内**已绘制内容**做模糊(tint 可选)
    ///
    /// GPU 在命令处结束当前 pass → resolve snapshot → 重开 pass 采样 13-tap blur;
    /// 软件光栅化对当前目标像素做同参数卷积。矩形为圆角遮罩,外部不受影响。
    /// `tint.a` > 0 时把模糊结果向 `tint.rgb` 混合(磨砂玻璃色调)。
    BackdropBlur { rect: Rect, radius: f32, blur_radius: f32, tint: Color },
    /// **P2-1.4:内阴影** — 在矩形内侧沿边缘衰减的阴影(inset shadow)
    ///
    /// SDF 单 pass:边缘处 coverage=1,向中心按 `exp(-depth² / 2blur²)` 衰减;
    /// `blur_radius=0` 时为 1px 内侧描边。绘制在已有内容之上(SourceOver)。
    InsetShadow { rect: Rect, color: Color, radius: f32, blur_radius: f32 },
    /// 两色线性渐变矩形(可带圆角)。
    LinearGradient {
        rect: Rect,
        /// 渐变起点(layer 本地坐标)
        start: Point,
        /// 渐变终点
        end: Point,
        from: Color,
        to: Color,
        corner_radius: f32,
    },
    /// 两色径向渐变矩形(可带圆角)。
    RadialGradient { rect: Rect, center: Point, radial_radius: f32, from: Color, to: Color, corner_radius: f32 },
    /// **P2-1.3: 纹理 mask** — 用纹理 alpha 裁掉 layer 中已有内容(destination-in)
    ///
    /// 只影响 `rect` 范围内已经绘制的内容:`new_alpha = old_alpha × tex.a × alpha`。
    /// 纹理需通过 `PaintList::push_texture` 或 renderer 的 register_image 注册;
    /// `uv` 是归一化坐标(左上原点)。
    MaskRect { rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32 },
    /// **P2-1.3** 压入混合模式,作用于后续矩形族命令,直到 `PopBlendMode`
    PushBlendMode(BlendMode),
    /// 恢复上一个混合模式
    PopBlendMode,
    /// 压入裁剪矩形(layer 本地坐标)
    ///
    /// 之后的绘制命令都被裁在该矩形内,直到配对的 `PopClip`。
    /// 嵌套时与外层 clip 求交(即当前 clip = 所有未弹出 clip 的交集)。
    /// GPU 侧由 render pass 的 scissor_rect 精确实现。
    PushClip(Rect),
    /// **P2-1.3** 压入圆角矩形裁剪(layer 本地坐标),配对 `PopClip`
    ///
    /// 与 `PushClip` 共用同一剪裁栈;GPU 用 stencil SDF 三角形精确裁角,
    /// 软件光栅化用 tiny-skia 圆角路径 mask。`radius <= 0` 等价直角。
    PushClipRRect { rect: Rect, radius: f32 },
    /// 弹出最近一次 `PushClip` / `PushClipRRect`(与 push 严格配对)
    PopClip,
    /// **路径裁剪** — 压入一个 PathBuilder.fill() 产出的三角形网格作为裁剪区域
    ///
    /// - `vertices` + `indices` 与 `Triangles` 完全同结构(PathBuilder.fill() 的 earcut 输出)
    /// - GPU 用 stencil mask 精确裁剪(支持嵌套,见 `PushClipRRect` 同机制)
    /// - 嵌套时与外层 clip 求交
    PushClipPath { vertices: Vec<Vertex>, indices: Vec<u32> },
    /// 弹出最近一次 `PushClipPath`(也接受 `PushClipRRect`;与 push 严格配对)
    PopClipPath,
}

/// 一帧的绘制指令列表。
/// 保留式:跨帧复用,只有脏的 RenderObject 会重建自己那部分。
#[derive(Clone, Debug, Default)]
pub struct PaintList {
    pub commands: Vec<PaintCommand>,
    /// 侧通道:本帧 RenderObject 声明的新增待注册纹理
    /// renderer render 开始前 drain,调 register_image(幂等)
    /// 不走 PaintCommand 避免大数据 clone 污染绘制协议
    pub pending_textures: Vec<(u32, std::rc::Rc<crate::image::ImageData>)>,
}

// =================================================================
// Layer 合成时的视觉效果
// =================================================================

/// layer 合成到父 layer/surface 时的视觉效果
///
/// 嵌套 layer 树语义:child layer 的 effect 是相对于 parent layer 的
/// 局部坐标系(parent 已经做了 transform,child effect 是在 parent 变换
/// 之后的世界空间继续应用)。
///
/// `None` 是常见情况 — 大部分 layer 不需要 effect,shader 走快速路径。
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum LayerEffect {
    /// 无效果(默认值)— shader 走无开销 blit 路径
    #[default]
    None,
    /// 2D 仿射变换(平移+旋转+均匀缩放),绕 layer 中心
    Transform(Transform2D),
    /// 整体 alpha 乘(0.0 = 完全透明,1.0 = 不透明)
    Opacity(f32),
    /// 圆角裁剪(在 4 个角的圆角 SDF 区域 alpha=0)
    ClipRRect(RRectDef),
}

/// effect flag(bit field) — shader 用这个走分支
///
/// bit 分配(预留 8 bit):
/// - bit 0: has_transform
/// - bit 1: has_opacity
/// - bit 2: has_clip
/// - bit 3-7: 预留(Blur/DropShadow/ColorMatrix/Filters...)
pub mod effect_flags {
    pub const HAS_TRANSFORM: u32 = 1 << 0;
    pub const HAS_OPACITY: u32 = 1 << 1;
    pub const HAS_CLIP: u32 = 1 << 2;
    /// bit 3 预留(Blur)
    pub const HAS_BLUR: u32 = 1 << 3;
    /// bit 4 预留(DropShadow)
    pub const HAS_DROP_SHADOW: u32 = 1 << 4;
}

impl PaintList {
    pub fn new() -> Self {
        Self { commands: Vec::new(), pending_textures: Vec::new() }
    }

    pub fn clear(&mut self) {
        self.commands.clear();
        self.pending_textures.clear();
    }

    pub fn push(&mut self, cmd: PaintCommand) {
        self.commands.push(cmd);
    }

    /// 声明一条待注册纹理(renderer render 开始前 drain)
    pub fn push_texture(&mut self, texture_id: u32, data: std::rc::Rc<crate::image::ImageData>) {
        self.pending_textures.push((texture_id, data));
    }

    /// 追加另一个 list 的所有 commands(多 layer 合成用)
    pub fn extend(&mut self, other: &PaintList) {
        self.commands.extend(other.commands.iter().cloned());
        // pending_textures 用 Rc::clone 合并(纹理声明可能来自子 layer)
        self.pending_textures.extend(other.pending_textures.iter().map(|(id, data)| (*id, std::rc::Rc::clone(data))));
    }

    /// 直角矩形
    pub fn rect(&mut self, rect: Rect, color: Color) {
        self.commands.push(PaintCommand::Rect { rect, color, radius: 0.0 });
    }

    /// 圆角矩形
    pub fn rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
        self.commands.push(PaintCommand::Rect { rect, color, radius });
    }

    /// 高层文字命令(runtime 层展开成 glyph quads)
    pub fn text(&mut self, text: impl Into<Rc<str>>, font_size: f32, color: Color, position: Point) {
        self.commands.push(PaintCommand::Text {
            text: text.into(),
            range: None,
            font_size,
            color,
            position,
            max_width: None,
        });
    }

    /// 带可选 soft wrap 的高层文字命令
    pub fn text_wrapped(
        &mut self,
        text: impl Into<Rc<str>>,
        font_size: f32,
        color: Color,
        position: Point,
        max_width: Option<f32>,
    ) {
        self.commands.push(PaintCommand::Text {
            text: text.into(),
            range: None,
            font_size,
            color,
            position,
            max_width,
        });
    }

    /// 共享整串 + 字节区间的高层文字命令
    ///
    /// 编辑器等"一行文本切多个语法 span"的场景使用:整行 `Rc<str>` 被所有
    /// span 命令共享,只携带区间,shaping 缓存命中时零字符串分配。
    pub fn text_span(&mut self, text: &Rc<str>, range: (usize, usize), font_size: f32, color: Color, position: Point) {
        self.commands.push(PaintCommand::Text {
            text: Rc::clone(text),
            range: Some(range),
            font_size,
            color,
            position,
            max_width: None,
        });
    }

    /// **T0-2:GPU SDF BoxShadow** — 单 pass shader blur(无需多 render pass)
    ///
    /// 旧 N 层半透明近似已被替代。现在发 1 个 `BoxShadow` 命令,
    /// renderer 复用 Rect pipeline,shader 里 smoothstep 过渡区从 1px 扩展到 blur_radius,
    /// 实现真正的 Gaussian-like blur。
    ///
    /// - `rect`:子元素 bounding box(阴影的"中心形状")
    /// - `offset`:阴影相对 rect 的偏移(dx, dy)
    /// - `blur_radius`:模糊半径(逻辑像素);shader smoothstep 区间 = ±blur_radius
    /// - `spread`:阴影扩张(+外扩/-内缩)
    /// - `color`:阴影颜色(通常带 alpha,如 Color::rgba(0,0,0,0.25))
    /// - `corner_radius`:子元素圆角(阴影同形状)
    pub fn box_shadow(
        &mut self,
        rect: Rect,
        offset: Point,
        blur_radius: f32,
        spread: f32,
        color: Color,
        corner_radius: f32,
    ) {
        // 1. 基础 shape rect(阴影几何中心)
        let sh_x = rect.x + offset.x - spread;
        let sh_y = rect.y + offset.y - spread;
        let sh_w = (rect.width + spread * 2.0).max(0.0);
        let sh_h = (rect.height + spread * 2.0).max(0.0);
        // 负 spread 收缩形状,圆角同步收缩(CSS/Flutter 语义)
        let base_radius = (corner_radius + spread).max(0.0);

        // 2. BoxShadow rect 外扩 4×blur — Gaussian 衰减到 d=4σ 时已 ≈0.03%
        // (exp(-8)),quad 边界不会留下硬切边。shader 侧约定同样按 4×blur
        // 还原基础 shape 的半尺寸(见 rect.wgsl 的 SHADOW_PAD_FACTOR)。
        let b = blur_radius.max(0.0);
        let pad = b * 4.0;
        let padded = Rect::new(sh_x - pad, sh_y - pad, sh_w + pad * 2.0, sh_h + pad * 2.0);

        self.commands.push(PaintCommand::BoxShadow {
            rect: padded,
            color,
            radius: base_radius, // **不扩 blur_radius**(shader 内补偿)
            blur_radius: b,
        });
    }

    /// 两色线性渐变(可带圆角)。
    pub fn linear_gradient(
        &mut self,
        rect: Rect,
        start: Point,
        end: Point,
        from: Color,
        to: Color,
        corner_radius: f32,
    ) {
        self.commands.push(PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius });
    }

    /// 两色径向渐变(可带圆角)。
    pub fn radial_gradient(
        &mut self,
        rect: Rect,
        center: Point,
        radial_radius: f32,
        from: Color,
        to: Color,
        corner_radius: f32,
    ) {
        self.commands.push(PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius });
    }

    /// 纹理 alpha mask(destination-in):裁掉此前已绘制内容的透明度。
    pub fn mask(&mut self, rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32) {
        self.commands.push(PaintCommand::MaskRect { rect, texture_id, uv, alpha: alpha.clamp(0.0, 1.0) });
    }

    /// 内阴影(绘制在 rect 内部边缘)
    pub fn inset_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur_radius: f32) {
        self.commands.push(PaintCommand::InsetShadow { rect, color, radius, blur_radius: blur_radius.max(0.0) });
    }

    /// 背景模糊(对 rect 内已绘制内容做 13-tap blur;tint.a 可加磨砂色调)
    pub fn backdrop_blur(&mut self, rect: Rect, radius: f32, blur_radius: f32, tint: Color) {
        self.commands.push(PaintCommand::BackdropBlur {
            rect,
            radius: radius.max(0.0),
            blur_radius: blur_radius.max(0.0),
            tint,
        });
    }

    /// 压入混合模式(作用于后续矩形族命令)
    pub fn push_blend_mode(&mut self, mode: BlendMode) {
        self.commands.push(PaintCommand::PushBlendMode(mode));
    }

    /// 恢复上一个混合模式
    pub fn pop_blend_mode(&mut self) {
        self.commands.push(PaintCommand::PopBlendMode);
    }

    /// 压入裁剪矩形(之后的绘制被裁在该矩形内,直到 `pop_clip`)
    pub fn push_clip(&mut self, rect: Rect) {
        self.commands.push(PaintCommand::PushClip(rect));
    }

    /// 压入圆角矩形裁剪(之后的绘制被裁在该圆角矩形内,直到 `pop_clip`)
    pub fn push_clip_rrect(&mut self, rect: Rect, radius: f32) {
        self.commands.push(PaintCommand::PushClipRRect { rect, radius });
    }

    /// 弹出最近一次 `push_clip`
    pub fn pop_clip(&mut self) {
        self.commands.push(PaintCommand::PopClip);
    }

    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }
    pub fn len(&self) -> usize {
        self.commands.len()
    }
}

// =================================================================
// PathBuilder — MoveTo/LineTo/QuadTo/CubicTo/Close → earcut → Triangles
// =================================================================
//
// v2 Path 填充方案:CPU 侧 flatten 贝塞尔为折线 + earcut 三角剖分,
// 结果 = PaintCommand::Triangles,走 wgpu vertex pipeline(与 renderer
// 现有 Rect pipeline 结构一致,新增极少)。
//
// 设计取舍:
// - fill 不支持 anti-aliasing / 自相交多边形 / 多回路洞(earcut 仅处理
//   简单非自相交多边形,UI 路径的典型场景)
// - **曲线段在存储期保留**(PathSeg::Quad/Cubic,fill 导出时才 flatten);
//   stroke 通道(curve_contours)把曲线直接交给描边器(如 tiny-skia
//   PathStroker),避免密集折线逼近导致的内 join 毛刺自相交
// - QuadTo flatten 用递归细分(flatness 小于给定容差时停止)

/// 路径段(曲线感知存储;fill/paths 导出时 flatten 成折线)
#[derive(Clone, Copy, Debug)]
pub enum PathSeg {
    /// 直线段终点
    Line(f32, f32),
    /// 二次贝塞尔:控制点 + 终点 + flatten 容差(各坐标空间)
    Quad { cx: f32, cy: f32, x: f32, y: f32, flat: f32 },
    /// 三次贝塞尔:两控制点 + 终点 + flatten 容差
    Cubic { c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32, flat: f32 },
}

/// 一条回路:起点 + 段序列 + 是否显式 close
#[derive(Clone, Debug, Default)]
struct Contour {
    start: (f32, f32),
    segs: Vec<PathSeg>,
    closed: bool,
}

impl PathSeg {
    /// 段终点
    fn end(&self) -> (f32, f32) {
        match *self {
            PathSeg::Line(x, y) => (x, y),
            PathSeg::Quad { x, y, .. } => (x, y),
            PathSeg::Cubic { x, y, .. } => (x, y),
        }
    }

    /// 坐标缩放(sx, sy);flatten 容差按 fscale 同步缩放(均匀缩放下严格正确)
    fn transform(&mut self, sx: f32, sy: f32, fscale: f32) {
        match self {
            PathSeg::Line(x, y) => {
                *x *= sx;
                *y *= sy;
            }
            PathSeg::Quad { cx, cy, x, y, flat } => {
                *cx *= sx;
                *cy *= sy;
                *x *= sx;
                *y *= sy;
                *flat *= fscale;
            }
            PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
                *c1x *= sx;
                *c1y *= sy;
                *c2x *= sx;
                *c2y *= sy;
                *x *= sx;
                *y *= sy;
                *flat *= fscale;
            }
        }
    }
}

/// 路径构造器(多回路,支持 fill 三角化与 stroke 曲线导出)
#[derive(Default, Clone, Debug)]
pub struct PathBuilder {
    /// 当前点
    cx: f32,
    cy: f32,
    /// 当前回路起点(move_to 设置)
    start: (f32, f32),
    /// 当前回路的段(未 close 前积累在此)
    segs: Vec<PathSeg>,
    /// 已完成回路(close 或 move_to 冲刷)
    contours: Vec<Contour>,
}

impl PathBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// 对所有已积累的坐标乘 (sx, sy) —— 用于把 viewBox 坐标缩放到屏幕像素。
    /// 段内 flatten 容差按 max(|sx|,|sy|) 同步缩放(均匀缩放下严格正确)。
    pub fn transform(&mut self, sx: f32, sy: f32) {
        let fscale = sx.abs().max(sy.abs());
        for c in self.contours.iter_mut() {
            c.start.0 *= sx;
            c.start.1 *= sy;
            for seg in c.segs.iter_mut() {
                seg.transform(sx, sy, fscale);
            }
        }
        self.start.0 *= sx;
        self.start.1 *= sy;
        for seg in self.segs.iter_mut() {
            seg.transform(sx, sy, fscale);
        }
        self.cx *= sx;
        self.cy *= sy;
    }

    /// 把回路 flatten 成折线(导出用;首点为回路起点,不含重复尾点)
    fn flatten_contour(start: (f32, f32), segs: &[PathSeg], out: &mut Vec<(f32, f32)>) {
        out.push(start);
        let (mut x0, mut y0) = start;
        for seg in segs {
            match *seg {
                PathSeg::Line(x, y) => out.push((x, y)),
                PathSeg::Quad { cx, cy, x, y, flat } => flatten_quad_bezier(x0, y0, cx, cy, x, y, flat, out),
                PathSeg::Cubic { c1x, c1y, c2x, c2y, x, y, flat } => {
                    flatten_cubic_bezier(x0, y0, c1x, c1y, c2x, c2y, x, y, flat, out)
                }
            }
            x0 = seg.end().0;
            y0 = seg.end().1;
        }
    }

    pub fn move_to(&mut self, x: f32, y: f32) {
        // 先把之前未闭合的回路冲掉(如果有)
        if !self.segs.is_empty() {
            let segs = std::mem::take(&mut self.segs);
            self.contours.push(Contour { start: self.start, segs, closed: false });
        }
        self.start = (x, y);
        self.cx = x;
        self.cy = y;
    }

    pub fn line_to(&mut self, x: f32, y: f32) {
        self.segs.push(PathSeg::Line(x, y));
        self.cx = x;
        self.cy = y;
    }

    /// 二次贝塞尔(控制点 cx,cy,终点 ex,ey),flat = 当前坐标空间容差(0.5 / scale)。
    /// 存储期保留曲线,fill/paths 导出时才按 flat flatten。
    pub fn quad_to(&mut self, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32) {
        self.segs.push(PathSeg::Quad { cx, cy, x: ex, y: ey, flat });
        self.cx = ex;
        self.cy = ey;
    }

    /// 三次贝塞尔(控制点 c1/c2,终点 ex,ey),flat 语义同 quad_to
    #[allow(clippy::too_many_arguments)]
    pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, ex: f32, ey: f32, flat: f32) {
        self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: ex, y: ey, flat });
        self.cx = ex;
        self.cy = ey;
    }

    /// 圆弧(圆心 cx,cy + 半径 r + 起/终角度(弧度) + 分段数上限)
    /// 以三次贝塞尔段逼近存储(kappa 圆逼近),fill 导出时 flatten。
    ///
    /// - `start_angle`/`end_angle` 标准数学极坐标:0 = +X 轴,逆时针增大
    /// - `num_segments` 只是段数上限;实际段数 = ceil(|sweep| / 90°)
    /// - 自动处理跨过 ±TAU 的情况(end < start 时逆时针走大弧)
    pub fn arc_to(&mut self, cx: f32, cy: f32, r: f32, start_angle: f32, end_angle: f32, num_segments: u32) {
        if r <= 0.0 {
            return;
        }
        let sweep = end_angle - start_angle;
        // 避免完全闭合(会产生自相交或多 contour 问题) — earcut 单 contour 要求简单多边形
        let sweep = if sweep.abs() >= std::f32::consts::TAU { sweep * 0.999 } else { sweep };

        // 段数:每段 ≤90°(kappa 精确逼近,径向误差 ~2.7e-4·r,远低于 0.5px 光栅化
        // 精度)。**不要细分更多**:stroker 在每段边界发 inner join,段越多毛刺越多
        // (32 段/90° 实测产生叶片伪影;usvg 归一化就是 90° 1 段)。cubic stroke 的
        // 平行曲线由描边器自行细分,无需输入侧预细分。fill(earcut) 侧 flat 已足够。
        let segs = (((sweep.abs() / std::f32::consts::FRAC_PI_2).ceil()) as u32).clamp(1, num_segments.max(1));
        let step = sweep / segs as f32;
        let flat = (r * step).abs() * 0.05;

        // 兼容性:旧 arc_to 总是先落弧起点 —— 调用方惯用法有两种:
        // ① move_to(弧起点) 后续接(当前点 == 弧起点,无需补线)
        // ② move_to(圆心) 画饼形(需要一条 圆心→弧起点 的径向边)
        // 当前点偏离弧起点时补 Line,两种惯用法都得到与旧版相同的折线。
        let (sx, sy) = (cx + r * start_angle.cos(), cy + r * start_angle.sin());
        let dcx = sx - self.cx;
        let dcy = sy - self.cy;
        if dcx * dcx + dcy * dcy > 1e-12 {
            self.segs.push(PathSeg::Line(sx, sy));
            self.cx = sx;
            self.cy = sy;
        }

        let k = (4.0 / 3.0) * (step / 4.0).tan() * r; // 控制点切向偏移长度
        let mut a0 = start_angle;
        for _ in 0..segs {
            let a1 = a0 + step;
            let (x0, y0) = (cx + r * a0.cos(), cy + r * a0.sin());
            let (x1, y1) = (cx + r * a1.cos(), cy + r * a1.sin());
            // 切向(角度递增方向)= (-sin a, cos a)
            let c1x = x0 - k * a0.sin();
            let c1y = y0 + k * a0.cos();
            let c2x = x1 + k * a1.sin();
            let c2y = y1 - k * a1.cos();
            self.segs.push(PathSeg::Cubic { c1x, c1y, c2x, c2y, x: x1, y: y1, flat });
            self.cx = x1;
            self.cy = y1;
            a0 = a1;
        }
    }

    pub fn close(&mut self) {
        if !self.segs.is_empty() {
            let segs = std::mem::take(&mut self.segs);
            // closed = 显式 close(earcut/fill 按闭合回路处理)
            self.contours.push(Contour { start: self.start, segs, closed: true });
        }
    }

    /// 导出所有已闭合回路(去掉首尾重复点;曲线段 flatten 成折线)。
    /// 需要曲线时请用 curve_contours。
    pub fn paths(&self) -> Vec<Vec<(f32, f32)>> {
        let mut out = Vec::with_capacity(self.contours.len());
        for c in &self.contours {
            let mut pts = Vec::new();
            Self::flatten_contour(c.start, &c.segs, &mut pts);
            if pts.first() == pts.last() && pts.len() > 1 {
                pts.pop();
            }
            if pts.len() >= 2 {
                out.push(pts);
            }
        }
        // 如果还有未闭合回路(没 close),也导出来(首尾不重复)
        if !self.segs.is_empty() {
            let mut pts = Vec::new();
            Self::flatten_contour(self.start, &self.segs, &mut pts);
            if pts.first() == pts.last() && pts.len() > 1 {
                pts.pop();
            }
            if pts.len() >= 2 {
                out.push(pts);
            }
        }
        out
    }

    /// 曲线保留导出:每个回路 (起点, 段序列, 是否显式 close)。
    ///
    /// 与 paths() 的区别:Quad/Cubic **不 flatten**,把曲线原样交给曲线感知
    /// 消费者(如 tiny-skia PathStroker 的 quad/cubic stroke 路径)——密集折线
    /// 逼近会让 stroker 在每个折点发 inner join 毛刺,锐角/密段时互相交叉。
    pub fn curve_contours(&self) -> Vec<((f32, f32), Vec<PathSeg>, bool)> {
        let mut out = Vec::with_capacity(self.contours.len() + 1);
        for c in &self.contours {
            out.push((c.start, c.segs.clone(), c.closed));
        }
        if !self.segs.is_empty() {
            out.push((self.start, self.segs.clone(), false));
        }
        out
    }

    /// 导出所有回路及其闭合状态:`(回路折线, 是否显式 close)`。
    ///
    /// 闭合判定:显式 close 的回路 closed=true;move_to 冲刷的未闭合回路
    /// closed=false。stroke 需要区分开/闭路径(开放路径不补 closing 边)。
    pub fn paths_with_closed(&self) -> Vec<(Vec<(f32, f32)>, bool)> {
        let mut out = Vec::with_capacity(self.contours.len() + 1);
        for c in &self.contours {
            let mut pts = Vec::new();
            Self::flatten_contour(c.start, &c.segs, &mut pts);
            if pts.first() == pts.last() && pts.len() > 1 {
                pts.pop();
            }
            if pts.len() >= 2 {
                out.push((pts, c.closed));
            }
        }
        if !self.segs.is_empty() {
            let mut pts = Vec::new();
            Self::flatten_contour(self.start, &self.segs, &mut pts);
            if pts.first() == pts.last() && pts.len() > 1 {
                pts.pop();
            }
            if pts.len() >= 2 {
                out.push((pts, false));
            }
        }
        out
    }

    /// 把已闭合回路三角化为 PaintCommand::Triangles 并写进 list。
    /// 支持多回路(外轮廓顺时针 + 内洞逆时针的 winding rule)。
    pub fn fill(self, color: Color, list: &mut PaintList) {
        if self.contours.is_empty() && self.segs.is_empty() {
            return;
        }
        // 处理每条回路:曲线段 flatten;去掉首尾重复点
        let mut clean_contours: Vec<Vec<(f32, f32)>> = Vec::with_capacity(self.contours.len());
        for c in self.contours.iter() {
            let mut pts = Vec::new();
            Self::flatten_contour(c.start, &c.segs, &mut pts);
            if pts.first() == pts.last() && pts.len() > 1 {
                pts.pop();
            }
            if pts.len() >= 3 {
                clean_contours.push(pts);
            }
        }
        if clean_contours.is_empty() {
            return;
        }

        // earcut 需要所有顶点 flatten 成一个大数组,外加每条回路的起始索引
        let mut flat: Vec<(f32, f32)> = Vec::new();
        let mut hole_offsets: Vec<usize> = Vec::new();
        let mut first = true;
        for contour in clean_contours.iter() {
            if !first {
                hole_offsets.push(flat.len());
            }
            first = false;
            for &p in contour {
                flat.push(p);
            }
        }
        // 关键:顶点必须取自 earcut 实际索引的那份点集 —— 多回路(含洞)时
        // earcut 会把洞桥接进外轮廓生成新的顶点数组,索引指向它而非 flat,
        // 若此处仍用 flat 建 vertices,索引会越界(GPU 静默读垃圾,CPU 光栅化 panic)。
        let (tri_points, indices) = earcut(&flat, if hole_offsets.is_empty() { None } else { Some(&hole_offsets) });
        if indices.len() < 3 {
            return;
        }
        let vertices: Vec<Vertex> = tri_points.iter().map(|&(x, y)| Vertex { x, y, color }).collect();
        list.push(PaintCommand::Triangles { vertices, indices });
    }
}

// =================================================================
// 数学工具:quad bezier flatten + earcut
// =================================================================

#[allow(dead_code)]
const MAX_FLATTEN_DEPTH: u32 = 10;

#[allow(clippy::too_many_arguments)]
fn flatten_quad_bezier(x0: f32, y0: f32, cx: f32, cy: f32, ex: f32, ey: f32, flat: f32, out: &mut Vec<(f32, f32)>) {
    // 控制点到首尾连线的距离,判断是否可以停止细分
    let dx = ex - x0;
    let dy = ey - y0;
    let len_sq = dx * dx + dy * dy;
    if len_sq < 1e-6 {
        out.push((ex, ey));
        return;
    }
    // 叉积:点到直线距离 * |ab| = |ab × ac|
    let cross = dx * (cy - y0) - dy * (cx - x0);
    let dist = (cross / len_sq.sqrt().max(1e-6)).abs();
    if dist < flat {
        out.push((ex, ey));
        return;
    }
    // 二分
    let mx0 = (x0 + cx) / 2.0;
    let my0 = (y0 + cy) / 2.0;
    let mx1 = (cx + ex) / 2.0;
    let my1 = (cy + ey) / 2.0;
    let mx = (mx0 + mx1) / 2.0;
    let my = (my0 + my1) / 2.0;
    flatten_quad_bezier(x0, y0, mx0, my0, mx, my, flat, out);
    flatten_quad_bezier(mx, my, mx1, my1, ex, ey, flat, out);
}

/// 三次贝塞尔 flatten(递归细分,flatness 容差)
#[allow(dead_code, clippy::too_many_arguments)]
fn flatten_cubic_bezier(
    x0: f32,
    y0: f32,
    x1: f32,
    y1: f32,
    x2: f32,
    y2: f32,
    x3: f32,
    y3: f32,
    flat: f32,
    out: &mut Vec<(f32, f32)>,
) {
    // 两控制点到首尾连线的最大距离作为 flatness
    let dx = x3 - x0;
    let dy = y3 - y0;
    let len = (dx * dx + dy * dy).sqrt().max(1e-6);
    let d1 = (dx * (y1 - y0) - dy * (x1 - x0)).abs() / len;
    let d2 = (dx * (y2 - y0) - dy * (x2 - x0)).abs() / len;
    if d1.max(d2) < flat {
        out.push((x3, y3));
        return;
    }
    let (mx01x, mx01y) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
    let (mx12x, mx12y) = ((x1 + x2) / 2.0, (y1 + y2) / 2.0);
    let (mx23x, mx23y) = ((x2 + x3) / 2.0, (y2 + y3) / 2.0);
    let (mxx, mxy) = ((mx01x + mx12x) / 2.0, (mx01y + mx12y) / 2.0);
    let (myy, myz) = ((mx12x + mx23x) / 2.0, (mx12y + mx23y) / 2.0);
    let (midx, midy) = ((mxx + myy) / 2.0, (mxy + myz) / 2.0);
    flatten_cubic_bezier(x0, y0, mx01x, mx01y, mxx, mxy, midx, midy, flat, out);
    flatten_cubic_bezier(midx, midy, myy, myz, mx23x, mx23y, x3, y3, flat, out);
}

/// earcut 三角剖分(简单多边形 O(n²) 剪耳法)
///
/// 返回 `(实际参与索引的点集, indices)`。单回路时返回原始 `points`;
/// 多回路(含洞)时返回桥接洞后合并出的新点集 —— 调用方必须用返回的点集
/// 构造顶点,否则 indices 会越界。
fn earcut(points: &[(f32, f32)], hole_offsets: Option<&[usize]>) -> (Vec<(f32, f32)>, Vec<u32>) {
    let n = points.len();
    if n < 3 {
        return (Vec::new(), Vec::new());
    }
    // 简单多边形(单 contour,无洞)
    if hole_offsets.is_none() {
        return (points.to_vec(), earcut_single(points));
    }
    // 多回路:把洞合并进外轮廓(按桥接边的方向拼接)
    // 简化实现:第一个 contour 为外轮廓,其余按顺序桥接
    let hole_offsets = hole_offsets.unwrap();
    let mut merged: Vec<(f32, f32)> = Vec::with_capacity(n + hole_offsets.len());
    // 外轮廓
    let first_end = hole_offsets.first().copied().unwrap_or(n);
    merged.extend_from_slice(&points[0..first_end]);
    // 每个洞:找最近点桥接
    let mut contour_start = first_end;
    for &end_idx in hole_offsets.iter().skip(1) {
        let hole = &points[contour_start..end_idx];
        bridge_hole(&mut merged, hole);
        contour_start = end_idx;
    }
    if contour_start < n {
        let last = &points[contour_start..n];
        bridge_hole(&mut merged, last);
    }
    let indices = earcut_single(&merged);
    (merged, indices)
}

/// 把洞桥接进外轮廓:找到外轮廓上离洞最近的点,在两者之间插入两条边
fn bridge_hole(outer: &mut Vec<(f32, f32)>, hole: &[(f32, f32)]) {
    if hole.is_empty() {
        return;
    }
    // 洞的 winding 必须与外轮廓相反;否则 earcut 会把洞当成实体重复填充
    let mut hole = hole.to_vec();
    let outer_ccw = area2(outer) > 0.0;
    let hole_ccw = area2(&hole) > 0.0;
    if hole_ccw == outer_ccw {
        hole.reverse();
    }
    // 找 outer 上离 hole 最近的点
    let hole_pt = hole[0];
    let mut best_i = 0usize;
    let mut best_d = f32::INFINITY;
    for (i, &p) in outer.iter().enumerate() {
        let d = (p.0 - hole_pt.0).powi(2) + (p.1 - hole_pt.1).powi(2);
        if d < best_d {
            best_d = d;
            best_i = i;
        }
    }
    let insert_pos = best_i + 1;
    let skip_last = if hole.first() == hole.last() { hole.len() - 1 } else { hole.len() };
    let bridge = outer[best_i];
    // 桥接必须「出去 → 绕洞一整圈 → 回到洞起点 → 原路返回」:
    // 只绕到洞的最后一个点就回去会漏掉洞的闭合边,填充区域会少掉
    // 外轮廓点与洞首尾之间的那块三角(甜甜圈面积对不上)。
    outer.insert(insert_pos, bridge);
    outer.splice(insert_pos + 1..insert_pos + 1, hole[..skip_last].iter().copied());
    let close_pos = insert_pos + 1 + skip_last;
    if let Some(&first) = hole.first() {
        outer.insert(close_pos, first);
        outer.insert(close_pos + 1, bridge);
    }
}

/// 单 contour earcut
fn earcut_single(points: &[(f32, f32)]) -> Vec<u32> {
    let n = points.len();
    // 去掉闭合时的重复首尾点
    let points = if points.first() == points.last() { &points[..n - 1] } else { points };
    let n = points.len();
    if n < 3 {
        return Vec::new();
    }

    let mut result = Vec::with_capacity((n - 2) * 3);
    // 活动节点链表:start = 0,按 ear 剪
    let mut active: Vec<usize> = (0..n).collect();
    // 轮廓 winding:凸角判定必须与整体方向一致(顺/逆时针都支持)
    let ccw = area2(points) > 0.0;

    // 迭代剪耳:每次找一个 ear triangle,把中间点从链表移除
    let mut safety = n * n; // 防无限循环
    while active.len() >= 3 && safety > 0 {
        safety -= 1;
        if active.len() == 3 {
            // 收尾三角形直接输出(弱简单多边形的桥接点常留下共线的最后三个点,
            // 用 is_ear 判会因面积≈0 失败并误触发整多边形 fan 兜底,把前面
            // 已经剪好的耳全部丢掉)。
            let (a, b, c) = (active[0], active[1], active[2]);
            let (ax, ay) = points[a];
            let (bx, by) = points[b];
            let (cx, cy) = points[c];
            let cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
            if cross.abs() > 1e-6 {
                result.push(a as u32);
                result.push(b as u32);
                result.push(c as u32);
            }
            break;
        }
        let m = active.len();
        let mut found = None;
        for j in 0..m {
            let prev = active[(j + m - 1) % m];
            let curr = active[j];
            let next = active[(j + 1) % m];
            if is_ear(points, prev, curr, next, ccw) {
                found = Some(j);
                break;
            }
        }
        match found {
            Some(j) => {
                let prev = active[(j + m - 1) % m];
                let curr = active[j];
                let next = active[(j + 1) % m];
                result.push(prev as u32);
                result.push(curr as u32);
                result.push(next as u32);
                active.remove(j);
            }
            None => {
                // 没 ear 了(自相交),直接用 fan 分解凸化近似
                return fan_triangulation(points);
            }
        }
    }
    if result.is_empty() {
        fan_triangulation(points)
    } else {
        result
    }
}

fn area2(points: &[(f32, f32)]) -> f32 {
    let mut a = 0.0f32;
    for w in points.windows(2) {
        a += w[0].0 * w[1].1 - w[1].0 * w[0].1;
    }
    if points.len() >= 2 {
        a += points.last().unwrap().0 * points[0].1 - points[0].0 * points.last().unwrap().1;
    }
    a
}

fn is_ear(points: &[(f32, f32)], a: usize, b: usize, c: usize, ccw: bool) -> bool {
    let (ax, ay) = points[a];
    let (bx, by) = points[b];
    let (cx, cy) = points[c];
    // 凸角判定:三角形方向必须与轮廓 winding 一致。凹(反射)顶点
    // 切出来的三角形会覆盖到多边形外,造成重叠/错色。
    let abc_cross = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
    if (abc_cross > 0.0) != ccw {
        return false;
    }
    // 检查没有其他点在三角形内部(严格内部:边界/共线点不阻塞剪耳)
    for (i, &(px, py)) in points.iter().enumerate() {
        if i == a || i == b || i == c {
            continue;
        }
        if point_in_triangle(px, py, ax, ay, bx, by, cx, cy) {
            return false;
        }
    }
    true
}

#[allow(clippy::too_many_arguments)]
fn point_in_triangle(px: f32, py: f32, ax: f32, ay: f32, bx: f32, by: f32, cx: f32, cy: f32) -> bool {
    let v0x = cx - ax;
    let v0y = cy - ay;
    let v1x = bx - ax;
    let v1y = by - ay;
    let v2x = px - ax;
    let v2y = py - ay;

    let dot00 = v0x * v0x + v0y * v0y;
    let dot01 = v0x * v1x + v0y * v1y;
    let dot02 = v0x * v2x + v0y * v2y;
    let dot11 = v1x * v1x + v1y * v1y;
    let dot12 = v1x * v2x + v1y * v2y;

    let inv_denom = 1.0 / (dot00 * dot11 - dot01 * dot01).max(1e-9);
    let u = (dot11 * dot02 - dot01 * dot12) * inv_denom;
    let v = (dot00 * dot12 - dot01 * dot02) * inv_denom;
    // 严格内部:边界上的共线点不应阻止剪耳(否则直角/网格类轮廓频繁
    // 找不到 ear → 退化到错误的 fan 兜底)。
    const EPS: f32 = 1e-6;
    u > EPS && v > EPS && (u + v) < 1.0 - EPS
}

/// 简单扇形三角化(凸多边形,或 earcut 失败时的兜底)
fn fan_triangulation(points: &[(f32, f32)]) -> Vec<u32> {
    let mut result = Vec::new();
    if points.len() < 3 {
        return result;
    }
    let base = points[0];
    // 尝试从 base 扇形切
    for i in 2..points.len() {
        // 检查三角形 base,0,i 是否包含其他点
        let mut ok = true;
        for j in 1..points.len() {
            if j == i || j == 0 {
                continue;
            }
            if point_in_triangle(
                points[j].0,
                points[j].1,
                base.0,
                base.1,
                points[1].0,
                points[1].1,
                points[i].0,
                points[i].1,
            ) {
                ok = false;
                break;
            }
        }
        if ok {
            result.push(0u32);
            result.push(1u32);
            result.push(i as u32);
        }
    }
    // 如果 fan 结果太少(凹多边形),用一个中间点做退化分割
    if result.len() < 3 && points.len() >= 3 {
        let n = points.len() as u32;
        for i in 1..n - 1 {
            result.push(0);
            result.push(i);
            result.push(i + 1);
        }
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Color;

    #[test]
    fn path_builder_triangulates_square() {
        let mut pb = PathBuilder::new();
        pb.move_to(0.0, 0.0);
        pb.line_to(100.0, 0.0);
        pb.line_to(100.0, 100.0);
        pb.line_to(0.0, 100.0);
        pb.close();
        let mut list = PaintList::new();
        pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
        assert_eq!(list.commands.len(), 1);
        if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
            // 正方形 earcut:4 vertices + 6 indices = 2 triangles(顺序取决于 winding)
            assert_eq!(vertices.len(), 4);
            assert_eq!(indices.len(), 6);
        } else {
            panic!("expected Triangles");
        }
    }

    #[test]
    fn path_builder_quadbezier_flattens() {
        let mut pb = PathBuilder::new();
        pb.move_to(0.0, 50.0);
        pb.quad_to(50.0, 0.0, 100.0, 50.0, 0.5);
        pb.quad_to(50.0, 100.0, 0.0, 50.0, 0.5);
        pb.close();
        let mut list = PaintList::new();
        pb.fill(Color::rgb(0.0, 1.0, 0.0), &mut list);
        assert_eq!(list.commands.len(), 1);
        if let PaintCommand::Triangles { indices, .. } = &list.commands[0] {
            assert!(indices.len() >= 6, "bezier triangulation should produce >= 6 indices, got {}", indices.len());
        }
    }

    #[test]
    fn path_builder_arc_to_produces_points() {
        let mut pb = PathBuilder::new();
        // 1/4 圆弧(从 +X 到 +Y,90 度)
        pb.move_to(100.0, 100.0);
        pb.arc_to(100.0, 100.0, 50.0, 0.0, std::f32::consts::FRAC_PI_2, 16);
        pb.close();
        let mut list = PaintList::new();
        pb.fill(Color::WHITE, &mut list);

        if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
            assert!(vertices.len() >= 4, "arc + close → 至少 4 vertices");
            assert!(indices.len() >= 6, "earcut → 至少 1 triangle(3 indices)");
            // 检查点都在半径 50 附近
            for v in vertices {
                let dx = v.x - 100.0;
                let dy = v.y - 100.0;
                let d = (dx * dx + dy * dy).sqrt();
                assert!((d - 50.0).abs() < 1.0 || d < 1.0, "vertex ({}, {}) should be at r≈50 or center", v.x, v.y);
            }
        }
    }

    #[test]
    fn path_builder_annulus_sector_triangulates() {
        // Circular Progress 的 annulus sector:外弧 + 径向 + 内弧 + close
        let cx = 100.0;
        let cy = 100.0;
        let outer_r = 80.0;
        let inner_r = 60.0;
        let start_a = -std::f32::consts::FRAC_PI_2;
        let end_a = start_a + std::f32::consts::TAU * 0.75; // 270 度
        let segs = 32u32;

        let mut pb = PathBuilder::new();
        pb.move_to(cx + outer_r * start_a.cos(), cy + outer_r * start_a.sin());
        pb.arc_to(cx, cy, outer_r, start_a, end_a, segs);
        pb.line_to(cx + inner_r * end_a.cos(), cy + inner_r * end_a.sin());
        pb.arc_to(cx, cy, inner_r, end_a, start_a, segs);
        pb.close();

        let mut list = PaintList::new();
        pb.fill(Color::rgb(0.2, 0.6, 1.0), &mut list);

        if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
            // 外弧 33 + 径向连线 → 内弧 33 反向 → close → ~68 vertices(earcut 会用其中的)
            assert!(vertices.len() >= 20, "annulus sector should have many vertices, got {}", vertices.len());
            assert!(indices.len() >= 6, "should produce triangles");

            // 点要么在外半径附近,要么在内半径附近(径向连线除外)
            for v in vertices {
                let dx = v.x - cx;
                let dy = v.y - cy;
                let d = (dx * dx + dy * dy).sqrt();
                let on_outer = (d - outer_r).abs() < 1.0;
                let on_inner = (d - inner_r).abs() < 1.0;
                let on_radial = v.y == cy; // 径向连线端点在 y=cy 上(start_a = -PI/2)
                assert!(
                    on_outer || on_inner || on_radial,
                    "vertex ({}, {}) d={} not on inner/outer/radial",
                    v.x,
                    v.y,
                    d
                );
            }
        }
    }

    #[test]
    fn box_shadow_pads_four_sigma_and_shrinks_radius_on_negative_spread() {
        let mut list = PaintList::new();
        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);
        match &list.commands[0] {
            PaintCommand::BoxShadow { rect, radius, blur_radius, .. } => {
                // shape=(11,22,102,52),pad=4×5=20 → 外扩后 (-9,2,142,92)
                assert_eq!(*rect, Rect::new(-9.0, 2.0, 142.0, 92.0));
                assert_eq!(*radius, 9.0, "正 spread 圆角增大");
                assert_eq!(*blur_radius, 5.0);
            }
            other => panic!("expected BoxShadow, got {other:?}"),
        }

        let mut list = PaintList::new();
        list.box_shadow(Rect::new(0.0, 0.0, 100.0, 50.0), Point::ZERO, 0.0, -4.0, Color::BLACK, 10.0);
        match &list.commands[0] {
            PaintCommand::BoxShadow { rect, radius, .. } => {
                assert_eq!(*rect, Rect::new(4.0, 4.0, 92.0, 42.0));
                assert_eq!(*radius, 6.0, "负 spread 圆角应收缩");
            }
            other => panic!("expected BoxShadow, got {other:?}"),
        }
    }

    #[test]
    fn path_builder_empty_nop() {
        let pb = PathBuilder::new();
        let mut list = PaintList::new();
        pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
        assert!(list.is_empty());
    }

    #[test]
    fn earcut_simple_triangle() {
        let pts = vec![(0.0, 0.0), (10.0, 0.0), (5.0, 10.0), (0.0, 0.0)];
        let (points, indices) = earcut(&pts, None);
        // 有效三角形 = 3 indices,方向取决于 winding(不影响渲染)
        assert_eq!(indices.len(), 3);
        let unique: std::collections::HashSet<&u32> = indices.iter().collect();
        assert_eq!(unique.len(), 3); // 三个不同顶点
                                     // 索引必须落在返回点集范围内(防越界回归)
        assert!(indices.iter().all(|&i| (i as usize) < points.len()));
    }

    fn tri_area_sum(points: &[(f32, f32)], indices: &[u32]) -> f32 {
        let mut area = 0.0;
        for t in indices.as_chunks::<3>().0 {
            let (ax, ay) = points[t[0] as usize];
            let (bx, by) = points[t[1] as usize];
            let (cx, cy) = points[t[2] as usize];
            area += ((bx - ax) * (cy - ay) - (cx - ax) * (by - ay)).abs() * 0.5;
        }
        area
    }

    /// 凹多边形:三角化总面积必须等于多边形面积(无重叠/无越界覆盖)
    #[test]
    fn earcut_concave_polygon_area_matches() {
        // L 形(逆时针)
        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)];
        let (points, indices) = earcut(&pts, None);
        assert_eq!(indices.len(), 12, "6 顶点凹多边形 → 4 个三角形");
        assert!(indices.iter().all(|&i| (i as usize) < points.len()));
        let expected = area2(&pts).abs() * 0.5;
        let got = tri_area_sum(&points, &indices);
        assert!((got - expected).abs() < 0.5, "凹多边形面积: expected={expected}, got={got}");
    }

    /// 带洞填充:总面积 = 外轮廓 - 洞(桥接拓扑正确性回归)
    #[test]
    fn earcut_donut_hole_area_subtracted() {
        let outer = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
        let hole = vec![(25.0, 25.0), (75.0, 25.0), (75.0, 75.0), (25.0, 75.0)];
        let mut pts = outer.clone();
        pts.extend_from_slice(&hole);
        let (points, indices) = earcut(&pts, Some(&[outer.len()]));
        assert!(!indices.is_empty());
        assert!(indices.iter().all(|&i| (i as usize) < points.len()), "索引不得越界");
        let got = tri_area_sum(&points, &indices);
        let expected = 100.0 * 100.0 - 50.0 * 50.0;
        assert!((got - expected).abs() < 1.0, "带洞面积: expected={expected}, got={got}");
    }

    /// 回归:含洞(多回路)的 fill 索引不得越界。
    /// 修复前 earcut 索引指向桥接后的 merged 点集,而 fill 用 flat 建 vertices,
    /// 最后一根索引恰好 == flat.len() → CPU 光栅化 panic。
    #[test]
    fn fill_multi_contour_indices_in_range() {
        let mut pb = PathBuilder::new();
        // 外轮廓(正方形)
        pb.move_to(0.0, 0.0);
        pb.line_to(100.0, 0.0);
        pb.line_to(100.0, 100.0);
        pb.line_to(0.0, 100.0);
        pb.close();
        // 洞(内部小三角)
        pb.move_to(40.0, 40.0);
        pb.line_to(60.0, 40.0);
        pb.line_to(50.0, 60.0);
        pb.close();
        let mut list = PaintList::new();
        pb.fill(Color::rgb(1.0, 0.0, 0.0), &mut list);
        assert_eq!(list.commands.len(), 1);
        if let PaintCommand::Triangles { vertices, indices } = &list.commands[0] {
            assert!(
                indices.iter().all(|&i| (i as usize) < vertices.len()),
                "索引 {} 越界(vertices.len={})",
                indices.iter().max().unwrap(),
                vertices.len()
            );
        } else {
            panic!("expected Triangles");
        }
    }
}