mgui-software 0.1.0

CPU 软件光栅器:消费 PaintList/FramePaint,用于像素黄金测试与无 GPU 回退
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
//! PaintList → 像素:形状/文字/图片/阴影/裁剪。
//!
//! 所有命令坐标是 layer 本地逻辑像素。Raster 持有目标 Pixmap(物理像素),
//! 绘制时统一套 `Transform::from_scale(dpr)`;文字/纹理源图已按 dpr 栅格化。

use std::collections::HashMap;
use std::rc::Rc;

use mgui_core::image::ImageData;
use mgui_core::paint::{BlendMode as CoreBlendMode, PaintCommand, TextureMode, Vertex};
use mgui_core::{Color, PaintList, Rect};
use tiny_skia::{
    BlendMode, FillRule, FilterQuality, GradientStop, LinearGradient, Mask, Paint, PathBuilder, Pattern, Pixmap,
    PixmapPaint, PremultipliedColorU8, RadialGradient, SpreadMode, Transform,
};

use crate::layers::{rounded_rect_path, to_skia_rect};

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct GlyphCacheKey {
    pub generation: u64,
    pub uv: [u32; 4],
    pub color: [u32; 4],
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct ImageTintKey {
    pub texture_id: u32,
    pub color: [u32; 4],
    /// true = Mask(R 通道为 coverage,用于 SVG tint/icon);false = Color
    pub mask: bool,
}

enum ClipEntry {
    Rect(Rect),
    Path(tiny_skia::Path),
}

pub(crate) struct Raster<'a> {
    pub target: &'a mut Pixmap,
    pub dpr: f32,
    clips: Vec<ClipEntry>,
    mask: Option<Mask>,
    pub textures: &'a HashMap<u32, (Rc<ImageData>, Pixmap)>,
    pub glyph_cache: &'a mut HashMap<GlyphCacheKey, Pixmap>,
    pub tint_cache: &'a mut HashMap<ImageTintKey, Pixmap>,
    pub atlas_generation: u64,
    /// 当前矩形族混合模式
    blend: CoreBlendMode,
    blend_stack: Vec<CoreBlendMode>,
}

impl<'a> Raster<'a> {
    pub fn new(
        target: &'a mut Pixmap,
        dpr: f32,
        textures: &'a HashMap<u32, (Rc<ImageData>, Pixmap)>,
        glyph_cache: &'a mut HashMap<GlyphCacheKey, Pixmap>,
        tint_cache: &'a mut HashMap<ImageTintKey, Pixmap>,
        atlas_generation: u64,
    ) -> Self {
        Self {
            target,
            dpr,
            clips: Vec::new(),
            mask: None,
            textures,
            glyph_cache,
            tint_cache,
            atlas_generation,
            blend: CoreBlendMode::Normal,
            blend_stack: Vec::new(),
        }
    }

    pub fn run(&mut self, list: &PaintList) {
        for cmd in &list.commands {
            self.draw(cmd);
        }
    }

