mgui-software 1.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
//! 像素黄金测试:CI 无需 GPU,锁死五类曾漏网的渲染问题。
//!
//! 1. sRGB 颜色值(主题 hex / 0..1 分数直写)
//! 2. BoxShadow 边缘 alpha(高斯衰减,无硬边)
//! 3. 圆角四角裁切
//! 4. rect 覆盖文字的 z-order
//! 5. 滚动容器内 PushClip + PushClipPath(含 layer offset)

use mgui_components::CustomPaint;
use mgui_core::paint::{PaintCommand, Vertex};
use mgui_core::painter::Painter;
use mgui_core::widget::Widget;
use mgui_core::{Color, FramePaint, LayerEffect, LayerId, LayerPaint, PaintList, Point, Rect, Size};
use mgui_software::{render_paint_list, RgbaImage, SoftwareRenderer};
use slotmap::KeyData;

fn layer_id(n: u64) -> LayerId {
    LayerId::from(KeyData::from_ffi(n))
}

fn render(w: u32, h: u32, build: impl FnOnce(&mut PaintList)) -> RgbaImage {
    let mut list = PaintList::new();
    build(&mut list);
    render_paint_list(&list, Size::new(w as f32, h as f32), 1.0)
}

#[test]
fn srgb_color_values_are_exact() {
    // 0.5/0.25/0.75 sRGB 分数 → 128/64/191;目标非 sRGB(与 GPU 一致,直写)
    let img = render(80, 80, |list| {
        list.rect(Rect::new(0.0, 0.0, 64.0, 64.0), Color::rgba(0.5, 0.25, 0.75, 1.0));
    });
    assert_eq!(img.pixel(32, 32), [128, 64, 191, 255], "实心 rect 必须逐字节等于 sRGB 输入");
    assert_eq!(img.pixel(70, 70), [0, 0, 0, 0], "rect 外必须是透明背景");

    // 半透明:straight RGBA 输出保留颜色与 alpha(预乘在内部完成)
    let img = render(40, 40, |list| {
        list.rect(Rect::new(0.0, 0.0, 40.0, 40.0), Color::rgba(0.5, 0.25, 0.75, 0.5));
    });
    assert_eq!(img.pixel(20, 20), [128, 64, 191, 128], "半透明色必须按 straight alpha 输出");
}

#[test]
fn shadow_edge_has_soft_alpha_falloff() {
    let img = render(120, 120, |list| {
        list.box_shadow(Rect::new(30.0, 30.0, 40.0, 40.0), Point::ZERO, 8.0, 0.0, Color::rgba(0.0, 0.0, 0.0, 1.0), 0.0);
    });

    let center = img.pixel(50, 50)[3];
    assert_eq!(center, 255, "shape 内部 shadow 完全不透明");

    // 沿 +x 采样:alpha 必须单调衰减,既有中间值也不会在边界硬切
    let samples: Vec<u8> = [72, 76, 80, 84, 88, 92, 96].iter().map(|&x| img.pixel(x, 50)[3]).collect();
    assert!(samples[0] > 0 && samples[0] < 255, "边缘应是半透明: {samples:?}");
    assert!(samples.windows(2).all(|w| w[0] >= w[1]), "shadow alpha 必须单调衰减: {samples:?}");
    assert!(samples.last().copied().unwrap() < 24, "远端应接近透明: {samples:?}");
    assert!(samples[2] > samples[5], "中间区域要有可见渐变: {samples:?}");
}

#[test]
fn rounded_rect_clips_all_four_corners() {
    let img = render(100, 100, |list| {
        list.rounded_rect(Rect::new(10.0, 10.0, 80.0, 80.0), Color::WHITE, 20.0);
    });
    for (x, y) in [(10, 10), (89, 10), (10, 89), (89, 89)] {
        assert_eq!(img.pixel(x, y)[3], 0, "圆角外的角点必须被裁掉 ({x},{y})");
    }
    for (x, y) in [(50, 10), (50, 89), (10, 50), (89, 50), (50, 50)] {
        assert_eq!(img.pixel(x, y)[3], 255, "边中点/中心必须不透明 ({x},{y})");
    }
}

