1#![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#[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 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
60pub const SOFTWARE_TEXTURE_BUDGET_BYTES: u64 = 128 * 1024 * 1024;
65
66const LAYER_POOL_MAX_BUFFERS: usize = 8;
68const LAYER_POOL_MAX_BYTES: u64 = 32 * 1024 * 1024;
69
70#[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
106pub struct SoftwareRenderer {
108 textures: HashMap<u32, (Rc<ImageData>, Pixmap)>,
110 texture_last_used: HashMap<u32, u64>,
112 glyph_cache: HashMap<GlyphCacheKey, Pixmap>,
114 tint_cache: HashMap<ImageTintKey, Pixmap>,
116 atlas_generation: u64,
117 frame_clock: u64,
119 texture_budget: u64,
121 target: Option<Pixmap>,
123 layer_pool: LayerPixmapPool,
125 composition_scratch: CompositionScratch,
127 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 pub fn set_texture_budget(&mut self, bytes: u64) {
156 self.texture_budget = bytes;
157 }
158
159 pub fn register_texture(&mut self, id: u32, data: Rc<ImageData>) {
161 self.insert_texture(id, data);
162 }
163
164 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 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 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 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 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 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 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 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 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
330pub 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 #[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 #[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 let huge = Pixmap::new(3000, 3000).unwrap();
376 pool.put(huge);
377 assert_eq!(pool.count, 2, "超预算缓冲应直接释放");
378 }
379
380 #[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 renderer.begin_frame();
388 renderer.insert_texture(1, Rc::clone(&data));
389 renderer.texture_last_used.insert(1, renderer.frame_clock);
390
391 renderer.begin_frame();
393 renderer.insert_texture(2, Rc::clone(&data));
394 renderer.texture_last_used.insert(2, renderer.frame_clock);
395
396 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}