    fn draw(&mut self, cmd: &PaintCommand) {
        match cmd {
            PaintCommand::PushBlendMode(mode) => {
                self.blend_stack.push(self.blend);
                self.blend = *mode;
            }
            PaintCommand::PopBlendMode => {
                self.blend = self.blend_stack.pop().unwrap_or(CoreBlendMode::Normal);
            }
            PaintCommand::Rect { rect, color, radius } => self.fill_rounded_rect(*rect, *color, *radius),
            PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
                self.fill_box_shadow(*rect, *color, *radius, *blur_radius)
            }
            PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
                self.fill_inset_shadow(*rect, *color, *radius, *blur_radius)
            }
            PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
                self.fill_backdrop_blur(*rect, *radius, *blur_radius, *tint)
            }
            PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
                let stops = vec![GradientStop::new(0.0, sk_color(*from)), GradientStop::new(1.0, sk_color(*to))];
                if let Some(shader) = LinearGradient::new(
                    tiny_skia::Point::from_xy(start.x, start.y),
                    tiny_skia::Point::from_xy(end.x, end.y),
                    stops,
                    SpreadMode::Pad,
                    Transform::identity(),
                ) {
                    self.fill_rounded_rect_shader(*rect, *corner_radius, shader);
                }
            }
            PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
                let stops = vec![GradientStop::new(0.0, sk_color(*from)), GradientStop::new(1.0, sk_color(*to))];
                let c = tiny_skia::Point::from_xy(center.x, center.y);
                if let Some(shader) =
                    RadialGradient::new(c, c, radial_radius.max(0.001), stops, SpreadMode::Pad, Transform::identity())
                {
                    self.fill_rounded_rect_shader(*rect, *corner_radius, shader);
                }
            }
            PaintCommand::Triangles { vertices, indices } => self.fill_triangles(vertices, indices),
            PaintCommand::PushClip(rect) => {
                self.clips.push(ClipEntry::Rect(*rect));
                self.rebuild_mask();
            }
            PaintCommand::PopClip | PaintCommand::PopClipPath => {
                self.clips.pop();
                self.rebuild_mask();
            }
            PaintCommand::PushClipRRect { rect, radius } => {
                match rounded_rect_path(*rect, *radius) {
                    Some(path) => self.clips.push(ClipEntry::Path(path)),
                    None => self.clips.push(ClipEntry::Rect(Rect::new(0.0, 0.0, 0.0, 0.0))),
                }
                self.rebuild_mask();
            }
            PaintCommand::PushClipPath { vertices, indices } => {
                match triangles_path(vertices, indices) {
                    Some(path) => self.clips.push(ClipEntry::Path(path)),
                    None => self.clips.push(ClipEntry::Rect(Rect::new(0.0, 0.0, 0.0, 0.0))),
                }
                self.rebuild_mask();
            }
            // **P2-1.3:纹理 mask** — destination-in,只保留纹理 alpha 覆盖的区域
            PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
                self.fill_alpha_mask(*rect, *texture_id, *uv, *alpha)
            }
            PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
                self.fill_textured(*rect, *color, *uv, *texture_id, *mode)
            }
            // 高层文字命令:与 GPU 一样先展开成 glyph TexturedRect,再走同一光栅化路径
            PaintCommand::Text { text, range, font_size, color, position, max_width } => {
                let mut expanded = PaintList::new();
                mgui_text::text::paint_text_span(
                    text,
                    *range,
                    *font_size,
                    *color,
                    *position,
                    &mut expanded,
                    *max_width,
                );
                for c in &expanded.commands {
                    self.draw(c);
                }
            }
        }
    }

    fn rebuild_mask(&mut self) {
        if self.clips.is_empty() {
            self.mask = None;
            return;
        }
        let (w, h) = (self.target.width(), self.target.height());
        let Some(mut mask) = Mask::new(w, h) else {
            self.mask = None;
            return;
        };
        mask.data_mut().fill(255);
        let transform = Transform::from_scale(self.dpr, self.dpr);
        for entry in &self.clips {
            match entry {
                ClipEntry::Rect(rect) => {
                    let Some(r) = to_skia_rect(*rect) else {
                        mask.data_mut().fill(0);
                        continue;
                    };
                    let path = PathBuilder::from_rect(r);
                    mask.intersect_path(&path, FillRule::Winding, false, transform);
                }
                ClipEntry::Path(path) => {
                    mask.intersect_path(path, FillRule::Winding, true, transform);
                }
            }
        }
        self.mask = Some(mask);
    }

    fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
        if rect.width <= 0.0 || rect.height <= 0.0 {
            return;
        }
        let mut paint = Paint::default();
        paint.set_color_rgba8(enc(color.r), enc(color.g), enc(color.b), enc(color.a));
        paint.anti_alias = true;
        paint.blend_mode = self.sk_blend();
        self.fill_rounded_rect_with(rect, radius, &paint);
    }

    fn fill_rounded_rect_shader(&mut self, rect: Rect, radius: f32, shader: tiny_skia::Shader) {
        if rect.width <= 0.0 || rect.height <= 0.0 {
            return;
        }
        let paint = Paint { shader, blend_mode: self.sk_blend(), anti_alias: true, ..Default::default() };
        self.fill_rounded_rect_with(rect, radius, &paint);
    }

    fn sk_blend(&self) -> BlendMode {
        match self.blend {
            CoreBlendMode::Normal => BlendMode::SourceOver,
            CoreBlendMode::Multiply => BlendMode::Multiply,
            CoreBlendMode::Screen => BlendMode::Screen,
            CoreBlendMode::Add => BlendMode::Plus,
        }
    }

    fn fill_rounded_rect_with(&mut self, rect: Rect, radius: f32, paint: &Paint) {
        let transform = Transform::from_scale(self.dpr, self.dpr);
        let Raster { target, mask, .. } = self;
        if radius <= 0.0 {
            if let Some(r) = to_skia_rect(rect) {
                target.fill_rect(r, paint, transform, mask.as_ref());
            }
        } else if let Some(path) = rounded_rect_path(rect, radius) {
            target.fill_path(&path, paint, FillRule::Winding, transform, mask.as_ref());
        }
    }

    /// GPU SDF shadow 的逐像素复刻:`box_shadow` 的 rect 已按 4×blur 外扩,
    /// shape 中心 = rect 中心;blur>0 用 exp 衰减,blur=0 用 1px smoothstep。
    fn fill_box_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur: f32) {
        if rect.width <= 0.0 || rect.height <= 0.0 || color.a <= 0.0 {
            return;
        }
        let dpr = self.dpr;
        let (x0, y0, x1, y1) = shadow_pixel_bounds(rect, dpr, self.target.width(), self.target.height());
        if x1 <= x0 || y1 <= y0 {
            return;
        }
        let (pw, ph) = (x1 - x0, y1 - y0);
        let Some(mut shadow) = Pixmap::new(pw, ph) else { return };
        let half = (rect.width * 0.5, rect.height * 0.5);
        let pad = blur.max(0.0) * 4.0;
        let shape_half = ((half.0 - pad).max(0.0), (half.1 - pad).max(0.0));
        let r = radius.max(0.0).min(shape_half.0.min(shape_half.1));
        let data = shadow.data_mut();
        for py in 0..ph {
            for px in 0..pw {
                let lx = (x0 + px) as f32 + 0.5;
                let ly = (y0 + py) as f32 + 0.5;
                // 物理像素中心 → 逻辑坐标(相对 padded rect 左上)
                let lx = lx / dpr - rect.x;
                let ly = ly / dpr - rect.y;
                let p = (lx - half.0, ly - half.1);
                let q = (p.0.abs() - shape_half.0 + r, p.1.abs() - shape_half.1 + r);
                let outside = (q.0.max(0.0).powi(2) + q.1.max(0.0).powi(2)).sqrt();
                let d = q.0.max(q.1).min(0.0) + outside - r;
                let coverage = if blur > 0.0 {
                    let dp = d.max(0.0);
                    (-(dp * dp) / (2.0 * blur * blur)).exp()
                } else {
                    1.0 - smoothstep(-0.5, 0.5, d)
                };
                let alpha = (color.a * coverage).clamp(0.0, 1.0);
                if alpha <= 0.001 {
                    continue;
                }
                let a = enc(alpha);
                let cr = enc((color.r * alpha).min(1.0));
                let cg = enc((color.g * alpha).min(1.0));
                let cb = enc((color.b * alpha).min(1.0));
                let i = ((py * pw + px) * 4) as usize;
                data[i..i + 4].copy_from_slice(&[cr.min(a), cg.min(a), cb.min(a), a]);
            }
        }
        let blend = self.sk_blend();
        let Raster { target, mask, .. } = self;
        target.draw_pixmap(
            x0 as i32,
            y0 as i32,
            shadow.as_ref(),
            &PixmapPaint { blend_mode: blend, ..PixmapPaint::default() },
            Transform::identity(),
            mask.as_ref(),
        );
    }

    /// P2-1.4:内阴影(与 rect.wgsl kind=3 像素级对齐)
    fn fill_inset_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur: f32) {
        if rect.width <= 0.0 || rect.height <= 0.0 || color.a <= 0.0 {
            return;
        }
        let dpr = self.dpr;
        let (x0, y0, x1, y1) = shadow_pixel_bounds(rect, dpr, self.target.width(), self.target.height());
        if x1 <= x0 || y1 <= y0 {
            return;
        }
        let (pw, ph) = (x1 - x0, y1 - y0);
        let Some(mut shadow) = Pixmap::new(pw, ph) else { return };
        let half = (rect.width * 0.5, rect.height * 0.5);
        let r = radius.max(0.0).min(half.0.min(half.1));
        let data = shadow.data_mut();
        for py in 0..ph {
            for px in 0..pw {
                let lx = ((x0 + px) as f32 + 0.5) / dpr - rect.x;
                let ly = ((y0 + py) as f32 + 0.5) / dpr - rect.y;
                let p = (lx - half.0, ly - half.1);
                let q = (p.0.abs() - half.0 + r, p.1.abs() - half.1 + r);
                let outside = (q.0.max(0.0).powi(2) + q.1.max(0.0).powi(2)).sqrt();
                let d = q.0.max(q.1).min(0.0) + outside - r;
                let inside = 1.0 - smoothstep(-0.5, 0.5, d);
                if inside <= 0.0 {
                    continue;
                }
                let depth = (-d).max(0.0);
                let coverage = if blur > 0.0 {
                    inside * (-(depth * depth) / (2.0 * blur * blur)).exp()
                } else {
                    inside * (1.0 - smoothstep(0.0, 1.0, depth))
                };
                let alpha = (color.a * coverage).clamp(0.0, 1.0);
                if alpha <= 0.001 {
                    continue;
                }
                let a = enc(alpha);
                let cr = enc((color.r * alpha).min(1.0));
                let cg = enc((color.g * alpha).min(1.0));
                let cb = enc((color.b * alpha).min(1.0));
                let i = ((py * pw + px) * 4) as usize;
                data[i..i + 4].copy_from_slice(&[cr.min(a), cg.min(a), cb.min(a), a]);
            }
        }
        let blend = self.sk_blend();
        let Raster { target, mask, .. } = self;
        target.draw_pixmap(
            x0 as i32,
            y0 as i32,
            shadow.as_ref(),
            &PixmapPaint { blend_mode: blend, ..PixmapPaint::default() },
            Transform::identity(),
            mask.as_ref(),
        );
    }

    /// P2-1.4b:背景模糊(13-tap,与 backdrop.wgsl 同权重)
    fn fill_backdrop_blur(&mut self, rect: Rect, radius: f32, blur: f32, tint: Color) {
        if rect.width <= 0.0 || rect.height <= 0.0 {
            return;
        }
        let dpr = self.dpr;
        let (x0, y0, x1, y1) = shadow_pixel_bounds(rect, dpr, self.target.width(), self.target.height());
        if x1 <= x0 || y1 <= y0 {
            return;
        }
        let (pw, ph) = (x1 - x0, y1 - y0);
        let Some(mut out) = Pixmap::new(pw, ph) else { return };

        // 快照:后续写入不影响采样
        let snap = self.target.data().to_vec();
        let (tw, th) = (self.target.width() as i32, self.target.height() as i32);
        let step = blur.max(0.0) * dpr;
        let half = (rect.width * 0.5, rect.height * 0.5);
        let r = radius.max(0.0).min(half.0.min(half.1));
        let tint_a = tint.a.clamp(0.0, 1.0);

        // (dx, dy, weight)
        let taps: [(f32, f32, f32); 13] = [
            (0.0, 0.0, 0.20),
            (0.5, 0.0, 0.12),
            (-0.5, 0.0, 0.12),
            (0.0, 0.5, 0.12),
            (0.0, -0.5, 0.12),
            (0.35, 0.35, 0.06),
            (-0.35, 0.35, 0.06),
            (0.35, -0.35, 0.06),
            (-0.35, -0.35, 0.06),
            (1.0, 0.0, 0.02),
            (-1.0, 0.0, 0.02),
            (0.0, 1.0, 0.02),
            (0.0, -1.0, 0.02),
        ];

        let data = out.data_mut();
        for py in 0..ph {
            for px in 0..pw {
                let sx = x0 + px;
                let sy = y0 + py;
                let lx = (sx as f32 + 0.5) / dpr - rect.x;
                let ly = (sy as f32 + 0.5) / dpr - rect.y;
                let p = (lx - half.0, ly - half.1);
                let q = (p.0.abs() - half.0 + r, p.1.abs() - half.1 + r);
                let outside = (q.0.max(0.0).powi(2) + q.1.max(0.0).powi(2)).sqrt();
                let d = q.0.max(q.1).min(0.0) + outside - r;
                let mask = 1.0 - smoothstep(-0.5, 0.5, d);
                if mask <= 0.0 {
                    continue;
                }

                let mut acc = [0.0f32; 4];
                for &(dx, dy, w) in &taps {
                    let ox = (sx as f32 + dx * step).round() as i32;
                    let oy = (sy as f32 + dy * step).round() as i32;
                    let ox = ox.clamp(0, tw - 1);
                    let oy = oy.clamp(0, th - 1);
                    let i = ((oy * tw + ox) * 4) as usize;
                    for c in 0..4 {
                        acc[c] += snap[i + c] as f32 * w;
                    }
                }
                let a = (acc[3] / 255.0).clamp(0.0, 1.0);
                let mut rgb = [0.0f32; 3];
                if acc[3] > 0.001 {
                    for c in 0..3 {
                        rgb[c] = acc[c] / acc[3];
                    }
                }
                // tint 混合(straight RGB)
                rgb[0] = rgb[0] * (1.0 - tint_a) + tint.r * tint_a;
                rgb[1] = rgb[1] * (1.0 - tint_a) + tint.g * tint_a;
                rgb[2] = rgb[2] * (1.0 - tint_a) + tint.b * tint_a;

                let alpha = (a * mask).clamp(0.0, 1.0);
                if alpha <= 0.001 {
                    continue;
                }
                let ab = enc(alpha);
                let i = ((py * pw + px) * 4) as usize;
                data[i..i + 4].copy_from_slice(&[
                    enc((rgb[0] * alpha).min(1.0)).min(ab),
                    enc((rgb[1] * alpha).min(1.0)).min(ab),
                    enc((rgb[2] * alpha).min(1.0)).min(ab),
                    ab,
                ]);
            }
        }

        let Raster { target, mask, .. } = self;
        target.draw_pixmap(
            x0 as i32,
            y0 as i32,
            out.as_ref(),
            &PixmapPaint::default(),
            Transform::identity(),
            mask.as_ref(),
        );
    }

    fn fill_triangles(&mut self, vertices: &[Vertex], indices: &[u32]) {
        let Some(path) = triangles_path(vertices, indices) else { return };
        let color = vertices.first().map(|v| v.color).unwrap_or(Color::WHITE);
        let mut paint = Paint::default();
        paint.set_color_rgba8(enc(color.r), enc(color.g), enc(color.b), enc(color.a));
        paint.anti_alias = true;
        let transform = Transform::from_scale(self.dpr, self.dpr);
        let Raster { target, mask, .. } = self;
        target.fill_path(&path, &paint, FillRule::Winding, transform, mask.as_ref());
    }

    fn fill_textured(&mut self, rect: Rect, color: Color, uv: [f32; 4], texture_id: u32, mode: TextureMode) {
        if rect.width <= 0.0 || rect.height <= 0.0 || color.a <= 0.0 {
            return;
        }
        if texture_id == 0 {
            self.fill_glyph(rect, color, uv);
        } else {
            self.fill_image(rect, color, uv, texture_id, mode);
        }
    }

    fn fill_glyph(&mut self, rect: Rect, color: Color, uv: [f32; 4]) {
        let generation = mgui_text::text::atlas_generation();
        if generation != self.atlas_generation {
            self.atlas_generation = generation;
            self.glyph_cache.clear();
        }
        let key = GlyphCacheKey {
            generation,
            uv: uv.map(f32::to_bits),
            color: [color.r.to_bits(), color.g.to_bits(), color.b.to_bits(), color.a.to_bits()],
        };
        if let std::collections::hash_map::Entry::Vacant(entry) = self.glyph_cache.entry(key) {
            let built = mgui_text::text::with_atlas(|aw, ah, data| build_glyph_pixmap(aw, ah, data, uv, color));
            if let Some(pix) = built {
                entry.insert(pix);
            }
        }
        let Raster { target, mask, dpr, glyph_cache, .. } = self;
        if let Some(src) = glyph_cache.get(&key) {
            draw_pixmap_rect(target, src, rect, *dpr, mask.as_ref(), FilterQuality::Bilinear);
        }
    }

    /// 纹理 alpha mask:destination-in,new_alpha = old_alpha × tex.a × alpha
    fn fill_alpha_mask(&mut self, rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32) {
        if rect.width <= 0.0 || rect.height <= 0.0 || alpha <= 0.0 {
            return;
        }
        let Some((_, src)) = self.textures.get(&texture_id) else { return };
        let (x0, y0, x1, y1) = uv_pixels(uv, src.width() as f32, src.height() as f32);
        let (uw, uh) = ((x1 - x0).max(1e-3), (y1 - y0).max(1e-3));
        let sx = rect.width / uw;
        let sy = rect.height / uh;
        let pat = Transform::from_row(sx, 0.0, 0.0, sy, rect.x - x0 * sx, rect.y - y0 * sy);
        let shader = Pattern::new(src.as_ref(), SpreadMode::Pad, FilterQuality::Bilinear, alpha.clamp(0.0, 1.0), pat);
        let paint = Paint { shader, blend_mode: BlendMode::DestinationIn, anti_alias: true, ..Paint::default() };
        let Some(r) = to_skia_rect(rect) else { return };
        let dpr = self.dpr;
        let Raster { target, mask, .. } = self;
        target.fill_rect(r, &paint, Transform::from_scale(dpr, dpr), mask.as_ref());
    }

    fn fill_image(&mut self, rect: Rect, color: Color, uv: [f32; 4], texture_id: u32, mode: TextureMode) {
        if !self.textures.contains_key(&texture_id) {
            return;
        }
        if mode == TextureMode::Mask {
            // SVG tint / icon:GPU 用纹理 R 通道作 coverage,颜色来自命令
            let key = ImageTintKey {
                texture_id,
                color: [color.r.to_bits(), color.g.to_bits(), color.b.to_bits(), color.a.to_bits()],
                mask: true,
            };
            if !self.tint_cache.contains_key(&key) {
                if let Some((data, _)) = self.textures.get(&texture_id) {
                    if let Some(tinted) = mask_tint_pixmap(data, color) {
                        self.tint_cache.insert(key, tinted);
                    }
                }
            }
            let Raster { target, mask, dpr, tint_cache, .. } = self;
            if let Some(src) = tint_cache.get(&key) {
                draw_image_rect(target, src, rect, uv, *dpr, mask.as_ref());
            }
            return;
        }
        let white = color.r >= 1.0 - f32::EPSILON
            && color.g >= 1.0 - f32::EPSILON
            && color.b >= 1.0 - f32::EPSILON
            && color.a >= 1.0 - f32::EPSILON;
        if !white {
            let key = ImageTintKey {
                texture_id,
                color: [color.r.to_bits(), color.g.to_bits(), color.b.to_bits(), color.a.to_bits()],
                mask: false,
            };
            if !self.tint_cache.contains_key(&key) {
                if let Some((_, base)) = self.textures.get(&texture_id) {
                    if let Some(tinted) = tint_pixmap(base, color) {
                        self.tint_cache.insert(key, tinted);
                    }
                }
            }
            let Raster { target, mask, dpr, tint_cache, .. } = self;
            if let Some(src) = tint_cache.get(&key) {
                draw_image_rect(target, src, rect, uv, *dpr, mask.as_ref());
            }
        } else {
            let Raster { target, mask, dpr, textures, .. } = self;
            if let Some((_, src)) = textures.get(&texture_id) {
                draw_image_rect(target, src, rect, uv, *dpr, mask.as_ref());
            }
        }
    }
}