#[test]
fn rounded_clip_cuts_corners_but_keeps_edges() {
    let img = render(64, 64, |list| {
        list.push_clip_rrect(Rect::new(8.0, 8.0, 48.0, 48.0), 20.0);
        list.rect(Rect::new(0.0, 0.0, 64.0, 64.0), Color::WHITE);
        list.pop_clip();
    });
    assert_eq!(img.pixel(32, 32)[3], 255, "圆角内部必须保留");
    assert_eq!(img.pixel(32, 8)[3], 255, "上边中点必须保留");
    assert_eq!(img.pixel(10, 10)[3], 0, "圆角外角必须裁掉");
    assert_eq!(img.pixel(54, 54)[3], 0, "右下圆角外必须裁掉");
}

#[test]
fn texture_mask_scales_alpha_inside_rect_only() {
    use mgui_core::image::ImageData;
    use std::rc::Rc;

    let img = render(32, 32, |list| {
        list.rect(Rect::new(0.0, 0.0, 32.0, 32.0), Color::WHITE);
        list.push_texture(7, Rc::new(ImageData::solid(4, 4, Color::rgba(1.0, 1.0, 1.0, 0.5))));
        list.mask(Rect::new(0.0, 0.0, 16.0, 32.0), 7, [0.0, 0.0, 1.0, 1.0], 1.0);
    });
    let masked = img.pixel(8, 16);
    assert_eq!(&masked[..3], &[255, 255, 255], "mask 只改 alpha,不换色");
    assert!((masked[3] as i32 - 128).abs() <= 2, "mask 区域 alpha 应约为 128: {masked:?}");
    assert_eq!(img.pixel(24, 16)[3], 255, "mask rect 之外保持原 alpha");
}

#[test]
fn blend_modes_multiply_and_add() {
    use mgui_core::paint::BlendMode;

    let img = render(64, 64, |list| {
        list.rect(Rect::new(0.0, 0.0, 32.0, 64.0), Color::rgb(0.0, 0.0, 1.0));
        list.push_blend_mode(BlendMode::Multiply);
        list.rect(Rect::new(0.0, 0.0, 32.0, 64.0), Color::rgb(1.0, 0.0, 0.0));
        list.pop_blend_mode();
        list.rect(Rect::new(32.0, 0.0, 32.0, 64.0), Color::rgb(0.0, 1.0, 0.0));
        list.push_blend_mode(BlendMode::Add);
        list.rect(Rect::new(32.0, 0.0, 32.0, 64.0), Color::rgb(1.0, 0.0, 0.0));
        list.pop_blend_mode();
    });
    assert_eq!(img.pixel(16, 32), [0, 0, 0, 255], "Multiply(红, 蓝) = 黑");
    assert_eq!(img.pixel(48, 32), [255, 255, 0, 255], "Add(红, 绿) = 黄");
}

#[test]
fn inset_shadow_darkens_inner_edges_only() {
    let img = render(64, 64, |list| {
        list.rect(Rect::new(0.0, 0.0, 64.0, 64.0), Color::WHITE);
        list.inset_shadow(Rect::new(8.0, 8.0, 48.0, 48.0), Color::BLACK, 0.0, 4.0);
    });
    assert_eq!(img.pixel(32, 32), [255, 255, 255, 255], "中心应保持白色");
    assert!(img.pixel(10, 32)[0] < 80, "内侧边缘应被压暗: {:?}", img.pixel(10, 32));
    assert!(img.pixel(32, 10)[0] < 80, "上侧内边缘应被压暗: {:?}", img.pixel(32, 10));
    assert_eq!(img.pixel(2, 32), [255, 255, 255, 255], "矩形外不受影响");
}

