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 (id, data) in &list.pending_textures {
266 self.insert_texture(*id, Rc::clone(data));
267 self.texture_last_used.insert(*id, self.frame_clock);
268 }
269 }
270
271 fn insert_texture(&mut self, id: u32, data: Rc<ImageData>) {
272 let needs = match self.textures.get(&id) {
273 Some((old, _)) => !Rc::ptr_eq(old, &data),
274 None => true,
275 };
276 if !needs {
277 return;
278 }
279 if let Some(pix) = raster::image_to_pixmap(&data) {
280 self.textures.insert(id, (data, pix));
281 self.texture_last_used.insert(id, self.frame_clock);
282 self.tint_cache.retain(|k, _| k.texture_id != id);
283 }
284 }
285
286 fn evict_textures(&mut self) {
290 let total: u64 = self.textures.values().map(|(_, pix)| pix.data().len() as u64).sum();
291 if total <= self.texture_budget {
292 return;
293 }
294 let mut candidates: Vec<(u32, u64, u64)> = self
295 .textures
296 .iter()
297 .filter(|(id, _)| self.texture_last_used.get(id).copied() != Some(self.frame_clock))
298 .map(|(&id, (_, pix))| (id, self.texture_last_used.get(&id).copied().unwrap_or(0), pix.data().len() as u64))
299 .collect();
300 candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
301
302 let mut total = total;
303 for (id, _, bytes) in candidates {
304 if total <= self.texture_budget {
305 break;
306 }
307 self.textures.remove(&id);
308 self.texture_last_used.remove(&id);
309 self.tint_cache.retain(|k, _| k.texture_id != id);
310 total = total.saturating_sub(bytes);
311 }
312 if total > self.texture_budget {
313 log::warn!(
314 target: "mgui_startup",
315 "software texture cache uses {} MiB (budget {} MiB); all remaining textures are in use this frame",
316 total / (1024 * 1024),
317 self.texture_budget / (1024 * 1024)
318 );
319 }
320 }
321}
322
323fn physical(logical: f32, dpr: f32) -> u32 {
324 (logical * dpr).round().max(1.0) as u32
325}
326
327pub fn render_paint_list(list: &PaintList, size: Size, scale_factor: f32) -> RgbaImage {
329 SoftwareRenderer::new().render_list(list, size, scale_factor)
330}
331
332#[cfg(test)]
333mod tests {
334 use super::*;
335 use mgui_core::{Color, Rect};
336
337 #[test]
340 fn target_and_layer_pixmap_reuse_preserve_pixels() {
341 let mut renderer = SoftwareRenderer::new();
342 let mut list = PaintList::new();
343 list.rect(Rect::new(0.0, 0.0, 32.0, 32.0), Color::from_rgb8(10, 20, 30));
344
345 let a = renderer.render_list(&list, Size::new(32.0, 32.0), 1.0);
346 let b = renderer.render_list(&list, Size::new(32.0, 32.0), 1.0);
347 assert_eq!(a.data, b.data, "复用 target/layer 缓冲不得改变像素");
348 assert_eq!(a.pixel(16, 16), [10, 20, 30, 255]);
349
350 let c = renderer.render_list(&list, Size::new(16.0, 16.0), 1.0);
351 assert_eq!((c.width, c.height), (16, 16), "尺寸变化后 target 必须重建");
352 assert_eq!(c.pixel(8, 8), [10, 20, 30, 255]);
353 assert_eq!(a.pixel(16, 16), [10, 20, 30, 255], "旧输出不能被复用缓冲覆盖");
354 }
355
356 #[test]
358 fn layer_pixmap_pool_reuses_by_size_and_bounds_memory() {
359 let mut pool = LayerPixmapPool::default();
360 pool.put(Pixmap::new(16, 16).unwrap());
361 pool.put(Pixmap::new(32, 16).unwrap());
362 assert_eq!(pool.count, 2);
363 assert_eq!(pool.bytes, (16 * 16 + 32 * 16) * 4);
364
365 let a = pool.take(16, 16).expect("16x16 should be reused");
366 assert_eq!((a.width(), a.height()), (16, 16));
367 assert_eq!(pool.count, 1);
368 pool.put(a);
369 assert_eq!(pool.count, 2);
370
371 let huge = Pixmap::new(3000, 3000).unwrap();
373 pool.put(huge);
374 assert_eq!(pool.count, 2, "超预算缓冲应直接释放");
375 }
376
377 #[test]
379 fn texture_cache_evicts_unused_over_budget() {
380 let mut renderer = SoftwareRenderer::new();
381 let data = Rc::new(ImageData::solid(16, 16, Color::WHITE));
382
383 renderer.begin_frame();
385 renderer.insert_texture(1, Rc::clone(&data));
386 renderer.texture_last_used.insert(1, renderer.frame_clock);
387
388 renderer.begin_frame();
390 renderer.insert_texture(2, Rc::clone(&data));
391 renderer.texture_last_used.insert(2, renderer.frame_clock);
392
393 renderer.set_texture_budget(16 * 16 * 4);
395 renderer.evict_textures();
396 assert!(renderer.textures.contains_key(&2), "本帧使用的纹理不得淘汰");
397 assert!(!renderer.textures.contains_key(&1), "超预算时应淘汰未使用的旧纹理");
398 }
399}