fn draw_pixmap_rect(
    target: &mut Pixmap,
    src: &Pixmap,
    dest: Rect,
    dpr: f32,
    mask: Option<&Mask>,
    quality: FilterQuality,
) {
    if src.width() == 0 || src.height() == 0 {
        return;
    }
    let sx = dest.width / src.width() as f32;
    let sy = dest.height / src.height() as f32;
    let pat = Transform::from_row(sx, 0.0, 0.0, sy, dest.x, dest.y);
    fill_with_pattern(target, src, dest, pat, dpr, mask, quality, 1.0);
}

fn draw_image_rect(target: &mut Pixmap, src: &Pixmap, dest: Rect, uv: [f32; 4], dpr: f32, mask: Option<&Mask>) {
    let sw = src.width() as f32;
    let sh = src.height() as f32;
    let (x0, y0, x1, y1) = uv_pixels(uv, sw, sh);
    let (uw, uh) = ((x1 - x0).max(1e-3), (y1 - y0).max(1e-3));
    let sx = dest.width / uw;
    let sy = dest.height / uh;
    // uv 与 atlas 一致:左上原点归一化;平移把 uv 子区左缘映射到 dest 左缘
    let pat = Transform::from_row(sx, 0.0, 0.0, sy, dest.x - x0 * sx, dest.y - y0 * sy);
    fill_with_pattern(target, src, dest, pat, dpr, mask, FilterQuality::Bilinear, 1.0);
}