#[test]
fn backdrop_blur_mixes_adjacent_colors_only_inside_rect() {
    let img = render(64, 64, |list| {
        list.rect(Rect::new(0.0, 0.0, 32.0, 64.0), Color::rgb(1.0, 0.0, 0.0));
        list.rect(Rect::new(32.0, 0.0, 32.0, 64.0), Color::rgb(0.0, 0.0, 1.0));
        list.backdrop_blur(Rect::new(16.0, 16.0, 32.0, 32.0), 0.0, 8.0, Color::TRANSPARENT);
    });
    let center = img.pixel(32, 32);
    assert!(center[0] > 60 && center[2] > 60, "模糊区中心应混合红/蓝: {center:?}");
    assert_eq!(img.pixel(8, 32), [255, 0, 0, 255], "模糊矩形外保持锐利红色");
    assert_eq!(img.pixel(56, 32), [0, 0, 255, 255], "模糊矩形外保持锐利蓝色");
    assert_eq!(img.pixel(32, 8), [0, 0, 255, 255], "垂直方向矩形外保持锐利");
}

#[test]
fn rect_painted_after_text_covers_glyphs() {
    fn text_list() -> PaintList {
        let mut list = PaintList::new();
        list.text("Hg", 32.0, Color::WHITE, Point::new(10.0, 10.0));
        list
    }

    // 先证明文字确实产生了可见像素(否则遮挡测试没有意义)
    let text_only = render_paint_list(&text_list(), Size::new(120.0, 60.0), 1.0);
    let glyph_pixel = (0..text_only.height)
        .flat_map(|y| (0..text_only.width).map(move |x| (x, y)))
        .find(|&(x, y)| text_only.pixel(x, y)[3] > 200)
        .expect("文字必须有可见 glyph(检查系统字体)");

    // 文字之后画的 rect 必须完整盖住文字(z-order 由命令顺序决定)
    let mut list = text_list();
    list.rect(Rect::new(0.0, 0.0, 120.0, 60.0), Color::rgb(1.0, 0.0, 0.0));
    let covered = render_paint_list(&list, Size::new(120.0, 60.0), 1.0);
    assert_eq!(
        covered.pixel(glyph_pixel.0, glyph_pixel.1),
        [255, 0, 0, 255],
        "后画的 rect 必须盖住先画的文字(不能按类型重排)"
    );
}

#[test]
fn path_clip_inside_scrolled_layer() {
    // 模拟滚动容器:layer offset=(20,15),内部先裁 viewport 再裁三角形路径
    let mut list = PaintList::new();
    list.push_clip(Rect::new(5.0, 5.0, 50.0, 50.0));
    let tri = vec![
        Vertex { x: 10.0, y: 10.0, color: Color::WHITE },
        Vertex { x: 50.0, y: 10.0, color: Color::WHITE },
        Vertex { x: 30.0, y: 50.0, color: Color::WHITE },
    ];
    list.push(PaintCommand::PushClipPath { vertices: tri, indices: vec![0, 1, 2] });
    list.rect(Rect::new(0.0, 0.0, 60.0, 60.0), Color::rgb(1.0, 0.0, 0.0));
    list.push(PaintCommand::PopClipPath);
    list.pop_clip();

    let frame = FramePaint {
        sub_layers: vec![LayerPaint {
            layer_id: layer_id(1),
            paint_list: std::rc::Rc::new(list),
            is_dirty: true,
            parent: None,
            offset: Point::new(20.0, 15.0),
            logical_size: Some(Size::new(60.0, 60.0)),
            effect: LayerEffect::None,
        }],
    };
    let img = SoftwareRenderer::new().render(&frame, Size::new(100.0, 100.0), 1.0);

    // 三角形内部(层内 (30,30) → surface (50,45))
    assert_eq!(img.pixel(50, 45), [255, 0, 0, 255], "路径内 + viewport 内必须可见");
    // viewport 内、三角形外(层内 (12,45) → surface (32,60))
    assert_eq!(img.pixel(32, 60)[3], 0, "view 内但路径外必须被裁掉");
    // layer 外(与 offset 无关的区域)
    assert_eq!(img.pixel(10, 10)[3], 0, "layer offset 之外必须透明");
}

