Skip to main content

mgui_software/
lib.rs

1//! mgui-software — CPU 软件光栅器(与 GPU 共用 `PaintList` 渲染契约)。
2//!
3//! 输入:`FramePaint`(layer 列表 + `PaintList`)或单个 `PaintList`;
4//! 输出:straight RGBA8 像素。用于:
5//! - **像素黄金测试**(CI 无需显卡,断言 sRGB/阴影/圆角/遮挡/裁剪)
6//! - 无 GPU / VM / 远程桌面的软件回退(输出交给 softbuffer 等展示层)
7//!
8//! `present` feature(默认开)提供 softbuffer 上屏;关闭后只保留纯 CPU
9//! 光栅器,不引入 `mgui-runtime` / winit / softbuffer(headless/像素测试用)。
10//!
11//! 与 GPU Renderer 的对应关系:
12//! `Rect`/`BoxShadow`/`Triangles`/`TexturedRect`/`Text`/`PushClip`/
13//! `PushClipPath` 全部按同一 `PaintList` 语义光栅化;文字复用 parley
14//! shaping + swash 栅格化后的 **glyph atlas**(与 GPU 同一缓存)。
15
16#![forbid(unsafe_code)]
17
18mod layers;
19#[cfg(feature = "present")]
20mod present;
21mod raster;
22
23#[cfg(feature = "present")]
24pub use present::{rgba_to_xrgb, xrgb, SoftwarePresenter};
25
26use std::collections::HashMap;
27use std::rc::Rc;
28
29use mgui_core::composition::CompositionScratch;
30use mgui_core::image::ImageData;
31use mgui_core::{FramePaint, LayerId, PaintList, Size};
32use tiny_skia::Pixmap;
33
34use raster::{GlyphCacheKey, ImageTintKey};
35
36/// 一帧的 straight RGBA8 输出(左上原点,每像素 4 字节)
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct RgbaImage {
39    pub width: u32,
40    pub height: u32,
41    pub data: Vec<u8>,
42}
43
44impl RgbaImage {
45    /// 读取一个像素(越界 panic;测试用已知坐标)
46    pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
47        assert!(x < self.width && y < self.height, "pixel ({x},{y}) out of {}x{}", self.width, self.height);
48        let i = ((y * self.width + x) * 4) as usize;
49        [self.data[i], self.data[i + 1], self.data[i + 2], self.data[i + 3]]
50    }
51
52    pub fn try_pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
53        if x >= self.width || y >= self.height {
54            return None;
55        }
56        Some(self.pixel(x, y))
57    }
58}
59
60/// 软件后端图片纹理总预算(CPU 内存,128 MiB)。
61///
62/// 与 GPU 侧 256 MiB 预算独立:软件光栅器同时持有原图与预乘 pixmap,
63/// 且 headless/CI 的进程内存更敏感,所以取更小的值。
64pub const SOFTWARE_TEXTURE_BUDGET_BYTES: u64 = 128 * 1024 * 1024;
65
66/// layer 像素缓冲池上限:最多保留 8 个不同尺寸的 Pixmap,总字节 ≤32 MiB。
67const LAYER_POOL_MAX_BUFFERS: usize = 8;
68const LAYER_POOL_MAX_BYTES: u64 = 32 * 1024 * 1024;
69
70/// 按尺寸复用 layer 像素缓冲;多尺寸 layer 场景避免每层重新分配。
71#[derive(Default)]
72struct LayerPixmapPool {
73    by_size: HashMap<(u32, u32), Vec<Pixmap>>,
74    count: usize,
75    bytes: u64,
76}
77
78impl LayerPixmapPool {
79    fn take(&mut self, w: u32, h: u32) -> Option<Pixmap> {
80        let list = self.by_size.get_mut(&(w, h))?;
81        let mut pixmap = list.pop()?;
82        if list.is_empty() {
83            self.by_size.remove(&(w, h));
84        }
85        self.count = self.count.saturating_sub(1);
86        self.bytes = self.bytes.saturating_sub(pixmap_bytes(&pixmap));
87        pixmap.fill(tiny_skia::Color::TRANSPARENT);
88        Some(pixmap)
89    }
90
91    fn put(&mut self, pixmap: Pixmap) {
92        let bytes = pixmap_bytes(&pixmap);
93        if self.count >= LAYER_POOL_MAX_BUFFERS || self.bytes + bytes > LAYER_POOL_MAX_BYTES {
94            return;
95        }
96        self.by_size.entry((pixmap.width(), pixmap.height())).or_default().push(pixmap);
97        self.count += 1;
98        self.bytes += bytes;
99    }
100}
101
102fn pixmap_bytes(pixmap: &Pixmap) -> u64 {
103    pixmap.width() as u64 * pixmap.height() as u64 * 4
104}
105
106/// CPU 渲染器(缓存图片纹理 / glyph 着色结果,可跨帧复用)
107pub struct SoftwareRenderer {
108    /// id → (源数据,预乘 RGBA 全图)
109    textures: HashMap<u32, (Rc<ImageData>, Pixmap)>,
110    /// id → 最近使用帧时钟(用于预算淘汰)
111    texture_last_used: HashMap<u32, u64>,
112    /// atlas 覆盖区按 (generation, uv, color) 缓存
113    glyph_cache: HashMap<GlyphCacheKey, Pixmap>,
114    /// 图片按 (texture_id, tint) 缓存
115    tint_cache: HashMap<ImageTintKey, Pixmap>,
116    atlas_generation: u64,
117    /// 当前帧时钟(每帧 +1;last_used == frame_clock 表示本帧仍在使用)
118    frame_clock: u64,
119    /// 图片纹理预算(默认 [`SOFTWARE_TEXTURE_BUDGET_BYTES`];headless 可调低)
120    texture_budget: u64,
121    /// 跨帧复用的 surface target(尺寸不变时 fill 透明而不是重新分配)
122    target: Option<Pixmap>,
123    /// 按尺寸复用的 layer 像素缓冲池(多尺寸 layer 顺序复用)
124    layer_pool: LayerPixmapPool,
125    /// layer 合成参数 scratch(按 id/memo/visiting 复用三张表)
126    composition_scratch: CompositionScratch,
127    /// layer id → 逻辑尺寸,复用避免每帧分配
128    composition_sizes: HashMap<LayerId, Size>,
129}
130
131impl Default for SoftwareRenderer {
132    fn default() -> Self {
133        Self {
134            textures: HashMap::new(),
135            texture_last_used: HashMap::new(),
136            glyph_cache: HashMap::new(),
137            tint_cache: HashMap::new(),
138            atlas_generation: 0,
139            frame_clock: 0,
140            texture_budget: SOFTWARE_TEXTURE_BUDGET_BYTES,
141            target: None,
142            layer_pool: LayerPixmapPool::default(),
143            composition_scratch: CompositionScratch::default(),
144            composition_sizes: HashMap::new(),
145        }
146    }
147}
148
149impl SoftwareRenderer {
150    pub fn new() -> Self {
151        Self::default()
152    }
153
154    /// 调整图片纹理预算(字节);内存受限宿主/测试可调低。
155    pub fn set_texture_budget(&mut self, bytes: u64) {
156        self.texture_budget = bytes;
157    }
158
159    /// 显式注册图片纹理(测试/外部加载用;帧内 `pending_textures` 自动注册)
160    pub fn register_texture(&mut self, id: u32, data: Rc<ImageData>) {
161        self.insert_texture(id, data);
162    }
163
164    /// 渲染整帧(多 layer + 效果 + z-order)。`logical_size` 为 surface 逻辑尺寸。
165    pub fn render(&mut self, frame: &FramePaint, logical_size: Size, scale_factor: f32) -> RgbaImage {
166        let mut out = RgbaImage { width: 0, height: 0, data: Vec::new() };
167        self.render_into(frame, logical_size, scale_factor, &mut out);
168        out
169    }
170
171    /// 渲染到已有 `RgbaImage`(复用其像素 Vec);Headless/软件后端可跨帧复用,
172    /// 避免每帧分配整屏 RGBA。
173    pub fn render_into(&mut self, frame: &FramePaint, logical_size: Size, scale_factor: f32, out: &mut RgbaImage) {
174        let dpr = scale_factor.max(0.01);
175        mgui_text::text::set_text_dpr(dpr);
176        self.begin_frame();
177        for lp in &frame.sub_layers {
178            self.register_pending(&lp.paint_list);
179        }
180
181        let pw = physical(logical_size.width, dpr);
182        let ph = physical(logical_size.height, dpr);
183        let mut target = self.take_render_target(pw, ph);
184        self.composition_sizes.clear();
185        for lp in &frame.sub_layers {
186            self.composition_sizes.insert(lp.layer_id, layers::layer_size(lp, logical_size));
187        }
188        // CompositionScratch 暂时移出 self,避免与 rasterize(&mut self) 的借用冲突。
189        let mut scratch = std::mem::take(&mut self.composition_scratch);
190        scratch.resolve(&frame.sub_layers, &self.composition_sizes);
191
192        for lp in &frame.sub_layers {
193            let size = layers::layer_size(lp, logical_size);
194            if size.width <= 0.0 || size.height <= 0.0 {
195                continue;
196            }
197            let lw = physical(size.width, dpr);
198            let lh = physical(size.height, dpr);
199            let Some(mut layer_pix) = self.take_layer_pixmap(lw, lh) else { continue };
200            self.rasterize(&mut layer_pix, &lp.paint_list, dpr);
201            if let Some(comp) = scratch.get(lp.layer_id) {
202                let mask = layers::build_clip_mask(comp, logical_size, dpr);
203                layers::composite(&mut target, &layer_pix, comp, size, logical_size, dpr, mask.as_ref());
204            }
205            self.layer_pool.put(layer_pix);
206        }
207        self.composition_scratch = scratch;
208
209        self.evict_textures();
210        raster::pixmap_to_rgba_into(&target, &mut out.data);
211        out.width = pw;
212        out.height = ph;
213        self.target = Some(target);
214    }
215
216    /// 只渲染一个 PaintList(单 layer、无 layer effect;像素测试/预览用)
217    pub fn render_list(&mut self, list: &PaintList, logical_size: Size, scale_factor: f32) -> RgbaImage {
218        let dpr = scale_factor.max(0.01);
219        mgui_text::text::set_text_dpr(dpr);
220        self.begin_frame();
221        self.register_pending(list);
222        let pw = physical(logical_size.width, dpr);
223        let ph = physical(logical_size.height, dpr);
224        let mut pix = self.take_render_target(pw, ph);
225        self.rasterize(&mut pix, list, dpr);
226        self.evict_textures();
227        let data = raster::pixmap_to_rgba(&pix);
228        self.target = Some(pix);
229        RgbaImage { width: pw, height: ph, data }
230    }
231
232    /// 复用全屏 target;尺寸变化或首次使用时才分配。
233    fn take_render_target(&mut self, pw: u32, ph: u32) -> Pixmap {
234        match self.target.take() {
235            Some(mut pixmap) if pixmap.width() == pw && pixmap.height() == ph => {
236                pixmap.fill(tiny_skia::Color::TRANSPARENT);
237                pixmap
238            }
239            _ => Pixmap::new(pw, ph).expect("valid render target size"),
240        }
241    }
242
243    /// 复用单 layer 像素缓冲;同尺寸 layer 顺序渲染时只需清空。
244    fn take_layer_pixmap(&mut self, lw: u32, lh: u32) -> Option<Pixmap> {
245        self.layer_pool.take(lw, lh).or_else(|| Pixmap::new(lw, lh))
246    }
247
248    fn begin_frame(&mut self) {
249        self.frame_clock = self.frame_clock.wrapping_add(1);
250    }
251
252    fn rasterize(&mut self, target: &mut Pixmap, list: &PaintList, dpr: f32) {
253        let Self { textures, glyph_cache, tint_cache, atlas_generation, .. } = self;
254        let prev_generation = *atlas_generation;
255        let mut r = raster::Raster::new(target, dpr, textures, glyph_cache, tint_cache, *atlas_generation);
256        r.run(list);
257        *atlas_generation = r.atlas_generation;
258        if *atlas_generation != prev_generation {
259            // atlas 扩容/清空后旧 UV 全部失效:只保留新 generation 的着色缓存。
260            glyph_cache.retain(|k, _| k.generation == *atlas_generation);
261        }
262    }
263
264    fn register_pending(&mut self, list: &PaintList) {
265        for pending in &list.pending_textures {
266            self.insert_texture(pending.texture_id, Rc::clone(&pending.data));
267            self.texture_last_used.insert(pending.texture_id, self.frame_clock);
268        }
269    }
270
271    fn insert_texture(&mut self, id: u32, data: Rc<ImageData>) {
272        // 与 GPU 端**同一个判断**(`mgui_core::image::plan_texture_update`):
273        // 这里以前就是按 `Rc` 身份重建缓存的,V-P0-1 的修复正是把 GPU 端拉齐到这条规则上,
274        // 而不是反过来。规则收进 core 之后,两端再也没有各写一份"要不要更新"的余地。
275        use mgui_core::image::{image_identity, plan_texture_update, TextureUpdate};
276        let have = self.textures.get(&id).map(|(src, pix)| (image_identity(src), pix.width(), pix.height()));
277        let want = (image_identity(&data), data.width.max(1), data.height.max(1));
278        match plan_texture_update(have, want) {
279            TextureUpdate::Reuse => return,
280            TextureUpdate::UpdateContent | TextureUpdate::Recreate => {}
281        }
282        if let Some(pix) = raster::image_to_pixmap(&data) {
283            self.textures.insert(id, (data, pix));
284            self.texture_last_used.insert(id, self.frame_clock);
285            self.tint_cache.retain(|k, _| k.texture_id != id);
286        }
287    }
288
289    /// 超预算时淘汰本帧未使用的旧纹理(按最近使用时间)。
290    ///
291    /// 本帧声明过的纹理会通过 `register_pending` 刷新 `last_used`,不会被误删。
292    fn evict_textures(&mut self) {
293        let total: u64 = self.textures.values().map(|(_, pix)| pix.data().len() as u64).sum();
294        if total <= self.texture_budget {
295            return;
296        }
297        let mut candidates: Vec<(u32, u64, u64)> = self
298            .textures
299            .iter()
300            .filter(|(id, _)| self.texture_last_used.get(id).copied() != Some(self.frame_clock))
301            .map(|(&id, (_, pix))| (id, self.texture_last_used.get(&id).copied().unwrap_or(0), pix.data().len() as u64))
302            .collect();
303        candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
304
305        let mut total = total;
306        for (id, _, bytes) in candidates {
307            if total <= self.texture_budget {
308                break;
309            }
310            self.textures.remove(&id);
311            self.texture_last_used.remove(&id);
312            self.tint_cache.retain(|k, _| k.texture_id != id);
313            total = total.saturating_sub(bytes);
314        }
315        if total > self.texture_budget {
316            log::warn!(
317                target: "mgui_startup",
318                "software texture cache uses {} MiB (budget {} MiB); all remaining textures are in use this frame",
319                total / (1024 * 1024),
320                self.texture_budget / (1024 * 1024)
321            );
322        }
323    }
324}
325
326fn physical(logical: f32, dpr: f32) -> u32 {
327    (logical * dpr).round().max(1.0) as u32
328}
329
330/// 一次性渲染单个 PaintList 的便捷入口
331pub fn render_paint_list(list: &PaintList, size: Size, scale_factor: f32) -> RgbaImage {
332    SoftwareRenderer::new().render_list(list, size, scale_factor)
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use mgui_core::{Color, Rect};
339
340    /// 跨帧复用 target/layer 缓冲后,像素输出必须与重新分配时一致;
341    /// 视口尺寸变化时也要正确重建并输出新尺寸。
342    #[test]
343    fn target_and_layer_pixmap_reuse_preserve_pixels() {
344        let mut renderer = SoftwareRenderer::new();
345        let mut list = PaintList::new();
346        list.rect(Rect::new(0.0, 0.0, 32.0, 32.0), Color::from_rgb8(10, 20, 30));
347
348        let a = renderer.render_list(&list, Size::new(32.0, 32.0), 1.0);
349        let b = renderer.render_list(&list, Size::new(32.0, 32.0), 1.0);
350        assert_eq!(a.data, b.data, "复用 target/layer 缓冲不得改变像素");
351        assert_eq!(a.pixel(16, 16), [10, 20, 30, 255]);
352
353        let c = renderer.render_list(&list, Size::new(16.0, 16.0), 1.0);
354        assert_eq!((c.width, c.height), (16, 16), "尺寸变化后 target 必须重建");
355        assert_eq!(c.pixel(8, 8), [10, 20, 30, 255]);
356        assert_eq!(a.pixel(16, 16), [10, 20, 30, 255], "旧输出不能被复用缓冲覆盖");
357    }
358
359    /// layer 池按尺寸复用,并受数量/字节预算约束。
360    #[test]
361    fn layer_pixmap_pool_reuses_by_size_and_bounds_memory() {
362        let mut pool = LayerPixmapPool::default();
363        pool.put(Pixmap::new(16, 16).unwrap());
364        pool.put(Pixmap::new(32, 16).unwrap());
365        assert_eq!(pool.count, 2);
366        assert_eq!(pool.bytes, (16 * 16 + 32 * 16) * 4);
367
368        let a = pool.take(16, 16).expect("16x16 should be reused");
369        assert_eq!((a.width(), a.height()), (16, 16));
370        assert_eq!(pool.count, 1);
371        pool.put(a);
372        assert_eq!(pool.count, 2);
373
374        // 超过 32 MiB 单缓冲不再入池(避免 4K 大层常驻)
375        let huge = Pixmap::new(3000, 3000).unwrap();
376        pool.put(huge);
377        assert_eq!(pool.count, 2, "超预算缓冲应直接释放");
378    }
379
380    /// P1-4:超预算时只淘汰本帧未使用的旧纹理。
381    #[test]
382    fn texture_cache_evicts_unused_over_budget() {
383        let mut renderer = SoftwareRenderer::new();
384        let data = Rc::new(ImageData::solid(16, 16, Color::WHITE));
385
386        // 第一帧使用 id=1
387        renderer.begin_frame();
388        renderer.insert_texture(1, Rc::clone(&data));
389        renderer.texture_last_used.insert(1, renderer.frame_clock);
390
391        // 第二帧只使用 id=2 → id=1 变为可淘汰
392        renderer.begin_frame();
393        renderer.insert_texture(2, Rc::clone(&data));
394        renderer.texture_last_used.insert(2, renderer.frame_clock);
395
396        // 预算只够一张 16x16 RGBA
397        renderer.set_texture_budget(16 * 16 * 4);
398        renderer.evict_textures();
399        assert!(renderer.textures.contains_key(&2), "本帧使用的纹理不得淘汰");
400        assert!(!renderer.textures.contains_key(&1), "超预算时应淘汰未使用的旧纹理");
401    }
402}