#[allow(clippy::too_many_arguments)]
fn fill_with_pattern(
    target: &mut Pixmap,
    src: &Pixmap,
    dest: Rect,
    pattern_transform: Transform,
    dpr: f32,
    mask: Option<&Mask>,
    quality: FilterQuality,
    opacity: f32,
) {
    let shader = Pattern::new(src.as_ref(), SpreadMode::Pad, quality, opacity, pattern_transform);
    let paint = Paint { shader, anti_alias: true, ..Paint::default() };
    let Some(rect) = to_skia_rect(dest) else { return };
    target.fill_rect(rect, &paint, Transform::from_scale(dpr, dpr), mask);
}

/// 从 R8 atlas 裁出 glyph 覆盖区并按 color 预乘上色(左上原点 uv)
fn build_glyph_pixmap(aw: u32, ah: u32, atlas: &[u8], uv: [f32; 4], color: Color) -> Option<Pixmap> {
    let (x0, y0, x1, y1) = uv_pixels(uv, aw as f32, ah as f32);
    let x0 = x0.round() as i64;
    let y0 = y0.round() as i64;
    let x1 = (x1.round() as i64).min(aw as i64).max(x0);
    let y1 = (y1.round() as i64).min(ah as i64).max(y0);
    let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);
    if w == 0 || h == 0 || atlas.len() < (aw * ah) as usize {
        return None;
    }
    let mut pix = Pixmap::new(w, h)?;
    let out = pix.data_mut();
    for y in 0..h {
        for x in 0..w {
            let idx = (y0 as u32 + y) as usize * aw as usize + (x0 as u32 + x) as usize;
            let coverage = atlas[idx] as f32 / 255.0;
            let a = color.a * coverage;
            let pa = enc(a);
            let pr = enc(color.r * a).min(pa);
            let pg = enc(color.g * a).min(pa);
            let pb = enc(color.b * a).min(pa);
            let i = ((y * w + x) * 4) as usize;
            out[i..i + 4].copy_from_slice(&[pr, pg, pb, pa]);
        }
    }
    Some(pix)
}