#[test]
fn layers_composite_by_offset_opacity_and_z_order() {
    let mut bottom = PaintList::new();
    bottom.rect(Rect::new(0.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0));
    let mut top = PaintList::new();
    top.rect(Rect::new(0.0, 0.0, 50.0, 50.0), Color::rgb(1.0, 0.0, 0.0));

    let frame = FramePaint {
        sub_layers: vec![
            LayerPaint {
                layer_id: layer_id(1),
                paint_list: std::rc::Rc::new(bottom),
                is_dirty: true,
                parent: None,
                offset: Point::ZERO,
                logical_size: Some(Size::new(100.0, 100.0)),
                effect: LayerEffect::None,
            },
            LayerPaint {
                layer_id: layer_id(2),
                paint_list: std::rc::Rc::new(top),
                is_dirty: true,
                parent: None,
                offset: Point::new(10.0, 10.0),
                logical_size: Some(Size::new(50.0, 50.0)),
                effect: LayerEffect::Opacity(0.5),
            },
        ],
    };
    let img = SoftwareRenderer::new().render(&frame, Size::new(120.0, 120.0), 1.0);
    assert_eq!(img.pixel(5, 5), [0, 0, 255, 255], "底层蓝色");
    // 0.5 红覆盖蓝 → 约 (128,0,128)
    let c = img.pixel(20, 20);
    assert!(c[0] >= 126 && c[0] <= 130 && c[2] >= 126 && c[2] <= 130, "半透明红盖蓝得紫色: {c:?}");
    assert_eq!(img.pixel(65, 65), [0, 0, 255, 255], "上层只覆盖 offset 后的 50×50 区域");
}

#[test]
fn image_texture_maps_uv_and_scale() {
    use mgui_core::image::ImageData;
    use mgui_core::paint::TextureMode;
    use std::rc::Rc;

    // 2×2 四色图:红/绿/蓝/黄
    let data = ImageData::new(vec![255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255], 2, 2);
    let mut list = PaintList::new();
    list.push_texture(7, Rc::new(data));
    list.push(PaintCommand::TexturedRect {
        rect: Rect::new(0.0, 0.0, 40.0, 40.0),
        color: Color::WHITE,
        uv: [0.0, 0.0, 1.0, 1.0],
        texture_id: 7,
        mode: TextureMode::Color,
    });
    let img = render_paint_list(&list, Size::new(40.0, 40.0), 1.0);
    // GPU sampler 为 Linear,象限中心会与邻色插值 → 断言主导通道
    let red = img.pixel(10, 10);
    assert!(red[0] > 200 && red[1] < 60 && red[2] < 60, "左上象限 = 红: {red:?}");
    let green = img.pixel(30, 10);
    assert!(green[1] > 200 && green[0] < 60 && green[2] < 60, "右上象限 = 绿: {green:?}");
    let blue = img.pixel(10, 30);
    assert!(blue[2] > 200 && blue[0] < 60 && blue[1] < 60, "左下象限 = 蓝: {blue:?}");
    let yellow = img.pixel(30, 30);
    assert!(yellow[0] > 200 && yellow[1] > 200 && yellow[2] < 60, "右下象限 = 黄: {yellow:?}");
}

#[test]
fn dpr_scales_physical_output() {
    let mut list = PaintList::new();
    list.rect(Rect::new(2.0, 2.0, 6.0, 6.0), Color::rgb(0.0, 1.0, 0.0));
    let img = render_paint_list(&list, Size::new(20.0, 20.0), 2.0);
    assert_eq!((img.width, img.height), (40, 40), "物理尺寸 = 逻辑 × dpr");
    assert_eq!(img.pixel(8, 8), [0, 255, 0, 255], "rect 内部");
    assert_eq!(img.pixel(2, 2)[3], 0, "rect 外");
}

