1use mgui_core::paint::{BlendMode, TextureMode};
2use mgui_core::Rect;
3use mgui_core::{effect_flags, FramePaint, LayerEffect, LayerId, LayerPaint, PaintCommand, PaintList, RRectDef, Size};
4use std::cell::RefCell;
5use std::collections::HashMap;
6use std::rc::Rc;
7use std::time::Duration;
8
9use wgpu::util::DeviceExt;
10
11#[repr(C)]
14#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
15pub(crate) struct RectBatchUniform {
16 screen_size: [f32; 2], count: u32, _pad: [f32; 1], }
20
21#[repr(C)]
29#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
30pub(crate) struct RectInstance {
31 rect: [f32; 4],
32 from: [f32; 4],
33 to: [f32; 4],
34 grad: [f32; 4],
35 params: [f32; 4],
37}
38
39#[repr(C)]
41#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
42pub(crate) struct TextBatchUniform {
43 screen_size: [f32; 2], count: u32, _pad: [f32; 1], }
47
48#[repr(C)]
52#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
53pub(crate) struct TextInstance {
54 rect: [f32; 4], color: [f32; 4], uv: [f32; 4], mode: f32, _pad: [f32; 3], }
62
63#[repr(C)]
74#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
75pub(crate) struct BlitUniform {
76 offset: [f32; 2], size: [f32; 2], screen: [f32; 2], effect_flags: u32, opacity: f32, rotation: f32, scale_x: f32, translate_x: f32, translate_y: f32, clip_radius: f32, scale_y: f32, quad_offset: [f32; 2], quad_size: [f32; 2], phys_screen: [f32; 2], affine: [f32; 4], affine_translate: [f32; 2], _affine_pad: [f32; 2], clip_rect0: [f32; 4], clip_rect1: [f32; 4], clip_params: [f32; 4], }
105struct LayerGpuCache {
109 resolve_texture: wgpu::Texture,
111 resolve_view: wgpu::TextureView,
113 cached_size: (u32, u32),
115}
116
117#[derive(Clone)]
122pub struct RendererShared {
123 rect_pipelines: [wgpu::RenderPipeline; 4],
125 rect_bgl: wgpu::BindGroupLayout,
126 text_pipeline: wgpu::RenderPipeline,
127 text_bgl: wgpu::BindGroupLayout,
128 text_pipeline_mask: wgpu::RenderPipeline,
130 text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
131 tri_pipeline: wgpu::RenderPipeline,
132 tri_bgl: wgpu::BindGroupLayout,
133 tri_pipeline_stencil_inc: wgpu::RenderPipeline,
135 tri_pipeline_stencil_dec: wgpu::RenderPipeline,
136 rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
137 text_pipeline_stencil_test: wgpu::RenderPipeline,
138 tri_pipeline_stencil_test: wgpu::RenderPipeline,
139 blit_pipeline: wgpu::RenderPipeline,
140 blit_bgl: wgpu::BindGroupLayout,
141 blit_sampler: wgpu::Sampler,
142 backdrop_pipeline: wgpu::RenderPipeline,
144 backdrop_bgl: wgpu::BindGroupLayout,
145 format: wgpu::TextureFormat,
146 atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
147 image_cache: Rc<RefCell<ImageTextureCache>>,
148}
149
150#[derive(Default)]
152pub(crate) struct ImageTextureCache {
153 textures: HashMap<u32, ImageTextureEntry>,
154 clock: u64,
155 evict_enabled: bool,
157}
158
159impl RendererShared {
160 pub fn format(&self) -> wgpu::TextureFormat {
161 self.format
162 }
163
164 pub fn evict_images(&self, protected: &std::collections::HashSet<u32>) {
167 self.image_cache.borrow_mut().evict_to_budget(protected);
168 }
169}
170
171impl ImageTextureCache {
172 fn evict_to_budget(&mut self, protected: &std::collections::HashSet<u32>) {
173 let budget = IMAGE_TEXTURE_BUDGET_BYTES;
174 let mut total: u64 = self.textures.values().map(|e| e.bytes).sum();
175 if total <= budget {
176 return;
177 }
178 let mut candidates: Vec<(u32, u64, u64)> = self
179 .textures
180 .iter()
181 .filter(|(id, _)| !protected.contains(id))
182 .map(|(&id, e)| (id, e.last_used, e.bytes))
183 .collect();
184 candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
185 for (id, _, bytes) in candidates {
186 if total <= budget {
187 break;
188 }
189 self.textures.remove(&id);
190 total = total.saturating_sub(bytes);
191 }
192 if total > budget {
193 log::warn!(
194 target: "mgui_startup",
195 "shared image cache uses {} MiB (budget {} MiB); all remaining textures are in use",
196 total / (1024 * 1024),
197 budget / (1024 * 1024)
198 );
199 }
200 }
201}
202
203#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
204pub struct PresentStats {
205 pub presents: u64,
208 pub wait_ns: u64,
211 pub submit_ns: u64,
213 pub gaps: u64,
216 pub gap_sum_ns: u64,
217 pub gap_max_ns: u64,
218 pub last_gap_ns: u64,
220 pub present_mode: &'static str,
228 pub max_frame_latency: u32,
230 pub present_path_cpu_ns: u64,
233 pub redraw_cpu_ns: u64,
235 pub last_present_path_cpu_ns: u64,
237 pub last_redraw_cpu_ns: u64,
238 pub frame_to_acquire_ns: u64,
242 pub acquire_to_submit_ns: u64,
245 pub last_frame_to_acquire_ns: u64,
246 pub last_acquire_to_submit_ns: u64,
247}
248
249impl PresentStats {
250 pub fn record(&mut self, wait_ns: u64, submit_ns: u64, gap: Option<Duration>, mode: &'static str, latency: u32) {
255 self.presents = self.presents.saturating_add(1);
256 self.wait_ns = self.wait_ns.saturating_add(wait_ns);
257 self.submit_ns = self.submit_ns.saturating_add(submit_ns);
258 self.present_mode = mode;
259 self.max_frame_latency = latency;
260 if let Some(gap) = gap {
261 let ns = gap.as_nanos() as u64;
262 self.gaps = self.gaps.saturating_add(1);
263 self.gap_sum_ns = self.gap_sum_ns.saturating_add(ns);
264 self.gap_max_ns = self.gap_max_ns.max(ns);
265 self.last_gap_ns = ns;
266 }
267 }
268
269 pub fn mean_gap_ns(&self) -> u64 {
271 self.gap_sum_ns.checked_div(self.gaps).unwrap_or(0)
272 }
273}
274
275pub(crate) struct TextureUploadRecord {
283 pub outcome: mgui_core::image::TextureUpdate,
284 pub source_bytes: u64,
286 pub active_bytes: u64,
287 pub write_ns: u64,
289 pub width: u32,
292 pub height: u32,
293 pub meta: Option<mgui_core::paint::TextureFrameMeta>,
294}
295
296impl TextureUploadRecord {
297 pub(crate) fn outcome_code(&self) -> u8 {
299 use mgui_core::image::TextureUpdate;
300 match self.outcome {
301 TextureUpdate::Reuse => 1,
302 TextureUpdate::UpdateContent => 2,
303 TextureUpdate::Recreate => 3,
304 }
305 }
306}
307
308#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
309pub struct RenderStats {
310 pub layers_painted: u32,
312 pub segments: u32,
314 pub draw_calls: u32,
316 pub scratch_bytes: u64,
318 pub layer_texture_bytes: u64,
320 pub upload_ns: u64,
329 pub upload_write_ns: u64,
331 pub last_upload_width: u32,
333 pub last_upload_height: u32,
334 pub upload_source_bytes: u64,
336 pub upload_active_bytes: u64,
338 pub upload_count: u32,
340 pub texture_decl_count: u32,
342 pub texture_reuse_count: u32,
343 pub texture_update_count: u32,
344 pub texture_recreate_count: u32,
345 pub stale_decl_count: u32,
348 pub unsynced_decl_count: u32,
350 pub last_frame_sequence: u64,
353 pub last_frame_generation: u64,
354 pub last_frame_age_ns: u64,
355 pub last_frame_synced_seq: u64,
357 pub last_frame_latest_seq: u64,
358 pub last_frame_outcome: u8,
360 pub last_frame_encoder: u8,
362}
363
364pub struct Renderer {
365 rect_pipelines: [wgpu::RenderPipeline; 4],
367 rect_bgl: wgpu::BindGroupLayout,
368 text_pipeline: wgpu::RenderPipeline,
369 text_bgl: wgpu::BindGroupLayout,
370 text_pipeline_mask: wgpu::RenderPipeline,
372 text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
373 tri_pipeline: wgpu::RenderPipeline,
375 tri_bgl: wgpu::BindGroupLayout,
376 tri_pipeline_stencil_inc: wgpu::RenderPipeline,
380 tri_pipeline_stencil_dec: wgpu::RenderPipeline,
381 rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
382 text_pipeline_stencil_test: wgpu::RenderPipeline,
383 tri_pipeline_stencil_test: wgpu::RenderPipeline,
384 atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
386 layer_cache: HashMap<LayerId, LayerGpuCache>,
388 active_layer_ids: std::collections::HashSet<LayerId>,
390 frame_layer_sizes: HashMap<LayerId, Size>,
392 composition_scratch: mgui_core::CompositionScratch,
394 blit_pipeline: wgpu::RenderPipeline,
396 blit_bgl: wgpu::BindGroupLayout,
397 blit_sampler: wgpu::Sampler,
398 backdrop_pipeline: wgpu::RenderPipeline,
400 backdrop_bgl: wgpu::BindGroupLayout,
401 format: wgpu::TextureFormat,
403 pub gpu_profiler: Option<crate::gpu_profiler::GpuProfiler>,
405 batch_pools: HashMap<(LayerId, u32), LayerBatchPool>,
414 image_cache: Rc<RefCell<ImageTextureCache>>,
416 msaa_scratch: HashMap<(u32, u32), wgpu::TextureView>,
418 stencil_scratch: HashMap<(u32, u32), wgpu::TextureView>,
419 snapshot_scratch: HashMap<(u32, u32), (wgpu::Texture, wgpu::TextureView)>,
420 last_stats: RenderStats,
422 pending_upload: Option<(Vec<TextureUploadRecord>, u64)>,
427}
428
429pub(crate) struct ImageTextureEntry {
431 pub _texture: wgpu::Texture,
433 pub view: wgpu::TextureView,
434 pub sampler: wgpu::Sampler,
435 pub last_used: u64,
437 pub bytes: u64,
439 pub source: Rc<mgui_core::image::ImageData>,
442 pub size: (u32, u32),
444}
445
446pub const IMAGE_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
448
449pub use setup::LAYER_TEXTURE_BUDGET_BYTES;
451
452pub use mgui_core::inspect::ImageTextureStats;
453
454impl Renderer {
455 pub fn last_stats(&self) -> RenderStats {
457 self.last_stats
458 }
459
460 pub fn image_texture_stats(&self) -> ImageTextureStats {
462 let cache = self.image_cache.borrow();
463 ImageTextureStats {
464 count: cache.textures.len(),
465 bytes: cache.textures.values().map(|e| e.bytes).sum(),
466 budget_bytes: IMAGE_TEXTURE_BUDGET_BYTES,
467 }
468 }
469}
470
471struct LayerBatchPool {
473 rect_header: Option<wgpu::Buffer>,
474 rect_instances: Option<wgpu::Buffer>,
475 text_header: Option<wgpu::Buffer>,
476 text_instances: Option<wgpu::Buffer>,
477 tri_vertex: Option<wgpu::Buffer>,
479 tri_index: Option<wgpu::Buffer>,
480 tri_uniform: Option<wgpu::Buffer>,
481 stencil_vertex: Option<wgpu::Buffer>,
484 stencil_index: Option<wgpu::Buffer>,
485}
486
487pub(crate) struct AtlasGpu {
489 texture: wgpu::Texture,
490 view: wgpu::TextureView,
491 sampler: wgpu::Sampler,
492 cached_size: (u32, u32),
494}
495
496pub(crate) struct RectBatch {
497 bg: wgpu::BindGroup,
498}
499
500pub(crate) struct TriBatch {
502 bg: wgpu::BindGroup,
503}
504
505#[repr(C)]
507#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
508struct TriUniform {
509 screen_size: [f32; 2],
510 _pad0: u32,
511 _pad1: u32,
512}
513
514#[repr(C)]
516#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
517struct BackdropUniform {
518 screen: [f32; 2],
519 _pad: [f32; 2],
520 rect: [f32; 4],
521 params: [f32; 4],
523 tint: [f32; 4],
525}
526
527pub(crate) struct TextBatch {
529 bg: wgpu::BindGroup,
530 count: u32,
531}
532
533#[derive(Debug, Clone, Default)]
539pub(crate) struct StencilDraw {
540 pub vertices: Vec<f32>,
542 pub indices: Vec<u32>,
543}
544
545#[derive(Debug, Clone, Copy, PartialEq, Eq)]
550pub(crate) struct StencilAction {
551 pub draw: u32,
553 pub level: u32,
555 pub increment: bool,
556}
557
558pub(crate) struct StencilGpu {
560 pub vertex: wgpu::Buffer,
561 pub index: wgpu::Buffer,
562 pub ranges: Vec<(u32, u32)>,
563 pub bg: wgpu::BindGroup,
564}
565
566#[derive(Debug, Clone, Copy)]
568pub(crate) struct BackdropBlurSpec {
569 pub rect: Rect,
570 pub radius: f32,
571 pub blur_radius: f32,
572 pub tint: [f32; 4],
573}
574
575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
577pub(crate) enum DrawOp {
578 Rect(u32, u32, BlendMode),
580 Text(u32, u32),
582 Image(u32),
584 Mask(u32),
586 BackdropBlur(u32),
588 Tri(u32, u32),
590}
591
592#[derive(Debug, Clone, PartialEq)]
598pub(crate) struct ClipSegment {
599 pub scissor: Option<[u32; 4]>,
601 pub ops: Vec<DrawOp>,
603 pub rect_range: (u32, u32),
605 pub text_range: (u32, u32),
606 pub image_range: (u32, u32),
607 pub stencil_level: u32,
609 pub stencil_actions: Vec<StencilAction>,
611}
612
613pub(crate) struct ImageGroup {
616 pub texture_id: u32,
617 pub instances: Vec<TextInstance>,
618}
619
620pub(crate) struct ImageBatchDraw {
626 pub(crate) batch: TextBatch,
627}
628
629fn intersect_rect(a: Rect, b: Rect) -> Rect {
631 let x1 = a.x.max(b.x);
632 let y1 = a.y.max(b.y);
633 let x2 = (a.x + a.width).min(b.x + b.width);
634 let y2 = (a.y + a.height).min(b.y + b.height);
635 Rect::new(x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0))
636}
637
638fn path_bounding_box(vertices: &[mgui_core::paint::Vertex]) -> Rect {
640 if vertices.is_empty() {
641 return Rect::new(0.0, 0.0, 0.0, 0.0);
642 }
643 let mut min_x = f32::INFINITY;
644 let mut min_y = f32::INFINITY;
645 let mut max_x = f32::NEG_INFINITY;
646 let mut max_y = f32::NEG_INFINITY;
647 for v in vertices {
648 min_x = min_x.min(v.x);
649 min_y = min_y.min(v.y);
650 max_x = max_x.max(v.x);
651 max_y = max_y.max(v.y);
652 }
653 Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
654}
655
656fn rect_intersects_clip(r: &Rect, clip: Option<Rect>) -> bool {
658 match clip {
659 None => true,
660 Some(c) => {
662 c.width > 0.0
663 && c.height > 0.0
664 && r.x < c.x + c.width
665 && r.x + r.width > c.x
666 && r.y < c.y + c.height
667 && r.y + r.height > c.y
668 }
669 }
670}
671
672fn rounded_rect_stencil_mesh(rect: Rect, radius: f32) -> (Vec<f32>, Vec<u32>) {
677 if rect.width <= 0.0 || rect.height <= 0.0 {
678 return (Vec::new(), Vec::new());
679 }
680 let (x, y, w, h) = (rect.x, rect.y, rect.width, rect.height);
681 let r = radius.max(0.0).min(w.min(h) * 0.5);
682
683 let mut pts: Vec<(f32, f32)> = Vec::new();
684 if r <= 0.0 {
685 pts.extend_from_slice(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
686 } else {
687 const SEG: u32 = 8;
688 let arcs = [
690 (x + w - r, y + r, -std::f32::consts::FRAC_PI_2, 0.0),
691 (x + w - r, y + h - r, 0.0, std::f32::consts::FRAC_PI_2),
692 (x + r, y + h - r, std::f32::consts::FRAC_PI_2, std::f32::consts::PI),
693 (x + r, y + r, std::f32::consts::PI, 3.0 * std::f32::consts::FRAC_PI_2),
694 ];
695 for &(cx, cy, a0, a1) in &arcs {
696 for i in 0..=SEG {
697 let a = a0 + (a1 - a0) * (i as f32 / SEG as f32);
698 pts.push((cx + r * a.cos(), cy + r * a.sin()));
699 }
700 }
701 if pts.len() > 1 && pts.first() == pts.last() {
703 pts.pop();
704 }
705 }
706 pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5);
707
708 let n = pts.len();
709 if n < 3 {
710 return (Vec::new(), Vec::new());
711 }
712 let mut verts = Vec::with_capacity((n + 1) * 6);
713 for &(px, py) in &pts {
714 verts.extend_from_slice(&[px, py, 1.0, 1.0, 1.0, 1.0]);
715 }
716 verts.extend_from_slice(&[x + w * 0.5, y + h * 0.5, 1.0, 1.0, 1.0, 1.0]);
717 let center = n as u32;
718 let mut indices = Vec::with_capacity(n * 3);
719 for i in 0..n as u32 {
720 indices.extend_from_slice(&[center, i, (i + 1) % n as u32]);
721 }
722 (verts, indices)
723}
724
725fn clip_to_scissor_px(r: Rect, dpr: f32, tex: (u32, u32)) -> [u32; 4] {
727 let d = dpr.max(0.0);
728 let (tw, th) = (tex.0 as f32, tex.1 as f32);
729 let x0 = (r.x * d).floor().clamp(0.0, tw);
732 let y0 = (r.y * d).floor().clamp(0.0, th);
733 let x1 = ((r.x + r.width) * d).ceil().clamp(0.0, tw).max(x0);
734 let y1 = ((r.y + r.height) * d).ceil().clamp(0.0, th).max(y0);
735 let x = x0 as u32;
736 let y = y0 as u32;
737 let w = (x1 as u32).saturating_sub(x);
738 let h = (y1 as u32).saturating_sub(y);
739 [x, y, w, h]
740}
741
742type CollectedInstances = (
757 Vec<RectInstance>,
758 Vec<TextInstance>,
759 Vec<ImageGroup>,
760 Vec<ClipSegment>,
761 Vec<f32>, Vec<u32>, Vec<StencilDraw>,
766 Vec<BackdropBlurSpec>,
768);
769
770pub(crate) fn collect_instances_segmented(
771 paint_list: &PaintList,
772 dpr: f32,
773 tex_size: (u32, u32),
774) -> CollectedInstances {
775 let mut rects: Vec<RectInstance> = Vec::new();
776 let mut texts: Vec<TextInstance> = Vec::new();
777 let mut image_groups: Vec<ImageGroup> = Vec::new();
778 let mut segments: Vec<ClipSegment> = Vec::new();
779 let mut tri_vertices: Vec<f32> = Vec::new(); let mut tri_indices: Vec<u32> = Vec::new(); let mut tri_base_vertex: u32 = 0; let mut stencil_draws: Vec<StencilDraw> = Vec::new();
785 let mut pending_stencil: Vec<StencilAction> = Vec::new();
786 let mut backdrop_blurs: Vec<BackdropBlurSpec> = Vec::new();
787 let mut path_draw_stack: Vec<Option<u32>> = Vec::new();
788 let mut clip_depth: u32 = 0;
789 let mut blend_stack: Vec<BlendMode> = Vec::new();
791 let mut cur_blend = BlendMode::Normal;
792 let mut stack: Vec<(Option<Rect>, bool)> = Vec::new();
794 let mut cur_clip: Option<Rect> = None;
795 let (mut seg_r, mut seg_t, mut seg_i): (u32, u32, u32) = (0, 0, 0);
796 let mut ops: Vec<DrawOp> = Vec::new();
798
799 macro_rules! close_segment {
801 () => {
802 let r_end = rects.len() as u32;
803 let t_end = texts.len() as u32;
804 let i_end = image_groups.len() as u32;
805 if !ops.is_empty() {
806 segments.push(ClipSegment {
807 scissor: cur_clip.map(|c| clip_to_scissor_px(c, dpr, tex_size)),
808 ops: ops.clone(),
809 rect_range: (seg_r, r_end),
810 text_range: (seg_t, t_end),
811 image_range: (seg_i, i_end),
812 stencil_level: clip_depth,
813 stencil_actions: std::mem::take(&mut pending_stencil),
816 });
817 ops.clear();
818 }
819 seg_r = r_end;
820 seg_t = t_end;
821 seg_i = i_end;
822 };
823 }
824
825 fn push_range_op(ops: &mut Vec<DrawOp>, op: DrawOp) {
826 match op {
827 DrawOp::Rect(s, e, mode) => {
828 if let Some(DrawOp::Rect(_, last_end, last_mode)) = ops.last_mut() {
829 if *last_end == s && *last_mode == mode {
830 *last_end = e;
831 return;
832 }
833 }
834 }
835 DrawOp::Text(s, e) => {
836 if let Some(DrawOp::Text(_, last_end)) = ops.last_mut() {
837 if *last_end == s {
838 *last_end = e;
839 return;
840 }
841 }
842 }
843 DrawOp::Tri(s, e) => {
844 if let Some(DrawOp::Tri(_, last_end)) = ops.last_mut() {
845 if *last_end == s {
846 *last_end = e;
847 return;
848 }
849 }
850 }
851 DrawOp::Image(_) => {}
852 DrawOp::Mask(_) => {}
853 DrawOp::BackdropBlur(_) => {}
854 }
855 ops.push(op);
856 }
857
858 macro_rules! push_mask_clip {
860 ($flat:expr, $idxs:expr, $bbox:expr) => {{
861 clip_depth += 1;
862 let flat_verts: Vec<f32> = $flat;
863 let idxs: &[u32] = $idxs;
864 let draw_index = if !flat_verts.is_empty() && !idxs.is_empty() {
865 let idx = stencil_draws.len() as u32;
866 stencil_draws.push(StencilDraw { vertices: flat_verts, indices: idxs.to_vec() });
867 pending_stencil.push(StencilAction { draw: idx, level: clip_depth, increment: true });
868 Some(idx)
869 } else {
870 None
871 };
872 path_draw_stack.push(draw_index);
873
874 let bbox: Rect = $bbox;
875 stack.push((cur_clip, true));
876 cur_clip = Some(match cur_clip {
877 Some(outer) => intersect_rect(outer, bbox),
878 None => bbox,
879 });
880 }};
881 }
882
883 macro_rules! pop_mask_clip {
885 () => {{
886 if let Some(Some(draw)) = path_draw_stack.pop() {
887 pending_stencil.push(StencilAction { draw, level: clip_depth, increment: false });
889 }
890 clip_depth = clip_depth.saturating_sub(1);
891 }};
892 }
893
894 for cmd in &paint_list.commands {
895 match cmd {
896 PaintCommand::PushBlendMode(mode) => {
897 blend_stack.push(cur_blend);
898 cur_blend = *mode;
899 }
900 PaintCommand::PopBlendMode => {
901 cur_blend = blend_stack.pop().unwrap_or(BlendMode::Normal);
902 }
903 PaintCommand::PushClip(r) => {
904 close_segment!();
905 stack.push((cur_clip, false));
906 cur_clip = Some(match cur_clip {
907 Some(outer) => intersect_rect(outer, *r),
908 None => *r,
909 });
910 }
911 PaintCommand::PushClipRRect { rect, radius } => {
912 close_segment!();
913 let (flat_verts, idxs) = rounded_rect_stencil_mesh(*rect, *radius);
914 push_mask_clip!(flat_verts, &idxs, *rect);
915 }
916 PaintCommand::PopClip => {
917 close_segment!();
918 let (prev, is_mask) = stack.pop().unwrap_or((None, false));
919 if is_mask {
920 pop_mask_clip!();
921 }
922 cur_clip = prev;
923 }
924 PaintCommand::PushClipPath { vertices, indices } => {
926 close_segment!();
927 let mut flat_verts: Vec<f32> = Vec::with_capacity(vertices.len() * 6);
928 for v in vertices {
929 flat_verts.push(v.x);
930 flat_verts.push(v.y);
931 flat_verts.push(v.color.r);
932 flat_verts.push(v.color.g);
933 flat_verts.push(v.color.b);
934 flat_verts.push(v.color.a);
935 }
936 push_mask_clip!(flat_verts, indices, path_bounding_box(vertices));
937 }
938 PaintCommand::PopClipPath => {
939 close_segment!();
940 let (prev, is_mask) = stack.pop().unwrap_or((None, false));
941 if is_mask {
942 pop_mask_clip!();
943 }
944 cur_clip = prev;
945 }
946 PaintCommand::Rect { rect, color, radius } => {
947 if rect_intersects_clip(rect, cur_clip) {
948 let start = rects.len() as u32;
949 rects.push(RectInstance {
950 rect: [rect.x, rect.y, rect.width, rect.height],
951 from: [color.r, color.g, color.b, color.a],
952 to: [color.r, color.g, color.b, color.a],
953 grad: [0.0; 4],
954 params: [*radius, 0.0, 0.0, 0.0],
955 });
956 push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
957 }
958 }
959 PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
961 if rect_intersects_clip(rect, cur_clip) {
962 let start = rects.len() as u32;
963 rects.push(RectInstance {
964 rect: [rect.x, rect.y, rect.width, rect.height],
965 from: [color.r, color.g, color.b, color.a],
966 to: [color.r, color.g, color.b, color.a],
967 grad: [0.0; 4],
968 params: [*radius, 0.0, *blur_radius, 0.0],
969 });
970 push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
971 }
972 }
973 PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
975 if rect_intersects_clip(rect, cur_clip) {
976 let idx = rects.len() as u32;
977 rects.push(RectInstance {
978 rect: [rect.x, rect.y, rect.width, rect.height],
979 from: [color.r, color.g, color.b, color.a],
980 to: [color.r, color.g, color.b, color.a],
981 grad: [0.0; 4],
982 params: [*radius, 3.0, *blur_radius, 0.0],
983 });
984 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
985 }
986 }
987 PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
988 if rect_intersects_clip(rect, cur_clip) {
989 let idx = rects.len() as u32;
990 rects.push(RectInstance {
991 rect: [rect.x, rect.y, rect.width, rect.height],
992 from: [from.r, from.g, from.b, from.a],
993 to: [to.r, to.g, to.b, to.a],
994 grad: [start.x, start.y, end.x, end.y],
995 params: [*corner_radius, 1.0, 0.0, 0.0],
996 });
997 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
998 }
999 }
1000 PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
1001 if rect_intersects_clip(rect, cur_clip) {
1002 let idx = rects.len() as u32;
1003 rects.push(RectInstance {
1004 rect: [rect.x, rect.y, rect.width, rect.height],
1005 from: [from.r, from.g, from.b, from.a],
1006 to: [to.r, to.g, to.b, to.a],
1007 grad: [center.x, center.y, *radial_radius, 0.0],
1008 params: [*corner_radius, 2.0, 0.0, 0.0],
1009 });
1010 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
1011 }
1012 }
1013 PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
1015 if rect_intersects_clip(rect, cur_clip) {
1016 let idx = backdrop_blurs.len() as u32;
1017 backdrop_blurs.push(BackdropBlurSpec {
1018 rect: *rect,
1019 radius: *radius,
1020 blur_radius: *blur_radius,
1021 tint: [tint.r, tint.g, tint.b, tint.a],
1022 });
1023 ops.push(DrawOp::BackdropBlur(idx));
1024 }
1025 }
1026 PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
1028 if *alpha > 0.0 && rect_intersects_clip(rect, cur_clip) {
1029 let gi = image_groups.len() as u32;
1030 image_groups.push(ImageGroup {
1031 texture_id: *texture_id,
1032 instances: vec![TextInstance {
1033 rect: [rect.x, rect.y, rect.width, rect.height],
1034 color: [1.0, 1.0, 1.0, alpha.clamp(0.0, 1.0)],
1036 uv: *uv,
1037 mode: 2.0,
1038 _pad: [0.0; 3],
1039 }],
1040 });
1041 ops.push(DrawOp::Mask(gi));
1042 }
1043 }
1044 PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
1045 if rect_intersects_clip(rect, cur_clip) {
1046 let snap = |v: f32| (v * dpr).round() / dpr;
1049 let inst = TextInstance {
1050 rect: [
1051 snap(rect.x),
1052 snap(rect.y),
1053 snap(rect.x + rect.width) - snap(rect.x),
1054 snap(rect.y + rect.height) - snap(rect.y),
1055 ],
1056 color: [color.r, color.g, color.b, color.a],
1057 uv: *uv,
1058 mode: match mode {
1059 TextureMode::Mask => 0.0,
1060 TextureMode::Color => 1.0,
1061 },
1062 _pad: [0.0; 3],
1063 };
1064 if *texture_id == 0 {
1065 let start = texts.len() as u32;
1066 texts.push(inst);
1067 push_range_op(&mut ops, DrawOp::Text(start, start + 1));
1068 } else {
1069 let reuse_group = ops
1073 .last()
1074 .and_then(|op| match op {
1075 DrawOp::Image(gi) => Some(*gi),
1076 _ => None,
1077 })
1078 .filter(|&gi| image_groups[gi as usize].texture_id == *texture_id);
1079 if let Some(gi) = reuse_group {
1080 image_groups[gi as usize].instances.push(inst);
1081 } else {
1082 let gi = image_groups.len() as u32;
1083 image_groups.push(ImageGroup { texture_id: *texture_id, instances: vec![inst] });
1084 ops.push(DrawOp::Image(gi));
1085 }
1086 }
1087 }
1088 }
1089 PaintCommand::Triangles { vertices, indices } => {
1092 let idx_start = tri_indices.len() as u32;
1093 for v in vertices {
1095 tri_vertices.push(v.x);
1096 tri_vertices.push(v.y);
1097 tri_vertices.push(v.color.r);
1098 tri_vertices.push(v.color.g);
1099 tri_vertices.push(v.color.b);
1100 tri_vertices.push(v.color.a);
1101 }
1102 for &idx in indices {
1104 tri_indices.push(tri_base_vertex + idx);
1105 }
1106 tri_base_vertex += vertices.len() as u32;
1107 if !vertices.is_empty() && !indices.is_empty() {
1108 push_range_op(&mut ops, DrawOp::Tri(idx_start, tri_indices.len() as u32));
1109 }
1110 }
1111 PaintCommand::Text { text, range, font_size, color, position, max_width } => {
1114 let mut temp_list = PaintList::new();
1115 crate::text::paint_text_span(text, *range, *font_size, *color, *position, &mut temp_list, *max_width);
1116 let snap = |v: f32| (v * dpr).round() / dpr;
1118 let start = texts.len() as u32;
1119 for cmd in temp_list.commands {
1120 if let PaintCommand::TexturedRect { rect, color, uv, texture_id: 0, .. } = cmd {
1121 if rect_intersects_clip(&rect, cur_clip) {
1122 texts.push(TextInstance {
1123 rect: [
1124 snap(rect.x),
1125 snap(rect.y),
1126 snap(rect.x + rect.width) - snap(rect.x),
1127 snap(rect.y + rect.height) - snap(rect.y),
1128 ],
1129 color: [color.r, color.g, color.b, color.a],
1130 uv,
1131 mode: 0.0,
1133 _pad: [0.0; 3],
1134 });
1135 }
1136 }
1137 }
1138 if texts.len() as u32 > start {
1139 push_range_op(&mut ops, DrawOp::Text(start, texts.len() as u32));
1140 }
1141 }
1142 }
1143 }
1144 close_segment!();
1146 let _ = (seg_r, seg_t, seg_i); let mut merged: Vec<ClipSegment> = Vec::with_capacity(segments.len());
1152 for seg in segments.drain(..) {
1153 let can_merge = merged.last().is_some_and(|prev: &ClipSegment| {
1154 prev.scissor == seg.scissor && prev.stencil_level == seg.stencil_level && seg.stencil_actions.is_empty()
1155 });
1156 if can_merge {
1157 let prev = merged.last_mut().expect("checked non-empty");
1158 for op in &seg.ops {
1159 push_range_op(&mut prev.ops, *op);
1160 }
1161 prev.rect_range.1 = seg.rect_range.1;
1162 prev.text_range.1 = seg.text_range.1;
1163 prev.image_range.1 = seg.image_range.1;
1164 } else {
1165 merged.push(seg);
1166 }
1167 }
1168
1169 (rects, texts, image_groups, merged, tri_vertices, tri_indices, stencil_draws, backdrop_blurs)
1170}
1171
1172mod batches;
1185mod composition;
1186mod render;
1187mod setup;
1188#[cfg(test)]
1189mod tests;
1190
1191#[cfg(test)]
1192mod present_stats_tests {
1193 use super::*;
1194
1195 fn ms(v: u64) -> Duration {
1196 Duration::from_millis(v)
1197 }
1198
1199 #[test]
1203 fn the_first_present_invents_no_gap() {
1204 let mut s = PresentStats::default();
1205 s.record(1_000, 2_000, None, "Fifo", 2);
1206 assert_eq!(s.presents, 1, "present 本身要记上:屏幕上确实出新内容了");
1207 assert_eq!(s.gaps, 0, "没有前驱就不许有间隔");
1208 assert_eq!((s.last_gap_ns, s.gap_sum_ns, s.gap_max_ns), (0, 0, 0));
1209 assert_eq!(s.mean_gap_ns(), 0, "均值给 0 只允许配着 gaps == 0 读");
1210
1211 s.record(1_000, 2_000, Some(ms(33)), "Fifo", 2);
1212 assert_eq!(s.gaps, 1, "第二个 present 才产生第一个间隔");
1213 assert_eq!(s.last_gap_ns, 33_000_000);
1214 }
1215
1216 #[test]
1218 fn gap_stats_tally_count_max_and_mean_separately() {
1219 let mut s = PresentStats::default();
1220 s.record(0, 0, None, "Fifo", 2);
1221 for gap in [ms(16), ms(33), ms(99)] {
1222 s.record(0, 0, Some(gap), "Fifo", 2);
1223 }
1224 assert_eq!(s.presents, 4);
1225 assert_eq!(s.gaps, 3);
1226 assert_eq!(s.gap_max_ns, 99_000_000, "最坏那一顿必须单独看得见,不能被均值抹平");
1227 assert_eq!(s.mean_gap_ns(), (16 + 33 + 99) * 1_000_000 / 3);
1228 }
1229
1230 #[test]
1233 fn waiting_for_the_display_and_submitting_are_two_different_numbers() {
1234 let mut s = PresentStats::default();
1235 s.record(4_000_000, 300_000, None, "Fifo", 2);
1236 s.record(3_000_000, 200_000, Some(ms(33)), "Fifo", 2);
1237 assert_eq!(s.wait_ns, 7_000_000);
1238 assert_eq!(s.submit_ns, 500_000);
1239 assert_ne!(s.wait_ns, s.submit_ns, "两问合一之后,任何一条归因都无从下手");
1240 }
1241
1242 #[test]
1245 fn an_unwired_path_says_so_instead_of_looking_idle() {
1246 let unwired = PresentStats::default();
1247 assert_eq!(unwired.present_mode, "", "没接线的形式必须是可识别的,而不是恰好等于一个合法的零");
1248 assert_eq!(unwired.presents, 0);
1249 let mut wired = PresentStats::default();
1250 wired.record(1, 1, None, "Mailbox", 1);
1251 assert_eq!((wired.present_mode, wired.max_frame_latency), ("Mailbox", 1));
1252 assert_ne!(PresentStats::default().present_mode, wired.present_mode);
1253 }
1254}