/// Mask 纹理(SVG tint):coverage = ImageData 的 R 通道(GPU text.wgsl 同语义)
fn mask_tint_pixmap(data: &ImageData, color: Color) -> Option<Pixmap> {
    let (w, h) = (data.width, data.height);
    if w == 0 || h == 0 || data.rgba.len() < (w * h * 4) as usize {
        return None;
    }
    let mut pix = Pixmap::new(w, h)?;
    let out = pix.data_mut();
    for i in 0..(w * h) as usize {
        let coverage = data.rgba[i * 4] as f32 / 255.0;
        let a = color.a * coverage;
        let pa = enc(a);
        let pr = enc(color.r * a).min(pa);
        let pg = enc(color.g * a).min(pa);
        let pb = enc(color.b * a).min(pa);
        out[i * 4..i * 4 + 4].copy_from_slice(&[pr, pg, pb, pa]);
    }
    Some(pix)
}

fn tint_pixmap(base: &Pixmap, color: Color) -> Option<Pixmap> {
    let mut out = Pixmap::new(base.width(), base.height())?;
    for (dst, src) in out.pixels_mut().iter_mut().zip(base.pixels()) {
        let a = (src.alpha() as f32 / 255.0 * color.a).clamp(0.0, 1.0);
        let pa = enc(a);
        let rgb = |v: u8, c: f32| enc((v as f32 / 255.0) * c * color.a).min(pa);
        *dst = PremultipliedColorU8::from_rgba(
            rgb(src.red(), color.r),
            rgb(src.green(), color.g),
            rgb(src.blue(), color.b),
            pa,
        )?;
    }
    Some(out)
}