#[test]
fn layer_clip_rrect_cuts_corners() {
    use mgui_core::RRectDef;

    let mut list = PaintList::new();
    list.rect(Rect::new(0.0, 0.0, 80.0, 80.0), Color::rgb(1.0, 0.0, 0.0));
    let frame = FramePaint {
        sub_layers: vec![LayerPaint {
            layer_id: layer_id(3),
            paint_list: std::rc::Rc::new(list),
            is_dirty: true,
            parent: None,
            offset: Point::new(10.0, 10.0),
            logical_size: Some(Size::new(80.0, 80.0)),
            effect: LayerEffect::ClipRRect(RRectDef { radius: 20.0 }),
        }],
    };
    let img = SoftwareRenderer::new().render(&frame, Size::new(100.0, 100.0), 1.0);
    for (x, y) in [(10, 10), (89, 10), (10, 89), (89, 89)] {
        assert_eq!(img.pixel(x, y)[3], 0, "layer ClipRRect 外角必须被裁掉 ({x},{y})");
    }
    for (x, y) in [(50, 10), (50, 89), (10, 50), (89, 50), (50, 50)] {
        assert_eq!(img.pixel(x, y), [255, 0, 0, 255], "layer 内部必须保留 ({x},{y})");
    }
}

#[test]
fn mask_texture_uses_red_channel_coverage() {
    use mgui_core::image::ImageData;
    use mgui_core::paint::TextureMode;
    use std::rc::Rc;

    // R 通道 = coverage,颜色来自 PaintCommand::color;用 1×1 纹理避免双线性混色
    let draw = |coverage: u8| {
        let data = ImageData::new(vec![coverage, 0, 0, 255], 1, 1);
        let mut list = PaintList::new();
        list.push_texture(9, Rc::new(data));
        list.push(PaintCommand::TexturedRect {
            rect: Rect::new(0.0, 0.0, 40.0, 40.0),
            color: Color::WHITE,
            uv: [0.0, 0.0, 1.0, 1.0],
            texture_id: 9,
            mode: TextureMode::Mask,
        });
        render_paint_list(&list, Size::new(40.0, 40.0), 1.0)
    };
    assert_eq!(draw(255).pixel(20, 20), [255, 255, 255, 255], "R=255 按 color 着色");
    assert_eq!(draw(0).pixel(20, 20)[3], 0, "R=0 完全透明");
}

#[test]
fn triangle_mesh_fills_path() {
    let mut list = PaintList::new();
    list.push(PaintCommand::Triangles {
        vertices: vec![
            Vertex { x: 10.0, y: 10.0, color: Color::rgb(0.0, 1.0, 0.0) },
            Vertex { x: 90.0, y: 10.0, color: Color::rgb(0.0, 1.0, 0.0) },
            Vertex { x: 50.0, y: 90.0, color: Color::rgb(0.0, 1.0, 0.0) },
        ],
        indices: vec![0, 1, 2],
    });
    let img = render_paint_list(&list, Size::new(100.0, 100.0), 1.0);
    assert_eq!(img.pixel(50, 30), [0, 255, 0, 255], "三角形内部");
    assert_eq!(img.pixel(5, 5)[3], 0, "三角形外部");
    assert_eq!(img.pixel(50, 95)[3], 0, "底边之外");
}

#[test]
fn linear_and_radial_gradients_interpolate() {
    let linear = render(100, 20, |list| {
        list.linear_gradient(
            Rect::new(0.0, 0.0, 100.0, 20.0),
            Point::new(0.0, 10.0),
            Point::new(100.0, 10.0),
            Color::rgb(1.0, 0.0, 0.0),
            Color::rgb(0.0, 0.0, 1.0),
            0.0,
        );
    });
    let start = linear.pixel(2, 10);
    assert!(start[0] > 230 && start[2] < 24, "linear 起点应接近 from 色: {start:?}");
    let end = linear.pixel(97, 10);
    assert!(end[2] > 230 && end[0] < 24, "linear 终点应接近 to 色: {end:?}");
    let mid = linear.pixel(50, 10);
    assert!(mid[0] > 80 && mid[2] > 80, "linear 中点应为混合色: {mid:?}");

    let radial = render(100, 100, |list| {
        list.radial_gradient(
            Rect::new(0.0, 0.0, 100.0, 100.0),
            Point::new(50.0, 50.0),
            50.0,
            Color::rgb(1.0, 0.0, 0.0),
            Color::rgb(0.0, 0.0, 1.0),
            0.0,
        );
    });
    let center = radial.pixel(50, 50);
    assert!(center[0] > 230 && center[2] < 24, "radial 中心应接近 from 色: {center:?}");
    let edge = radial.pixel(97, 50);
    assert!(edge[2] > 200 && edge[0] < 36, "radial 边缘应接近 to 色: {edge:?}");
}

