1use mgui_core::paint::{BlendMode, TextureMode};
2use mgui_core::Rect;
3use mgui_core::{
4 effect_flags, CacheInvalidationReason, CacheStats, FramePaint, LayerEffect, LayerId, LayerPaint, PaintCommand,
5 PaintList, RRectDef, Size,
6};
7use std::cell::RefCell;
8use std::collections::HashMap;
9use std::rc::Rc;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::time::{Duration, Instant};
12
13use wgpu::util::DeviceExt;
14
15static INCREMENTAL_LAYER_CACHE: AtomicBool = AtomicBool::new(false);
18
19pub fn set_incremental_layer_cache_enabled(on: bool) {
21 INCREMENTAL_LAYER_CACHE.store(on, Ordering::SeqCst);
22}
23
24pub fn incremental_layer_cache_enabled() -> bool {
26 INCREMENTAL_LAYER_CACHE.load(Ordering::SeqCst)
27}
28
29#[repr(C)]
32#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
33pub(crate) struct RectBatchUniform {
34 screen_size: [f32; 2], count: u32, _pad: [f32; 1], }
38
39#[repr(C)]
47#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
48pub(crate) struct RectInstance {
49 rect: [f32; 4],
50 from: [f32; 4],
51 to: [f32; 4],
52 grad: [f32; 4],
53 params: [f32; 4],
55}
56
57#[repr(C)]
59#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
60pub(crate) struct TextBatchUniform {
61 screen_size: [f32; 2], count: u32, _pad: [f32; 1], }
65
66#[repr(C)]
70#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
71pub(crate) struct TextInstance {
72 rect: [f32; 4], color: [f32; 4], uv: [f32; 4], mode: f32, _pad: [f32; 3], }
80
81#[repr(C)]
92#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
93pub(crate) struct BlitUniform {
94 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], }
123struct LayerGpuCache {
127 resolve_texture: wgpu::Texture,
129 resolve_view: wgpu::TextureView,
131 cached_size: (u32, u32),
133 content_key: u64,
136}
137
138#[derive(Clone)]
143pub struct RendererShared {
144 rect_pipelines: [wgpu::RenderPipeline; 4],
146 rect_bgl: wgpu::BindGroupLayout,
147 text_pipeline: wgpu::RenderPipeline,
148 text_bgl: wgpu::BindGroupLayout,
149 text_pipeline_mask: wgpu::RenderPipeline,
151 text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
152 tri_pipeline: wgpu::RenderPipeline,
153 tri_bgl: wgpu::BindGroupLayout,
154 tri_pipeline_stencil_inc: wgpu::RenderPipeline,
156 tri_pipeline_stencil_dec: wgpu::RenderPipeline,
157 rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
158 text_pipeline_stencil_test: wgpu::RenderPipeline,
159 tri_pipeline_stencil_test: wgpu::RenderPipeline,
160 blit_pipeline: wgpu::RenderPipeline,
161 blit_bgl: wgpu::BindGroupLayout,
162 blit_sampler: wgpu::Sampler,
163 backdrop_pipeline: wgpu::RenderPipeline,
165 backdrop_bgl: wgpu::BindGroupLayout,
166 format: wgpu::TextureFormat,
167 atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
168 image_cache: Rc<RefCell<ImageTextureCache>>,
169}
170
171#[derive(Default)]
173pub(crate) struct ImageTextureCache {
174 textures: HashMap<u32, ImageTextureEntry>,
175 clock: u64,
176 generations: HashMap<u32, u64>,
179 evict_enabled: bool,
181}
182
183impl RendererShared {
184 pub fn format(&self) -> wgpu::TextureFormat {
185 self.format
186 }
187
188 pub fn evict_images(&self, protected: &std::collections::HashSet<u32>) {
191 self.image_cache.borrow_mut().evict_to_budget(protected);
192 }
193}
194
195impl ImageTextureCache {
196 pub(crate) fn generation(&self, texture_id: u32) -> u64 {
198 self.generations.get(&texture_id).copied().unwrap_or(0)
199 }
200
201 fn evict_to_budget(&mut self, protected: &std::collections::HashSet<u32>) {
202 let budget = IMAGE_TEXTURE_BUDGET_BYTES;
203 let mut total: u64 = self.textures.values().map(|e| e.bytes).sum();
204 if total <= budget {
205 return;
206 }
207 let mut candidates: Vec<(u32, u64, u64)> = self
208 .textures
209 .iter()
210 .filter(|(id, _)| !protected.contains(id))
211 .map(|(&id, e)| (id, e.last_used, e.bytes))
212 .collect();
213 candidates.sort_unstable_by_key(|&(_, last_used, _)| last_used);
214 for (id, _, bytes) in candidates {
215 if total <= budget {
216 break;
217 }
218 self.textures.remove(&id);
219 total = total.saturating_sub(bytes);
220 }
221 if total > budget {
222 log::warn!(
223 target: "mgui_startup",
224 "shared image cache uses {} MiB (budget {} MiB); all remaining textures are in use",
225 total / (1024 * 1024),
226 budget / (1024 * 1024)
227 );
228 }
229 }
230}
231
232#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
233pub struct PresentStats {
234 pub presents: u64,
237 pub wait_ns: u64,
240 pub submit_ns: u64,
242 pub gaps: u64,
245 pub gap_sum_ns: u64,
246 pub gap_max_ns: u64,
247 pub last_gap_ns: u64,
249 pub present_mode: &'static str,
257 pub max_frame_latency: u32,
259 pub present_path_cpu_ns: u64,
262 pub redraw_cpu_ns: u64,
264 pub last_present_path_cpu_ns: u64,
266 pub last_redraw_cpu_ns: u64,
267 pub frame_to_acquire_ns: u64,
271 pub acquire_to_submit_ns: u64,
274 pub last_frame_to_acquire_ns: u64,
275 pub last_acquire_to_submit_ns: u64,
276}
277
278impl PresentStats {
279 pub fn record(&mut self, wait_ns: u64, submit_ns: u64, gap: Option<Duration>, mode: &'static str, latency: u32) {
284 self.presents = self.presents.saturating_add(1);
285 self.wait_ns = self.wait_ns.saturating_add(wait_ns);
286 self.submit_ns = self.submit_ns.saturating_add(submit_ns);
287 self.present_mode = mode;
288 self.max_frame_latency = latency;
289 if let Some(gap) = gap {
290 let ns = gap.as_nanos() as u64;
291 self.gaps = self.gaps.saturating_add(1);
292 self.gap_sum_ns = self.gap_sum_ns.saturating_add(ns);
293 self.gap_max_ns = self.gap_max_ns.max(ns);
294 self.last_gap_ns = ns;
295 }
296 }
297
298 pub fn mean_gap_ns(&self) -> u64 {
300 self.gap_sum_ns.checked_div(self.gaps).unwrap_or(0)
301 }
302}
303
304pub(crate) struct TextureUploadRecord {
312 pub outcome: mgui_core::image::TextureUpdate,
313 pub source_bytes: u64,
315 pub active_bytes: u64,
316 pub write_ns: u64,
318 pub width: u32,
321 pub height: u32,
322 pub meta: Option<mgui_core::paint::TextureFrameMeta>,
323}
324
325impl TextureUploadRecord {
326 pub(crate) fn outcome_code(&self) -> u8 {
328 use mgui_core::image::TextureUpdate;
329 match self.outcome {
330 TextureUpdate::Reuse => 1,
331 TextureUpdate::UpdateContent => 2,
332 TextureUpdate::Recreate => 3,
333 }
334 }
335}
336
337#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
338pub struct RenderStats {
339 pub layers_painted: u32,
341 pub cache: CacheStats,
344 pub segments: u32,
346 pub draw_calls: u32,
348 pub scratch_bytes: u64,
350 pub layer_texture_bytes: u64,
352 pub upload_ns: u64,
361 pub upload_write_ns: u64,
363 pub last_upload_width: u32,
365 pub last_upload_height: u32,
366 pub upload_source_bytes: u64,
368 pub upload_active_bytes: u64,
370 pub upload_count: u32,
372 pub texture_decl_count: u32,
374 pub texture_reuse_count: u32,
375 pub texture_update_count: u32,
376 pub texture_recreate_count: u32,
377 pub stale_decl_count: u32,
380 pub unsynced_decl_count: u32,
382 pub last_frame_sequence: u64,
385 pub last_frame_generation: u64,
386 pub last_frame_age_ns: u64,
387 pub last_frame_synced_seq: u64,
389 pub last_frame_latest_seq: u64,
390 pub last_frame_outcome: u8,
392 pub last_frame_encoder: u8,
394}
395
396pub struct Renderer {
397 rect_pipelines: [wgpu::RenderPipeline; 4],
399 rect_bgl: wgpu::BindGroupLayout,
400 text_pipeline: wgpu::RenderPipeline,
401 text_bgl: wgpu::BindGroupLayout,
402 text_pipeline_mask: wgpu::RenderPipeline,
404 text_pipeline_mask_stencil_test: wgpu::RenderPipeline,
405 tri_pipeline: wgpu::RenderPipeline,
407 tri_bgl: wgpu::BindGroupLayout,
408 tri_pipeline_stencil_inc: wgpu::RenderPipeline,
412 tri_pipeline_stencil_dec: wgpu::RenderPipeline,
413 rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4],
414 text_pipeline_stencil_test: wgpu::RenderPipeline,
415 tri_pipeline_stencil_test: wgpu::RenderPipeline,
416 atlas_cache: Rc<RefCell<Option<AtlasGpu>>>,
418 layer_cache: HashMap<LayerId, LayerGpuCache>,
420 active_layer_ids: std::collections::HashSet<LayerId>,
422 frame_layer_sizes: HashMap<LayerId, Size>,
424 composition_scratch: mgui_core::CompositionScratch,
426 blit_pipeline: wgpu::RenderPipeline,
428 blit_bgl: wgpu::BindGroupLayout,
429 blit_sampler: wgpu::Sampler,
430 backdrop_pipeline: wgpu::RenderPipeline,
432 backdrop_bgl: wgpu::BindGroupLayout,
433 format: wgpu::TextureFormat,
435 pub gpu_profiler: Option<crate::gpu_profiler::GpuProfiler>,
437 batch_pools: HashMap<(LayerId, u32), LayerBatchPool>,
446 image_cache: Rc<RefCell<ImageTextureCache>>,
448 msaa_scratch: HashMap<(u32, u32), wgpu::TextureView>,
450 stencil_scratch: HashMap<(u32, u32), wgpu::TextureView>,
451 snapshot_scratch: HashMap<(u32, u32), (wgpu::Texture, wgpu::TextureView)>,
452 last_stats: RenderStats,
454 pending_invalidations: [u32; 9],
456 pending_invalidation_start: Option<Instant>,
458 cache_high_watermark_bytes: u64,
460 pending_upload: Option<(Vec<TextureUploadRecord>, u64)>,
465}
466
467pub(crate) struct ImageTextureEntry {
469 pub _texture: wgpu::Texture,
471 pub view: wgpu::TextureView,
472 pub sampler: wgpu::Sampler,
473 pub last_used: u64,
475 pub bytes: u64,
477 pub source: Rc<mgui_core::image::ImageData>,
480 pub size: (u32, u32),
482}
483
484pub const IMAGE_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
486
487pub use setup::LAYER_TEXTURE_BUDGET_BYTES;
489
490pub use mgui_core::inspect::ImageTextureStats;
491
492impl Renderer {
493 pub fn last_stats(&self) -> RenderStats {
495 self.last_stats
496 }
497
498 pub fn note_cache_invalidation(&mut self, reason: CacheInvalidationReason) {
501 if !mgui_core::frame::cache_stats_collecting() {
502 return;
503 }
504 let now = Instant::now();
505 if self.pending_invalidation_start.is_none() {
506 self.pending_invalidation_start = Some(now);
507 }
508 let slot = reason as usize;
509 self.pending_invalidations[slot] = self.pending_invalidations[slot].saturating_add(1);
510 }
511
512 pub fn image_texture_stats(&self) -> ImageTextureStats {
514 let cache = self.image_cache.borrow();
515 ImageTextureStats {
516 count: cache.textures.len(),
517 bytes: cache.textures.values().map(|e| e.bytes).sum(),
518 budget_bytes: IMAGE_TEXTURE_BUDGET_BYTES,
519 }
520 }
521}
522
523struct LayerBatchPool {
525 rect_header: Option<wgpu::Buffer>,
526 rect_instances: Option<wgpu::Buffer>,
527 text_header: Option<wgpu::Buffer>,
528 text_instances: Option<wgpu::Buffer>,
529 tri_vertex: Option<wgpu::Buffer>,
531 tri_index: Option<wgpu::Buffer>,
532 tri_uniform: Option<wgpu::Buffer>,
533 stencil_vertex: Option<wgpu::Buffer>,
536 stencil_index: Option<wgpu::Buffer>,
537}
538
539pub(crate) struct AtlasGpu {
541 texture: wgpu::Texture,
542 view: wgpu::TextureView,
543 sampler: wgpu::Sampler,
544 cached_size: (u32, u32),
546}
547
548pub(crate) struct RectBatch {
549 bg: wgpu::BindGroup,
550}
551
552pub(crate) struct TriBatch {
554 bg: wgpu::BindGroup,
555}
556
557#[repr(C)]
559#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
560struct TriUniform {
561 screen_size: [f32; 2],
562 _pad0: u32,
563 _pad1: u32,
564}
565
566#[repr(C)]
568#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
569struct BackdropUniform {
570 screen: [f32; 2],
571 _pad: [f32; 2],
572 rect: [f32; 4],
573 params: [f32; 4],
575 tint: [f32; 4],
577}
578
579pub(crate) struct TextBatch {
581 bg: wgpu::BindGroup,
582 count: u32,
583}
584
585#[derive(Debug, Clone, Default)]
591pub(crate) struct StencilDraw {
592 pub vertices: Vec<f32>,
594 pub indices: Vec<u32>,
595}
596
597#[derive(Debug, Clone, Copy, PartialEq, Eq)]
602pub(crate) struct StencilAction {
603 pub draw: u32,
605 pub level: u32,
607 pub increment: bool,
608}
609
610pub(crate) struct StencilGpu {
612 pub vertex: wgpu::Buffer,
613 pub index: wgpu::Buffer,
614 pub ranges: Vec<(u32, u32)>,
615 pub bg: wgpu::BindGroup,
616}
617
618#[derive(Debug, Clone, Copy)]
620pub(crate) struct BackdropBlurSpec {
621 pub rect: Rect,
622 pub radius: f32,
623 pub blur_radius: f32,
624 pub tint: [f32; 4],
625}
626
627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
629pub(crate) enum DrawOp {
630 Rect(u32, u32, BlendMode),
632 Text(u32, u32),
634 Image(u32),
636 Mask(u32),
638 BackdropBlur(u32),
640 Tri(u32, u32),
642}
643
644#[derive(Debug, Clone, PartialEq)]
650pub(crate) struct ClipSegment {
651 pub scissor: Option<[u32; 4]>,
653 pub ops: Vec<DrawOp>,
655 pub rect_range: (u32, u32),
657 pub text_range: (u32, u32),
658 pub image_range: (u32, u32),
659 pub stencil_level: u32,
661 pub stencil_actions: Vec<StencilAction>,
663}
664
665pub(crate) struct ImageGroup {
668 pub texture_id: u32,
669 pub instances: Vec<TextInstance>,
670}
671
672pub(crate) struct ImageBatchDraw {
678 pub(crate) batch: TextBatch,
679}
680
681fn intersect_rect(a: Rect, b: Rect) -> Rect {
683 let x1 = a.x.max(b.x);
684 let y1 = a.y.max(b.y);
685 let x2 = (a.x + a.width).min(b.x + b.width);
686 let y2 = (a.y + a.height).min(b.y + b.height);
687 Rect::new(x1, y1, (x2 - x1).max(0.0), (y2 - y1).max(0.0))
688}
689
690fn path_bounding_box(vertices: &[mgui_core::paint::Vertex]) -> Rect {
692 if vertices.is_empty() {
693 return Rect::new(0.0, 0.0, 0.0, 0.0);
694 }
695 let mut min_x = f32::INFINITY;
696 let mut min_y = f32::INFINITY;
697 let mut max_x = f32::NEG_INFINITY;
698 let mut max_y = f32::NEG_INFINITY;
699 for v in vertices {
700 min_x = min_x.min(v.x);
701 min_y = min_y.min(v.y);
702 max_x = max_x.max(v.x);
703 max_y = max_y.max(v.y);
704 }
705 Rect::new(min_x, min_y, (max_x - min_x).max(0.0), (max_y - min_y).max(0.0))
706}
707
708fn rect_intersects_clip(r: &Rect, clip: Option<Rect>) -> bool {
710 match clip {
711 None => true,
712 Some(c) => {
714 c.width > 0.0
715 && c.height > 0.0
716 && r.x < c.x + c.width
717 && r.x + r.width > c.x
718 && r.y < c.y + c.height
719 && r.y + r.height > c.y
720 }
721 }
722}
723
724fn rounded_rect_stencil_mesh(rect: Rect, radius: f32) -> (Vec<f32>, Vec<u32>) {
729 if rect.width <= 0.0 || rect.height <= 0.0 {
730 return (Vec::new(), Vec::new());
731 }
732 let (x, y, w, h) = (rect.x, rect.y, rect.width, rect.height);
733 let r = radius.max(0.0).min(w.min(h) * 0.5);
734
735 let mut pts: Vec<(f32, f32)> = Vec::new();
736 if r <= 0.0 {
737 pts.extend_from_slice(&[(x, y), (x + w, y), (x + w, y + h), (x, y + h)]);
738 } else {
739 const SEG: u32 = 8;
740 let arcs = [
742 (x + w - r, y + r, -std::f32::consts::FRAC_PI_2, 0.0),
743 (x + w - r, y + h - r, 0.0, std::f32::consts::FRAC_PI_2),
744 (x + r, y + h - r, std::f32::consts::FRAC_PI_2, std::f32::consts::PI),
745 (x + r, y + r, std::f32::consts::PI, 3.0 * std::f32::consts::FRAC_PI_2),
746 ];
747 for &(cx, cy, a0, a1) in &arcs {
748 for i in 0..=SEG {
749 let a = a0 + (a1 - a0) * (i as f32 / SEG as f32);
750 pts.push((cx + r * a.cos(), cy + r * a.sin()));
751 }
752 }
753 if pts.len() > 1 && pts.first() == pts.last() {
755 pts.pop();
756 }
757 }
758 pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-5 && (a.1 - b.1).abs() < 1e-5);
759
760 let n = pts.len();
761 if n < 3 {
762 return (Vec::new(), Vec::new());
763 }
764 let mut verts = Vec::with_capacity((n + 1) * 6);
765 for &(px, py) in &pts {
766 verts.extend_from_slice(&[px, py, 1.0, 1.0, 1.0, 1.0]);
767 }
768 verts.extend_from_slice(&[x + w * 0.5, y + h * 0.5, 1.0, 1.0, 1.0, 1.0]);
769 let center = n as u32;
770 let mut indices = Vec::with_capacity(n * 3);
771 for i in 0..n as u32 {
772 indices.extend_from_slice(&[center, i, (i + 1) % n as u32]);
773 }
774 (verts, indices)
775}
776
777fn clip_to_scissor_px(r: Rect, dpr: f32, tex: (u32, u32)) -> [u32; 4] {
779 let d = dpr.max(0.0);
780 let (tw, th) = (tex.0 as f32, tex.1 as f32);
781 let x0 = (r.x * d).floor().clamp(0.0, tw);
784 let y0 = (r.y * d).floor().clamp(0.0, th);
785 let x1 = ((r.x + r.width) * d).ceil().clamp(0.0, tw).max(x0);
786 let y1 = ((r.y + r.height) * d).ceil().clamp(0.0, th).max(y0);
787 let x = x0 as u32;
788 let y = y0 as u32;
789 let w = (x1 as u32).saturating_sub(x);
790 let h = (y1 as u32).saturating_sub(y);
791 [x, y, w, h]
792}
793
794type CollectedInstances = (
809 Vec<RectInstance>,
810 Vec<TextInstance>,
811 Vec<ImageGroup>,
812 Vec<ClipSegment>,
813 Vec<f32>, Vec<u32>, Vec<StencilDraw>,
818 Vec<BackdropBlurSpec>,
820);
821
822pub(crate) fn collect_instances_segmented(
823 paint_list: &PaintList,
824 dpr: f32,
825 tex_size: (u32, u32),
826) -> CollectedInstances {
827 let mut rects: Vec<RectInstance> = Vec::new();
828 let mut texts: Vec<TextInstance> = Vec::new();
829 let mut image_groups: Vec<ImageGroup> = Vec::new();
830 let mut segments: Vec<ClipSegment> = Vec::new();
831 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();
837 let mut pending_stencil: Vec<StencilAction> = Vec::new();
838 let mut backdrop_blurs: Vec<BackdropBlurSpec> = Vec::new();
839 let mut path_draw_stack: Vec<Option<u32>> = Vec::new();
840 let mut clip_depth: u32 = 0;
841 let mut blend_stack: Vec<BlendMode> = Vec::new();
843 let mut cur_blend = BlendMode::Normal;
844 let mut stack: Vec<(Option<Rect>, bool)> = Vec::new();
846 let mut cur_clip: Option<Rect> = None;
847 let (mut seg_r, mut seg_t, mut seg_i): (u32, u32, u32) = (0, 0, 0);
848 let mut ops: Vec<DrawOp> = Vec::new();
850
851 macro_rules! close_segment {
853 () => {
854 let r_end = rects.len() as u32;
855 let t_end = texts.len() as u32;
856 let i_end = image_groups.len() as u32;
857 if !ops.is_empty() {
858 segments.push(ClipSegment {
859 scissor: cur_clip.map(|c| clip_to_scissor_px(c, dpr, tex_size)),
860 ops: ops.clone(),
861 rect_range: (seg_r, r_end),
862 text_range: (seg_t, t_end),
863 image_range: (seg_i, i_end),
864 stencil_level: clip_depth,
865 stencil_actions: std::mem::take(&mut pending_stencil),
868 });
869 ops.clear();
870 }
871 seg_r = r_end;
872 seg_t = t_end;
873 seg_i = i_end;
874 };
875 }
876
877 fn push_range_op(ops: &mut Vec<DrawOp>, op: DrawOp) {
878 match op {
879 DrawOp::Rect(s, e, mode) => {
880 if let Some(DrawOp::Rect(_, last_end, last_mode)) = ops.last_mut() {
881 if *last_end == s && *last_mode == mode {
882 *last_end = e;
883 return;
884 }
885 }
886 }
887 DrawOp::Text(s, e) => {
888 if let Some(DrawOp::Text(_, last_end)) = ops.last_mut() {
889 if *last_end == s {
890 *last_end = e;
891 return;
892 }
893 }
894 }
895 DrawOp::Tri(s, e) => {
896 if let Some(DrawOp::Tri(_, last_end)) = ops.last_mut() {
897 if *last_end == s {
898 *last_end = e;
899 return;
900 }
901 }
902 }
903 DrawOp::Image(_) => {}
904 DrawOp::Mask(_) => {}
905 DrawOp::BackdropBlur(_) => {}
906 }
907 ops.push(op);
908 }
909
910 macro_rules! push_mask_clip {
912 ($flat:expr, $idxs:expr, $bbox:expr) => {{
913 clip_depth += 1;
914 let flat_verts: Vec<f32> = $flat;
915 let idxs: &[u32] = $idxs;
916 let draw_index = if !flat_verts.is_empty() && !idxs.is_empty() {
917 let idx = stencil_draws.len() as u32;
918 stencil_draws.push(StencilDraw { vertices: flat_verts, indices: idxs.to_vec() });
919 pending_stencil.push(StencilAction { draw: idx, level: clip_depth, increment: true });
920 Some(idx)
921 } else {
922 None
923 };
924 path_draw_stack.push(draw_index);
925
926 let bbox: Rect = $bbox;
927 stack.push((cur_clip, true));
928 cur_clip = Some(match cur_clip {
929 Some(outer) => intersect_rect(outer, bbox),
930 None => bbox,
931 });
932 }};
933 }
934
935 macro_rules! pop_mask_clip {
937 () => {{
938 if let Some(Some(draw)) = path_draw_stack.pop() {
939 pending_stencil.push(StencilAction { draw, level: clip_depth, increment: false });
941 }
942 clip_depth = clip_depth.saturating_sub(1);
943 }};
944 }
945
946 for cmd in &paint_list.commands {
947 match cmd {
948 PaintCommand::PushBlendMode(mode) => {
949 blend_stack.push(cur_blend);
950 cur_blend = *mode;
951 }
952 PaintCommand::PopBlendMode => {
953 cur_blend = blend_stack.pop().unwrap_or(BlendMode::Normal);
954 }
955 PaintCommand::PushClip(r) => {
956 close_segment!();
957 stack.push((cur_clip, false));
958 cur_clip = Some(match cur_clip {
959 Some(outer) => intersect_rect(outer, *r),
960 None => *r,
961 });
962 }
963 PaintCommand::PushClipRRect { rect, radius } => {
964 close_segment!();
965 let (flat_verts, idxs) = rounded_rect_stencil_mesh(*rect, *radius);
966 push_mask_clip!(flat_verts, &idxs, *rect);
967 }
968 PaintCommand::PopClip => {
969 close_segment!();
970 let (prev, is_mask) = stack.pop().unwrap_or((None, false));
971 if is_mask {
972 pop_mask_clip!();
973 }
974 cur_clip = prev;
975 }
976 PaintCommand::PushClipPath { vertices, indices } => {
978 close_segment!();
979 let mut flat_verts: Vec<f32> = Vec::with_capacity(vertices.len() * 6);
980 for v in vertices {
981 flat_verts.push(v.x);
982 flat_verts.push(v.y);
983 flat_verts.push(v.color.r);
984 flat_verts.push(v.color.g);
985 flat_verts.push(v.color.b);
986 flat_verts.push(v.color.a);
987 }
988 push_mask_clip!(flat_verts, indices, path_bounding_box(vertices));
989 }
990 PaintCommand::PopClipPath => {
991 close_segment!();
992 let (prev, is_mask) = stack.pop().unwrap_or((None, false));
993 if is_mask {
994 pop_mask_clip!();
995 }
996 cur_clip = prev;
997 }
998 PaintCommand::Rect { rect, color, radius } => {
999 if rect_intersects_clip(rect, cur_clip) {
1000 let start = rects.len() as u32;
1001 rects.push(RectInstance {
1002 rect: [rect.x, rect.y, rect.width, rect.height],
1003 from: [color.r, color.g, color.b, color.a],
1004 to: [color.r, color.g, color.b, color.a],
1005 grad: [0.0; 4],
1006 params: [*radius, 0.0, 0.0, 0.0],
1007 });
1008 push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
1009 }
1010 }
1011 PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
1013 if rect_intersects_clip(rect, cur_clip) {
1014 let start = rects.len() as u32;
1015 rects.push(RectInstance {
1016 rect: [rect.x, rect.y, rect.width, rect.height],
1017 from: [color.r, color.g, color.b, color.a],
1018 to: [color.r, color.g, color.b, color.a],
1019 grad: [0.0; 4],
1020 params: [*radius, 0.0, *blur_radius, 0.0],
1021 });
1022 push_range_op(&mut ops, DrawOp::Rect(start, start + 1, cur_blend));
1023 }
1024 }
1025 PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
1027 if rect_intersects_clip(rect, cur_clip) {
1028 let idx = rects.len() as u32;
1029 rects.push(RectInstance {
1030 rect: [rect.x, rect.y, rect.width, rect.height],
1031 from: [color.r, color.g, color.b, color.a],
1032 to: [color.r, color.g, color.b, color.a],
1033 grad: [0.0; 4],
1034 params: [*radius, 3.0, *blur_radius, 0.0],
1035 });
1036 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
1037 }
1038 }
1039 PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
1040 if rect_intersects_clip(rect, cur_clip) {
1041 let idx = rects.len() as u32;
1042 rects.push(RectInstance {
1043 rect: [rect.x, rect.y, rect.width, rect.height],
1044 from: [from.r, from.g, from.b, from.a],
1045 to: [to.r, to.g, to.b, to.a],
1046 grad: [start.x, start.y, end.x, end.y],
1047 params: [*corner_radius, 1.0, 0.0, 0.0],
1048 });
1049 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
1050 }
1051 }
1052 PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
1053 if rect_intersects_clip(rect, cur_clip) {
1054 let idx = rects.len() as u32;
1055 rects.push(RectInstance {
1056 rect: [rect.x, rect.y, rect.width, rect.height],
1057 from: [from.r, from.g, from.b, from.a],
1058 to: [to.r, to.g, to.b, to.a],
1059 grad: [center.x, center.y, *radial_radius, 0.0],
1060 params: [*corner_radius, 2.0, 0.0, 0.0],
1061 });
1062 push_range_op(&mut ops, DrawOp::Rect(idx, idx + 1, cur_blend));
1063 }
1064 }
1065 PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
1067 if rect_intersects_clip(rect, cur_clip) {
1068 let idx = backdrop_blurs.len() as u32;
1069 backdrop_blurs.push(BackdropBlurSpec {
1070 rect: *rect,
1071 radius: *radius,
1072 blur_radius: *blur_radius,
1073 tint: [tint.r, tint.g, tint.b, tint.a],
1074 });
1075 ops.push(DrawOp::BackdropBlur(idx));
1076 }
1077 }
1078 PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
1080 if *alpha > 0.0 && rect_intersects_clip(rect, cur_clip) {
1081 let gi = image_groups.len() as u32;
1082 image_groups.push(ImageGroup {
1083 texture_id: *texture_id,
1084 instances: vec![TextInstance {
1085 rect: [rect.x, rect.y, rect.width, rect.height],
1086 color: [1.0, 1.0, 1.0, alpha.clamp(0.0, 1.0)],
1088 uv: *uv,
1089 mode: 2.0,
1090 _pad: [0.0; 3],
1091 }],
1092 });
1093 ops.push(DrawOp::Mask(gi));
1094 }
1095 }
1096 PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
1097 if rect_intersects_clip(rect, cur_clip) {
1098 let snap = |v: f32| (v * dpr).round() / dpr;
1101 let inst = TextInstance {
1102 rect: [
1103 snap(rect.x),
1104 snap(rect.y),
1105 snap(rect.x + rect.width) - snap(rect.x),
1106 snap(rect.y + rect.height) - snap(rect.y),
1107 ],
1108 color: [color.r, color.g, color.b, color.a],
1109 uv: *uv,
1110 mode: match mode {
1111 TextureMode::Mask => 0.0,
1112 TextureMode::Color => 1.0,
1113 },
1114 _pad: [0.0; 3],
1115 };
1116 if *texture_id == 0 {
1117 let start = texts.len() as u32;
1118 texts.push(inst);
1119 push_range_op(&mut ops, DrawOp::Text(start, start + 1));
1120 } else {
1121 let reuse_group = ops
1125 .last()
1126 .and_then(|op| match op {
1127 DrawOp::Image(gi) => Some(*gi),
1128 _ => None,
1129 })
1130 .filter(|&gi| image_groups[gi as usize].texture_id == *texture_id);
1131 if let Some(gi) = reuse_group {
1132 image_groups[gi as usize].instances.push(inst);
1133 } else {
1134 let gi = image_groups.len() as u32;
1135 image_groups.push(ImageGroup { texture_id: *texture_id, instances: vec![inst] });
1136 ops.push(DrawOp::Image(gi));
1137 }
1138 }
1139 }
1140 }
1141 PaintCommand::Triangles { vertices, indices } => {
1144 let idx_start = tri_indices.len() as u32;
1145 for v in vertices {
1147 tri_vertices.push(v.x);
1148 tri_vertices.push(v.y);
1149 tri_vertices.push(v.color.r);
1150 tri_vertices.push(v.color.g);
1151 tri_vertices.push(v.color.b);
1152 tri_vertices.push(v.color.a);
1153 }
1154 for &idx in indices {
1156 tri_indices.push(tri_base_vertex + idx);
1157 }
1158 tri_base_vertex += vertices.len() as u32;
1159 if !vertices.is_empty() && !indices.is_empty() {
1160 push_range_op(&mut ops, DrawOp::Tri(idx_start, tri_indices.len() as u32));
1161 }
1162 }
1163 PaintCommand::Text { text, range, font_size, color, position, max_width } => {
1166 let mut temp_list = PaintList::new();
1167 crate::text::paint_text_span(text, *range, *font_size, *color, *position, &mut temp_list, *max_width);
1168 let snap = |v: f32| (v * dpr).round() / dpr;
1170 let start = texts.len() as u32;
1171 for cmd in temp_list.commands {
1172 if let PaintCommand::TexturedRect { rect, color, uv, texture_id: 0, .. } = cmd {
1173 if rect_intersects_clip(&rect, cur_clip) {
1174 texts.push(TextInstance {
1175 rect: [
1176 snap(rect.x),
1177 snap(rect.y),
1178 snap(rect.x + rect.width) - snap(rect.x),
1179 snap(rect.y + rect.height) - snap(rect.y),
1180 ],
1181 color: [color.r, color.g, color.b, color.a],
1182 uv,
1183 mode: 0.0,
1185 _pad: [0.0; 3],
1186 });
1187 }
1188 }
1189 }
1190 if texts.len() as u32 > start {
1191 push_range_op(&mut ops, DrawOp::Text(start, texts.len() as u32));
1192 }
1193 }
1194 }
1195 }
1196 close_segment!();
1198 let _ = (seg_r, seg_t, seg_i); let mut merged: Vec<ClipSegment> = Vec::with_capacity(segments.len());
1204 for seg in segments.drain(..) {
1205 let can_merge = merged.last().is_some_and(|prev: &ClipSegment| {
1206 prev.scissor == seg.scissor && prev.stencil_level == seg.stencil_level && seg.stencil_actions.is_empty()
1207 });
1208 if can_merge {
1209 let prev = merged.last_mut().expect("checked non-empty");
1210 for op in &seg.ops {
1211 push_range_op(&mut prev.ops, *op);
1212 }
1213 prev.rect_range.1 = seg.rect_range.1;
1214 prev.text_range.1 = seg.text_range.1;
1215 prev.image_range.1 = seg.image_range.1;
1216 } else {
1217 merged.push(seg);
1218 }
1219 }
1220
1221 (rects, texts, image_groups, merged, tri_vertices, tri_indices, stencil_draws, backdrop_blurs)
1222}
1223
1224mod batches;
1237mod composition;
1238mod render;
1239mod setup;
1240#[cfg(test)]
1241mod tests;
1242
1243#[cfg(test)]
1244mod present_stats_tests {
1245 use super::*;
1246
1247 fn ms(v: u64) -> Duration {
1248 Duration::from_millis(v)
1249 }
1250
1251 #[test]
1255 fn the_first_present_invents_no_gap() {
1256 let mut s = PresentStats::default();
1257 s.record(1_000, 2_000, None, "Fifo", 2);
1258 assert_eq!(s.presents, 1, "present 本身要记上:屏幕上确实出新内容了");
1259 assert_eq!(s.gaps, 0, "没有前驱就不许有间隔");
1260 assert_eq!((s.last_gap_ns, s.gap_sum_ns, s.gap_max_ns), (0, 0, 0));
1261 assert_eq!(s.mean_gap_ns(), 0, "均值给 0 只允许配着 gaps == 0 读");
1262
1263 s.record(1_000, 2_000, Some(ms(33)), "Fifo", 2);
1264 assert_eq!(s.gaps, 1, "第二个 present 才产生第一个间隔");
1265 assert_eq!(s.last_gap_ns, 33_000_000);
1266 }
1267
1268 #[test]
1270 fn gap_stats_tally_count_max_and_mean_separately() {
1271 let mut s = PresentStats::default();
1272 s.record(0, 0, None, "Fifo", 2);
1273 for gap in [ms(16), ms(33), ms(99)] {
1274 s.record(0, 0, Some(gap), "Fifo", 2);
1275 }
1276 assert_eq!(s.presents, 4);
1277 assert_eq!(s.gaps, 3);
1278 assert_eq!(s.gap_max_ns, 99_000_000, "最坏那一顿必须单独看得见,不能被均值抹平");
1279 assert_eq!(s.mean_gap_ns(), (16 + 33 + 99) * 1_000_000 / 3);
1280 }
1281
1282 #[test]
1285 fn waiting_for_the_display_and_submitting_are_two_different_numbers() {
1286 let mut s = PresentStats::default();
1287 s.record(4_000_000, 300_000, None, "Fifo", 2);
1288 s.record(3_000_000, 200_000, Some(ms(33)), "Fifo", 2);
1289 assert_eq!(s.wait_ns, 7_000_000);
1290 assert_eq!(s.submit_ns, 500_000);
1291 assert_ne!(s.wait_ns, s.submit_ns, "两问合一之后,任何一条归因都无从下手");
1292 }
1293
1294 #[test]
1297 fn an_unwired_path_says_so_instead_of_looking_idle() {
1298 let unwired = PresentStats::default();
1299 assert_eq!(unwired.present_mode, "", "没接线的形式必须是可识别的,而不是恰好等于一个合法的零");
1300 assert_eq!(unwired.presents, 0);
1301 let mut wired = PresentStats::default();
1302 wired.record(1, 1, None, "Mailbox", 1);
1303 assert_eq!((wired.present_mode, wired.max_frame_latency), ("Mailbox", 1));
1304 assert_ne!(PresentStats::default().present_mode, wired.present_mode);
1305 }
1306}