/// uv → 源图像素坐标(左上原点)
fn uv_pixels(uv: [f32; 4], w: f32, h: f32) -> (f32, f32, f32, f32) {
    (uv[0] * w, uv[1] * h, uv[2] * w, uv[3] * h)
}

fn triangles_path(vertices: &[Vertex], indices: &[u32]) -> Option<tiny_skia::Path> {
    if vertices.is_empty() || indices.len() < 3 {
        return None;
    }
    let mut pb = PathBuilder::new();
    for tri in indices.chunks_exact(3) {
        let (a, b, c) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
        let (Some(a), Some(b), Some(c)) = (vertices.get(a), vertices.get(b), vertices.get(c)) else {
            continue;
        };
        pb.move_to(a.x, a.y);
        pb.line_to(b.x, b.y);
        pb.line_to(c.x, c.y);
        pb.close();
    }
    pb.finish()
}

fn shadow_pixel_bounds(rect: Rect, dpr: f32, w: u32, h: u32) -> (u32, u32, u32, u32) {
    let x0 = ((rect.x * dpr).floor().max(0.0) as u32).min(w);
    let y0 = ((rect.y * dpr).floor().max(0.0) as u32).min(h);
    let x1 = ((rect.right() * dpr).ceil().max(0.0) as u32).min(w);
    let y1 = ((rect.bottom() * dpr).ceil().max(0.0) as u32).min(h);
    (x0, y0, x1.max(x0), y1.max(y0))
}

fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
    let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
    t * t * (3.0 - 2.0 * t)
}

pub(crate) fn enc(v: f32) -> u8 {
    (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
}

fn sk_color(c: Color) -> tiny_skia::Color {
    tiny_skia::Color::from_rgba8(enc(c.r), enc(c.g), enc(c.b), enc(c.a))
}

pub(crate) fn pixmap_to_rgba(pix: &Pixmap) -> Vec<u8> {
    let mut out = Vec::new();
    pixmap_to_rgba_into(pix, &mut out);
    out
}

/// 写入已有 RGBA Vec(保留容量),供 Headless/软件后端跨帧复用输出缓冲。
pub(crate) fn pixmap_to_rgba_into(pix: &Pixmap, out: &mut Vec<u8>) {
    let len = (pix.width() * pix.height() * 4) as usize;
    out.clear();
    out.resize(len, 0);
    for (dst, p) in out.chunks_exact_mut(4).zip(pix.pixels()) {
        let c = p.demultiply();
        dst[0] = c.red();
        dst[1] = c.green();
        dst[2] = c.blue();
        dst[3] = c.alpha();
    }
}

pub(crate) fn image_to_pixmap(data: &ImageData) -> Option<Pixmap> {
    if data.width == 0 || data.height == 0 || data.rgba.len() < (data.width * data.height * 4) as usize {
        return None;
    }
    let mut pix = Pixmap::new(data.width, data.height)?;
    for (dst, src) in pix.pixels_mut().iter_mut().zip(data.rgba.chunks_exact(4)) {
        let c = tiny_skia::ColorU8::from_rgba(src[0], src[1], src[2], src[3]);
        *dst = c.premultiply();
    }
    Some(pix)
}