#[test]
fn layer_transform_rotates_content() {
    use mgui_core::Transform2D;

    let mut list = PaintList::new();
    list.rect(Rect::new(0.0, 0.0, 40.0, 20.0), Color::rgb(1.0, 0.0, 0.0));
    let frame = FramePaint {
        sub_layers: vec![LayerPaint {
            layer_id: layer_id(4),
            paint_list: std::rc::Rc::new(list),
            is_dirty: true,
            parent: None,
            offset: Point::new(60.0, 10.0),
            logical_size: Some(Size::new(40.0, 20.0)),
            effect: LayerEffect::Transform(Transform2D {
                rotation: std::f32::consts::FRAC_PI_2,
                ..Transform2D::IDENTITY
            }),
        }],
    };
    let img = SoftwareRenderer::new().render(&frame, Size::new(120.0, 60.0), 1.0);
    // 未旋转区域(40×20 @ 60,10)覆盖而旋转后不覆盖的点
    assert_eq!(img.pixel(62, 20)[3], 0, "旋转后左侧空白");
    // 旋转后(20×40 @ 70,0)才覆盖的点
    assert_eq!(img.pixel(80, 35), [255, 0, 0, 255], "旋转后下方应可见");
    assert_eq!(img.pixel(80, 5), [255, 0, 0, 255], "旋转后上方应可见");
    assert_eq!(img.pixel(95, 20)[3], 0, "旋转后右侧空白");
}

/// **动态纹理逐帧替换**(0.4 V-P0-1 的修复契约)。
///
/// 这是视频的地基:`texture_id` 固定不变、每一帧换一份 `ImageData`。
/// 以前的行为是"同 id 再来一次什么都不做"(GPU 端尤其明显),表现成首帧冻结;
/// 当时只能靠"每帧一个新 id"绕开,而那条退路能跑,所以缺陷很容易被当成不存在。
#[test]
fn same_texture_id_new_frame_replaces_pixels() {
    use mgui_core::image::ImageData;
    use mgui_core::paint::TextureMode;
    use std::rc::Rc;

    let mut renderer = SoftwareRenderer::new();
    let paint = |r: &mut SoftwareRenderer, data: &Rc<ImageData>| {
        let mut list = PaintList::new();
        list.push_texture(21, Rc::clone(data));
        list.push(PaintCommand::TexturedRect {
            rect: Rect::new(0.0, 0.0, 20.0, 20.0),
            color: Color::WHITE,
            uv: [0.0, 0.0, 1.0, 1.0],
            texture_id: 21,
            mode: TextureMode::Color,
        });
        r.render_list(&list, Size::new(20.0, 20.0), 1.0)
    };

    let red: Rc<ImageData> = Rc::new(ImageData::new(vec![255, 0, 0, 255], 1, 1));
    assert_eq!(paint(&mut renderer, &red).pixel(10, 10), [255, 0, 0, 255], "第一帧");

    let green: Rc<ImageData> = Rc::new(ImageData::new(vec![0, 255, 0, 255], 1, 1));
    assert_eq!(paint(&mut renderer, &green).pixel(10, 10), [0, 255, 0, 255], "同 id 换源 → 画面必须换");

    // 同一份数据再注册一次:走 Reuse,结果不变(也不能崩/不能变灰)
    assert_eq!(paint(&mut renderer, &green).pixel(10, 10), [0, 255, 0, 255], "同一帧重复声明应保持");

    // 换回另一份新数据:又得更新(证明这不是"只有第二次才生效"的假象)
    let blue: Rc<ImageData> = Rc::new(ImageData::new(vec![0, 0, 255, 255], 1, 1));
    assert_eq!(paint(&mut renderer, &blue).pixel(10, 10), [0, 0, 255, 255], "第三帧仍要替换");
}

/// 带行 padding 的帧:按 `stride` 逐行读,padding 丢掉而不是串到下一行。
#[test]
fn strided_frame_ignores_row_padding() {
    use mgui_core::image::ImageData;
    use mgui_core::paint::TextureMode;
    use std::rc::Rc;

    // 2×2,packed 行 = 8 字节,故意给 stride = 12(每行 4 字节 padding)
    let mut rgba = Vec::new();
    for y in 0..2u8 {
        for x in 0..2u8 {
            rgba.extend_from_slice((if x == 0 { [255u8, 0, 0, 255] } else { [0, 0, 255, 255] }).as_slice());
        }
        rgba.extend_from_slice(&[y * 99, 0, 0, 0]); // padding:不该出现在画面上
    }
    let data = Rc::new(ImageData::with_stride(rgba, 2, 2, 12));

    // 目标尺寸 == 纹理尺寸:采样点正好落在 texel 中心,线性过滤也取到纯色。
    // (第一版在 20×20 目标上取 (5,5),混到了邻 texel —— 那测的是插值不是行距。)
    let img = render(2, 2, |list| {
        list.push_texture(22, Rc::clone(&data));
        list.push(PaintCommand::TexturedRect {
            rect: Rect::new(0.0, 0.0, 2.0, 2.0),
            color: Color::WHITE,
            uv: [0.0, 0.0, 1.0, 1.0],
            texture_id: 22,
            mode: TextureMode::Color,
        });
    });
    assert_eq!(img.pixel(0, 0), [255, 0, 0, 255], "第一行第一个像素");
    assert_eq!(img.pixel(1, 0), [0, 0, 255, 255], "第一行第二个像素");
    // 关键判别:若按 packed(8 字节/行) 读,第二行起点会落到第 0 行的 padding 上,
    // 读出来是透明黑 —— 这两条断言专门盯"行距有没有被尊重"。
    assert_eq!(img.pixel(0, 1), [255, 0, 0, 255], "第二行起点按 stride=12 算,不是 8");
    assert_eq!(img.pixel(1, 1), [0, 0, 255, 255], "第二行第二个像素");
}

/// 把 CustomPaint widget 的受限门面输出接到软件光栅,验证「闭包局部坐标 → 像素」全链路。
fn render_custom_paint(size: Size, painter: impl for<'a> Fn(&mut Painter<'a>) + 'static) -> RgbaImage {
    let widget = CustomPaint::new(size).paint(painter);
    let ro = widget.create_render_object();
    let mut list = PaintList::new();
    ro.paint(Point::ZERO, &mut list);
    render_paint_list(&list, size, 1.0)
}

#[test]
fn custom_paint_geometry_pixels_match_local_coordinates() {
    let img = render_custom_paint(Size::new(64.0, 64.0), |p| {
        let b = p.bounds();
        p.rect(Rect::new(4.0, 4.0, b.width - 8.0, b.height - 8.0), Color::rgb(1.0, 0.0, 0.0));
        p.rounded_rect(Rect::new(16.0, 16.0, 32.0, 32.0), Color::WHITE, 8.0);
        p.triangles(
            vec![
                Vertex { x: 40.0, y: 44.0, color: Color::rgb(0.0, 0.0, 1.0) },
                Vertex { x: 56.0, y: 44.0, color: Color::rgb(0.0, 0.0, 1.0) },
                Vertex { x: 48.0, y: 56.0, color: Color::rgb(0.0, 0.0, 1.0) },
            ],
            vec![0, 1, 2],
        );
    });
    // rect 内、rounded_rect 与三角形之外 → 红
    assert_eq!(img.pixel(8, 8), [255, 0, 0, 255]);
    // 圆角矩形中心 → 白(覆盖红)
    assert_eq!(img.pixel(32, 32), [255, 255, 255, 255]);
    // 圆角外角保持红,不会被圆角矩形误覆盖
    assert_eq!(img.pixel(17, 17), [255, 0, 0, 255]);
    // 三角形内部 → 蓝
    assert_eq!(img.pixel(48, 48), [0, 0, 255, 255]);
    // widget 边界外透明
    assert_eq!(img.pixel(63, 63)[3], 0);
}

#[test]
fn custom_paint_unbalanced_clip_is_closed_in_pixels() {
    let img = render_custom_paint(Size::new(48.0, 48.0), |p| {
        p.push_clip(Rect::new(8.0, 8.0, 16.0, 16.0));
        p.rect(Rect::new(0.0, 0.0, 48.0, 48.0), Color::WHITE);
        // 故意不 pop_clip;门面必须在闭包返回后补齐
    });
    assert_eq!(img.pixel(16, 16), [255, 255, 255, 255], "clip 内保留");
    assert_eq!(img.pixel(30, 16)[3], 0, "clip 外必须裁掉");
}

#[test]
fn custom_paint_panicking_closure_leaves_pixels_untouched() {
    let widget = CustomPaint::new(Size::new(32.0, 32.0)).paint(|p| {
        p.rect(Rect::new(0.0, 0.0, 32.0, 32.0), Color::WHITE);
        panic!("custom paint failure in golden");
    });
    let ro = widget.create_render_object();
    let mut list = PaintList::new();
    // 已有命令不属于本次闭包,必须保留
    list.rect(Rect::new(0.0, 0.0, 32.0, 32.0), Color::rgb(0.0, 0.0, 1.0));
    ro.paint(Point::ZERO, &mut list);
    let img = render_paint_list(&list, Size::new(32.0, 32.0), 1.0);
    assert_eq!(img.pixel(16, 16), [0, 0, 255, 255], "panic 回滚后只剩闭包前的蓝底");
}

// =============================================================================
// 文字像素黄金:仓库内 OFL 字体夹具 + 禁用系统字体,跨机器确定性。
// =============================================================================

/// 用夹具字体渲染文字,返回像素与字形可见像素数。
fn render_fixture_text() -> (RgbaImage, usize) {
    use mgui_text::reset_font_collection_without_system_fonts;
    use mgui_text::runtime::{with_text_runtime, TextRuntime};

    let runtime = TextRuntime::new();
    // 先切到无系统字体的确定性集合,再注册仓库内 OFL 字体。
    reset_font_collection_without_system_fonts();
    let id = runtime
        .register_font(include_bytes!("../../mgui-text/assets/fixtures/Cantarell-Regular.ttf"))
        .expect("OFL 夹具字体应可注册");
    runtime.set_font_stack(id.family());
    let img = with_text_runtime(&runtime, || {
        let mut list = PaintList::new();
        list.text("Hg", 32.0, Color::WHITE, Point::new(4.0, 4.0));
        render_paint_list(&list, Size::new(120.0, 60.0), 1.0)
    });
    let visible = (0..img.height)
        .flat_map(|y| (0..img.width).map(move |x| (x, y)))
        .filter(|&(x, y)| img.pixel(x, y)[3] > 128)
        .count();
    (img, visible)
}

#[test]
fn fixture_font_text_golden_is_deterministic() {
    let (img, visible) = render_fixture_text();
    assert!(visible > 40, "夹具字体应产生可见 glyph,实际可见像素 {visible}");
    // 颜色来自 PaintCommand::color,字形 coverage 走 mask;逐字节锁定 sRGB 与 alpha。
    let first = (0..img.height)
        .flat_map(|y| (0..img.width).map(move |x| (x, y)))
        .find(|&(x, y)| img.pixel(x, y)[3] > 240)
        .expect("应存在不透明字形像素");
    assert_eq!(img.pixel(first.0, first.1), [255, 255, 255, 255]);
    // 同一进程内重复渲染必须逐字节一致:禁用系统字体后 shaping/栅格不再受机器字体影响。
    let (again, visible_again) = render_fixture_text();
    assert_eq!(visible, visible_again, "同夹具同参数的字形覆盖像素数必须一致");
    assert_eq!(img.data, again.data, "同夹具同参数必须逐字节一致");
}