1use super::composition::LayerComposition;
5use super::*;
6use mgui_core::paint::BlendMode;
7
8const STENCIL_FMT: wgpu::TextureFormat = wgpu::TextureFormat::Stencil8;
9
10pub const LAYER_TEXTURE_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
12
13pub(crate) type LayerTextureSize = (LayerId, (u32, u32));
15pub(crate) type LayerTextureTargets = (Vec<LayerTextureSize>, f32);
17
18fn layer_tex_size(logical: Option<Size>, dpr: f32, screen: (f32, f32), max_dim: u32) -> (u32, u32) {
20 let (w, h) = match logical {
21 Some(s) => (s.width, s.height),
22 None => screen,
23 };
24 let w = (w * dpr).ceil() as u32;
26 let h = (h * dpr).ceil() as u32;
27 (w.max(1).min(max_dim), h.max(1).min(max_dim))
28}
29
30fn layer_tex_total_bytes(sizes: &[LayerTextureSize]) -> u64 {
31 sizes.iter().map(|&(_, (w, h))| w as u64 * h as u64 * 4).sum()
32}
33
34pub(crate) fn layer_texture_targets(
44 layer_paints: &[LayerPaint],
45 dpr: f32,
46 screen_size: (f32, f32),
47 max_dim: u32,
48 budget: u64,
49) -> LayerTextureTargets {
50 let dpr = if dpr.is_finite() && dpr > 0.0 { dpr } else { 1.0 };
51 let max_dim = max_dim.max(1);
52 let compute = |scale: f32| -> Vec<LayerTextureSize> {
53 layer_paints
54 .iter()
55 .map(|lp| (lp.layer_id, layer_tex_size(lp.logical_size, dpr * scale, screen_size, max_dim)))
56 .collect()
57 };
58
59 let mut scale = 1.0f32;
60 let mut sizes = compute(scale);
61 let mut total = layer_tex_total_bytes(&sizes);
62 if total > budget {
63 for _ in 0..8 {
65 if total <= budget {
66 break;
67 }
68 let factor = ((budget as f64) / (total as f64)).sqrt().clamp(0.05, 0.99);
69 let next = (scale as f64 * factor) as f32;
70 if next >= scale || next <= 0.01 {
71 break;
72 }
73 scale = next;
74 sizes = compute(scale);
75 total = layer_tex_total_bytes(&sizes);
76 }
77 let quantized = (scale * 8.0).floor() / 8.0;
80 if quantized > 0.0 && quantized < scale {
81 scale = quantized;
82 sizes = compute(scale);
83 }
84 }
85 (sizes, scale)
86}
87
88fn blend_state_for(mode: BlendMode) -> wgpu::BlendState {
90 use wgpu::{BlendComponent, BlendFactor, BlendOperation, BlendState};
91 let comp = |src_factor, dst_factor| BlendComponent { src_factor, dst_factor, operation: BlendOperation::Add };
92 match mode {
93 BlendMode::Normal => BlendState::ALPHA_BLENDING,
94 BlendMode::Multiply => BlendState {
95 color: comp(BlendFactor::Dst, BlendFactor::Zero),
96 alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
97 },
98 BlendMode::Screen => BlendState {
99 color: comp(BlendFactor::One, BlendFactor::OneMinusSrc),
100 alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
101 },
102 BlendMode::Add => BlendState {
103 color: comp(BlendFactor::One, BlendFactor::One),
104 alpha: comp(BlendFactor::One, BlendFactor::OneMinusSrcAlpha),
105 },
106 }
107}
108
109fn stencil_equal_state() -> wgpu::DepthStencilState {
111 let face = wgpu::StencilFaceState {
112 compare: wgpu::CompareFunction::Equal,
113 fail_op: wgpu::StencilOperation::Keep,
114 depth_fail_op: wgpu::StencilOperation::Keep,
115 pass_op: wgpu::StencilOperation::Keep,
116 };
117 wgpu::DepthStencilState {
118 format: STENCIL_FMT,
119 depth_write_enabled: None,
120 depth_compare: None,
121 stencil: wgpu::StencilState { front: face, back: face, read_mask: 0xFF, write_mask: 0 },
122 bias: wgpu::DepthBiasState::default(),
123 }
124}
125
126impl Renderer {
127 pub fn shared_resources(&self) -> RendererShared {
129 self.image_cache.borrow_mut().evict_enabled = false;
131 RendererShared {
132 atlas_cache: Rc::clone(&self.atlas_cache),
133 image_cache: Rc::clone(&self.image_cache),
134 rect_pipelines: self.rect_pipelines.clone(),
135 rect_bgl: self.rect_bgl.clone(),
136 text_pipeline: self.text_pipeline.clone(),
137 text_bgl: self.text_bgl.clone(),
138 text_pipeline_mask: self.text_pipeline_mask.clone(),
139 text_pipeline_mask_stencil_test: self.text_pipeline_mask_stencil_test.clone(),
140 tri_pipeline: self.tri_pipeline.clone(),
141 tri_bgl: self.tri_bgl.clone(),
142 tri_pipeline_stencil_inc: self.tri_pipeline_stencil_inc.clone(),
143 tri_pipeline_stencil_dec: self.tri_pipeline_stencil_dec.clone(),
144 rect_pipelines_stencil_test: self.rect_pipelines_stencil_test.clone(),
145 text_pipeline_stencil_test: self.text_pipeline_stencil_test.clone(),
146 tri_pipeline_stencil_test: self.tri_pipeline_stencil_test.clone(),
147 blit_pipeline: self.blit_pipeline.clone(),
148 blit_bgl: self.blit_bgl.clone(),
149 blit_sampler: self.blit_sampler.clone(),
150 backdrop_pipeline: self.backdrop_pipeline.clone(),
151 backdrop_bgl: self.backdrop_bgl.clone(),
152 format: self.format,
153 }
154 }
155
156 pub fn new_with_shared(device: &wgpu::Device, shared: &RendererShared) -> Self {
158 Self {
159 rect_pipelines: shared.rect_pipelines.clone(),
160 rect_bgl: shared.rect_bgl.clone(),
161 text_pipeline: shared.text_pipeline.clone(),
162 text_bgl: shared.text_bgl.clone(),
163 text_pipeline_mask: shared.text_pipeline_mask.clone(),
164 text_pipeline_mask_stencil_test: shared.text_pipeline_mask_stencil_test.clone(),
165 tri_pipeline: shared.tri_pipeline.clone(),
166 tri_bgl: shared.tri_bgl.clone(),
167 tri_pipeline_stencil_inc: shared.tri_pipeline_stencil_inc.clone(),
168 tri_pipeline_stencil_dec: shared.tri_pipeline_stencil_dec.clone(),
169 rect_pipelines_stencil_test: shared.rect_pipelines_stencil_test.clone(),
170 text_pipeline_stencil_test: shared.text_pipeline_stencil_test.clone(),
171 tri_pipeline_stencil_test: shared.tri_pipeline_stencil_test.clone(),
172 atlas_cache: Rc::clone(&shared.atlas_cache),
173 layer_cache: HashMap::new(),
174 active_layer_ids: std::collections::HashSet::new(),
175 frame_layer_sizes: HashMap::new(),
176 composition_scratch: mgui_core::CompositionScratch::default(),
177 blit_pipeline: shared.blit_pipeline.clone(),
178 blit_bgl: shared.blit_bgl.clone(),
179 blit_sampler: shared.blit_sampler.clone(),
180 backdrop_pipeline: shared.backdrop_pipeline.clone(),
181 backdrop_bgl: shared.backdrop_bgl.clone(),
182 format: shared.format,
183 gpu_profiler: crate::gpu_profiler::GpuProfiler::new(device),
184 batch_pools: HashMap::new(),
185 image_cache: Rc::clone(&shared.image_cache),
186 msaa_scratch: HashMap::new(),
187 stencil_scratch: HashMap::new(),
188 snapshot_scratch: HashMap::new(),
189 last_stats: RenderStats::default(),
190 }
191 }
192
193 pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
194 let pass1_msaa = wgpu::MultisampleState { count: 4, mask: !0, alpha_to_coverage_enabled: false };
200 let text_msaa = pass1_msaa;
204
205 let rect_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
207 label: Some("rect-shader"),
208 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/rect.wgsl").into()),
209 });
210
211 let rect_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
212 label: Some("rect-bgl"),
213 entries: &[
214 wgpu::BindGroupLayoutEntry {
215 binding: 0,
217 visibility: wgpu::ShaderStages::VERTEX,
218 ty: wgpu::BindingType::Buffer {
219 ty: wgpu::BufferBindingType::Uniform,
220 has_dynamic_offset: false,
221 min_binding_size: None,
222 },
223 count: None,
224 },
225 wgpu::BindGroupLayoutEntry {
226 binding: 1,
228 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
229 ty: wgpu::BindingType::Buffer {
230 ty: wgpu::BufferBindingType::Storage { read_only: true },
231 has_dynamic_offset: false,
232 min_binding_size: None,
233 },
234 count: None,
235 },
236 ],
237 });
238
239 let rect_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
240 label: Some("rect-pipeline-layout"),
241 bind_group_layouts: &[Some(&rect_bgl)],
242 immediate_size: 0,
243 });
244
245 const RECT_BLEND_MODES: [BlendMode; 4] =
248 [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Add];
249 let make_rect_pipeline =
250 |label: &'static str, blend: wgpu::BlendState, depth_stencil: Option<wgpu::DepthStencilState>| {
251 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
252 label: Some(label),
253 layout: Some(&rect_pipeline_layout),
254 vertex: wgpu::VertexState {
255 module: &rect_shader,
256 entry_point: Some("vs_main"),
257 compilation_options: Default::default(),
258 buffers: &[],
259 },
260 primitive: wgpu::PrimitiveState {
261 topology: wgpu::PrimitiveTopology::TriangleList,
262 ..Default::default()
263 },
264 depth_stencil,
265 multisample: pass1_msaa,
266 fragment: Some(wgpu::FragmentState {
267 module: &rect_shader,
268 entry_point: Some("fs_main"),
269 compilation_options: Default::default(),
270 targets: &[Some(wgpu::ColorTargetState {
271 format,
272 blend: Some(blend),
273 write_mask: wgpu::ColorWrites::ALL,
274 })],
275 }),
276 multiview_mask: None,
277 cache: None,
278 })
279 };
280 let rect_pipelines: [wgpu::RenderPipeline; 4] =
281 std::array::from_fn(|i| make_rect_pipeline("rect-pipeline", blend_state_for(RECT_BLEND_MODES[i]), None));
282
283 let text_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
285 label: Some("text-shader"),
286 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/text.wgsl").into()),
287 });
288
289 let text_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
290 label: Some("text-bgl"),
291 entries: &[
292 wgpu::BindGroupLayoutEntry {
293 binding: 0,
295 visibility: wgpu::ShaderStages::VERTEX,
296 ty: wgpu::BindingType::Buffer {
297 ty: wgpu::BufferBindingType::Uniform,
298 has_dynamic_offset: false,
299 min_binding_size: None,
300 },
301 count: None,
302 },
303 wgpu::BindGroupLayoutEntry {
304 binding: 1,
306 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
307 ty: wgpu::BindingType::Buffer {
308 ty: wgpu::BufferBindingType::Storage { read_only: true },
309 has_dynamic_offset: false,
310 min_binding_size: None,
311 },
312 count: None,
313 },
314 wgpu::BindGroupLayoutEntry {
315 binding: 2,
317 visibility: wgpu::ShaderStages::FRAGMENT,
318 ty: wgpu::BindingType::Texture {
319 sample_type: wgpu::TextureSampleType::Float { filterable: true },
320 view_dimension: wgpu::TextureViewDimension::D2,
321 multisampled: false,
322 },
323 count: None,
324 },
325 wgpu::BindGroupLayoutEntry {
326 binding: 3,
328 visibility: wgpu::ShaderStages::FRAGMENT,
329 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
330 count: None,
331 },
332 ],
333 });
334
335 let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
336 label: Some("text-pipeline-layout"),
337 bind_group_layouts: &[Some(&text_bgl)],
338 immediate_size: 0,
339 });
340
341 let mask_blend = wgpu::BlendState {
345 color: wgpu::BlendComponent {
346 src_factor: wgpu::BlendFactor::Zero,
347 dst_factor: wgpu::BlendFactor::One,
348 operation: wgpu::BlendOperation::Add,
349 },
350 alpha: wgpu::BlendComponent {
351 src_factor: wgpu::BlendFactor::Zero,
352 dst_factor: wgpu::BlendFactor::SrcAlpha,
353 operation: wgpu::BlendOperation::Add,
354 },
355 };
356
357 let text_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
358 label: Some("text-pipeline"),
359 layout: Some(&text_pipeline_layout),
360 vertex: wgpu::VertexState {
361 module: &text_shader,
362 entry_point: Some("vs_main"),
363 compilation_options: Default::default(),
364 buffers: &[],
365 },
366 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
367 depth_stencil: None,
368 multisample: text_msaa,
370 fragment: Some(wgpu::FragmentState {
371 module: &text_shader,
372 entry_point: Some("fs_main"),
373 compilation_options: Default::default(),
374 targets: &[Some(wgpu::ColorTargetState {
375 format,
376 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
377 write_mask: wgpu::ColorWrites::ALL,
378 })],
379 }),
380 multiview_mask: None,
381 cache: None,
382 });
383
384 let text_pipeline_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
386 label: Some("text-pipeline-mask"),
387 layout: Some(&text_pipeline_layout),
388 vertex: wgpu::VertexState {
389 module: &text_shader,
390 entry_point: Some("vs_main"),
391 compilation_options: Default::default(),
392 buffers: &[],
393 },
394 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
395 depth_stencil: None,
396 multisample: text_msaa,
397 fragment: Some(wgpu::FragmentState {
398 module: &text_shader,
399 entry_point: Some("fs_main"),
400 compilation_options: Default::default(),
401 targets: &[Some(wgpu::ColorTargetState {
402 format,
403 blend: Some(mask_blend),
404 write_mask: wgpu::ColorWrites::ALL,
405 })],
406 }),
407 multiview_mask: None,
408 cache: None,
409 });
410
411 let tri_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
413 label: Some("tri-shader"),
414 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/tri.wgsl").into()),
415 });
416
417 let tri_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
418 label: Some("tri-bgl"),
419 entries: &[wgpu::BindGroupLayoutEntry {
420 binding: 0,
421 visibility: wgpu::ShaderStages::VERTEX,
422 ty: wgpu::BindingType::Buffer {
423 ty: wgpu::BufferBindingType::Uniform,
424 has_dynamic_offset: false,
425 min_binding_size: None,
426 },
427 count: None,
428 }],
429 });
430
431 let tri_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
432 label: Some("tri-pipeline-layout"),
433 bind_group_layouts: &[Some(&tri_bgl)],
434 immediate_size: 0,
435 });
436
437 let tri_vb_layouts = [Some(wgpu::VertexBufferLayout {
438 array_stride: 24,
439 step_mode: wgpu::VertexStepMode::Vertex,
440 attributes: &[
441 wgpu::VertexAttribute { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float32x2 },
442 wgpu::VertexAttribute { offset: 8, shader_location: 1, format: wgpu::VertexFormat::Float32x4 },
443 ],
444 })];
445
446 let tri_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
447 label: Some("tri-pipeline"),
448 layout: Some(&tri_pipeline_layout),
449 vertex: wgpu::VertexState {
450 module: &tri_shader,
451 entry_point: Some("vs_main"),
452 compilation_options: Default::default(),
453 buffers: &tri_vb_layouts,
454 },
455 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
456 depth_stencil: None,
457 multisample: pass1_msaa,
458 fragment: Some(wgpu::FragmentState {
459 module: &tri_shader,
460 entry_point: Some("fs_main"),
461 compilation_options: Default::default(),
462 targets: &[Some(wgpu::ColorTargetState {
463 format,
464 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
465 write_mask: wgpu::ColorWrites::ALL,
466 })],
467 }),
468 multiview_mask: None,
469 cache: None,
470 });
471
472 let keep_op = wgpu::StencilOperation::Keep;
476
477 let stencil_write_pipeline = |label: &'static str, op: wgpu::StencilOperation| {
479 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
480 label: Some(label),
481 layout: Some(&tri_pipeline_layout),
482 vertex: wgpu::VertexState {
483 module: &tri_shader,
484 entry_point: Some("vs_main"),
485 compilation_options: Default::default(),
486 buffers: &tri_vb_layouts,
487 },
488 primitive: wgpu::PrimitiveState {
489 topology: wgpu::PrimitiveTopology::TriangleList,
490 ..Default::default()
491 },
492 depth_stencil: Some(wgpu::DepthStencilState {
493 format: STENCIL_FMT,
494 depth_write_enabled: None,
495 depth_compare: None,
496 stencil: wgpu::StencilState {
497 front: wgpu::StencilFaceState {
498 compare: wgpu::CompareFunction::Always,
499 fail_op: keep_op,
500 depth_fail_op: keep_op,
501 pass_op: op,
502 },
503 back: wgpu::StencilFaceState {
504 compare: wgpu::CompareFunction::Always,
505 fail_op: keep_op,
506 depth_fail_op: keep_op,
507 pass_op: op,
508 },
509 read_mask: 0xFF,
510 write_mask: 0xFF,
511 },
512 bias: wgpu::DepthBiasState::default(),
513 }),
514 multisample: pass1_msaa,
515 fragment: Some(wgpu::FragmentState {
516 module: &tri_shader,
517 entry_point: Some("fs_main"),
518 compilation_options: Default::default(),
519 targets: &[Some(wgpu::ColorTargetState {
520 format,
521 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
522 write_mask: wgpu::ColorWrites::empty(), })],
524 }),
525 multiview_mask: None,
526 cache: None,
527 })
528 };
529 let tri_pipeline_stencil_inc =
530 stencil_write_pipeline("tri-pipeline-stencil-inc", wgpu::StencilOperation::IncrementWrap);
531 let tri_pipeline_stencil_dec =
532 stencil_write_pipeline("tri-pipeline-stencil-dec", wgpu::StencilOperation::DecrementWrap);
533
534 let rect_pipelines_stencil_test: [wgpu::RenderPipeline; 4] = std::array::from_fn(|i| {
536 make_rect_pipeline(
537 "rect-pipeline-stencil-test",
538 blend_state_for(RECT_BLEND_MODES[i]),
539 Some(stencil_equal_state()),
540 )
541 });
542
543 let text_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
545 label: Some("text-pipeline-stencil-test"),
546 layout: Some(&text_pipeline_layout),
547 vertex: wgpu::VertexState {
548 module: &text_shader,
549 entry_point: Some("vs_main"),
550 compilation_options: Default::default(),
551 buffers: &[],
552 },
553 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
554 depth_stencil: Some(wgpu::DepthStencilState {
555 format: STENCIL_FMT,
556 depth_write_enabled: None,
557 depth_compare: None,
558 stencil: wgpu::StencilState {
559 front: wgpu::StencilFaceState {
560 compare: wgpu::CompareFunction::Equal,
561 fail_op: keep_op,
562 depth_fail_op: keep_op,
563 pass_op: keep_op,
564 },
565 back: wgpu::StencilFaceState {
566 compare: wgpu::CompareFunction::Equal,
567 fail_op: keep_op,
568 depth_fail_op: keep_op,
569 pass_op: keep_op,
570 },
571 read_mask: 0xFF,
572 write_mask: 0,
573 },
574 bias: wgpu::DepthBiasState::default(),
575 }),
576 multisample: text_msaa,
577 fragment: Some(wgpu::FragmentState {
578 module: &text_shader,
579 entry_point: Some("fs_main"),
580 compilation_options: Default::default(),
581 targets: &[Some(wgpu::ColorTargetState {
582 format,
583 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
584 write_mask: wgpu::ColorWrites::ALL,
585 })],
586 }),
587 multiview_mask: None,
588 cache: None,
589 });
590
591 let text_pipeline_mask_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
593 label: Some("text-pipeline-mask-stencil-test"),
594 layout: Some(&text_pipeline_layout),
595 vertex: wgpu::VertexState {
596 module: &text_shader,
597 entry_point: Some("vs_main"),
598 compilation_options: Default::default(),
599 buffers: &[],
600 },
601 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
602 depth_stencil: Some(wgpu::DepthStencilState {
603 format: STENCIL_FMT,
604 depth_write_enabled: None,
605 depth_compare: None,
606 stencil: wgpu::StencilState {
607 front: wgpu::StencilFaceState {
608 compare: wgpu::CompareFunction::Equal,
609 fail_op: keep_op,
610 depth_fail_op: keep_op,
611 pass_op: keep_op,
612 },
613 back: wgpu::StencilFaceState {
614 compare: wgpu::CompareFunction::Equal,
615 fail_op: keep_op,
616 depth_fail_op: keep_op,
617 pass_op: keep_op,
618 },
619 read_mask: 0xFF,
620 write_mask: 0,
621 },
622 bias: wgpu::DepthBiasState::default(),
623 }),
624 multisample: text_msaa,
625 fragment: Some(wgpu::FragmentState {
626 module: &text_shader,
627 entry_point: Some("fs_main"),
628 compilation_options: Default::default(),
629 targets: &[Some(wgpu::ColorTargetState {
630 format,
631 blend: Some(mask_blend),
632 write_mask: wgpu::ColorWrites::ALL,
633 })],
634 }),
635 multiview_mask: None,
636 cache: None,
637 });
638
639 let tri_pipeline_stencil_test = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
641 label: Some("tri-pipeline-stencil-test"),
642 layout: Some(&tri_pipeline_layout),
643 vertex: wgpu::VertexState {
644 module: &tri_shader,
645 entry_point: Some("vs_main"),
646 compilation_options: Default::default(),
647 buffers: &tri_vb_layouts,
648 },
649 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
650 depth_stencil: Some(wgpu::DepthStencilState {
651 format: STENCIL_FMT,
652 depth_write_enabled: None,
653 depth_compare: None,
654 stencil: wgpu::StencilState {
655 front: wgpu::StencilFaceState {
656 compare: wgpu::CompareFunction::Equal,
657 fail_op: keep_op,
658 depth_fail_op: keep_op,
659 pass_op: keep_op,
660 },
661 back: wgpu::StencilFaceState {
662 compare: wgpu::CompareFunction::Equal,
663 fail_op: keep_op,
664 depth_fail_op: keep_op,
665 pass_op: keep_op,
666 },
667 read_mask: 0xFF,
668 write_mask: 0,
669 },
670 bias: wgpu::DepthBiasState::default(),
671 }),
672 multisample: pass1_msaa,
673 fragment: Some(wgpu::FragmentState {
674 module: &tri_shader,
675 entry_point: Some("fs_main"),
676 compilation_options: Default::default(),
677 targets: &[Some(wgpu::ColorTargetState {
678 format,
679 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
680 write_mask: wgpu::ColorWrites::ALL,
681 })],
682 }),
683 multiview_mask: None,
684 cache: None,
685 });
686
687 let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
689 label: Some("blit-shader"),
690 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/blit.wgsl").into()),
691 });
692 let blit_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
693 label: Some("blit-bgl"),
694 entries: &[
695 wgpu::BindGroupLayoutEntry {
696 binding: 0,
697 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
698 ty: wgpu::BindingType::Buffer {
699 ty: wgpu::BufferBindingType::Uniform,
700 has_dynamic_offset: false,
701 min_binding_size: None,
702 },
703 count: None,
704 },
705 wgpu::BindGroupLayoutEntry {
706 binding: 1,
707 visibility: wgpu::ShaderStages::FRAGMENT,
708 ty: wgpu::BindingType::Texture {
709 sample_type: wgpu::TextureSampleType::Float { filterable: true },
710 view_dimension: wgpu::TextureViewDimension::D2,
711 multisampled: false,
712 },
713 count: None,
714 },
715 wgpu::BindGroupLayoutEntry {
716 binding: 2,
717 visibility: wgpu::ShaderStages::FRAGMENT,
718 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
719 count: None,
720 },
721 ],
722 });
723 let blit_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
724 label: Some("blit-pipeline-layout"),
725 bind_group_layouts: &[Some(&blit_bgl)],
726 immediate_size: 0,
727 });
728 let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
729 label: Some("blit-pipeline"),
730 layout: Some(&blit_pipeline_layout),
731 vertex: wgpu::VertexState {
732 module: &blit_shader,
733 entry_point: Some("vs_main"),
734 compilation_options: Default::default(),
735 buffers: &[],
736 },
737 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
738 depth_stencil: None,
739 multisample: wgpu::MultisampleState::default(),
741 fragment: Some(wgpu::FragmentState {
742 module: &blit_shader,
743 entry_point: Some("fs_main"),
744 compilation_options: Default::default(),
745 targets: &[Some(wgpu::ColorTargetState {
746 format,
747 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
748 write_mask: wgpu::ColorWrites::ALL,
749 })],
750 }),
751 multiview_mask: None,
752 cache: None,
753 });
754 let backdrop_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
756 label: Some("backdrop-shader"),
757 source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/backdrop.wgsl").into()),
758 });
759 let backdrop_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
760 label: Some("backdrop-bgl"),
761 entries: &[
762 wgpu::BindGroupLayoutEntry {
763 binding: 0,
764 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
765 ty: wgpu::BindingType::Buffer {
766 ty: wgpu::BufferBindingType::Uniform,
767 has_dynamic_offset: false,
768 min_binding_size: None,
769 },
770 count: None,
771 },
772 wgpu::BindGroupLayoutEntry {
773 binding: 1,
774 visibility: wgpu::ShaderStages::FRAGMENT,
775 ty: wgpu::BindingType::Texture {
776 sample_type: wgpu::TextureSampleType::Float { filterable: true },
777 view_dimension: wgpu::TextureViewDimension::D2,
778 multisampled: false,
779 },
780 count: None,
781 },
782 wgpu::BindGroupLayoutEntry {
783 binding: 2,
784 visibility: wgpu::ShaderStages::FRAGMENT,
785 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
786 count: None,
787 },
788 ],
789 });
790 let backdrop_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
791 label: Some("backdrop-pipeline-layout"),
792 bind_group_layouts: &[Some(&backdrop_bgl)],
793 immediate_size: 0,
794 });
795 let backdrop_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
796 label: Some("backdrop-pipeline"),
797 layout: Some(&backdrop_pipeline_layout),
798 vertex: wgpu::VertexState {
799 module: &backdrop_shader,
800 entry_point: Some("vs_main"),
801 compilation_options: Default::default(),
802 buffers: &[],
803 },
804 primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, ..Default::default() },
805 depth_stencil: Some(stencil_equal_state()),
807 multisample: pass1_msaa,
808 fragment: Some(wgpu::FragmentState {
809 module: &backdrop_shader,
810 entry_point: Some("fs_main"),
811 compilation_options: Default::default(),
812 targets: &[Some(wgpu::ColorTargetState {
813 format,
814 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
815 write_mask: wgpu::ColorWrites::ALL,
816 })],
817 }),
818 multiview_mask: None,
819 cache: None,
820 });
821
822 let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
823 address_mode_u: wgpu::AddressMode::ClampToEdge,
824 address_mode_v: wgpu::AddressMode::ClampToEdge,
825 address_mode_w: wgpu::AddressMode::ClampToEdge,
826 mag_filter: wgpu::FilterMode::Linear,
827 min_filter: wgpu::FilterMode::Linear,
828 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
829 ..Default::default()
830 });
831
832 Self {
833 rect_pipelines,
834 rect_bgl,
835 text_pipeline,
836 text_bgl,
837 text_pipeline_mask,
838 text_pipeline_mask_stencil_test,
839 tri_pipeline,
840 tri_bgl,
841 tri_pipeline_stencil_inc,
842 tri_pipeline_stencil_dec,
843 rect_pipelines_stencil_test,
844 text_pipeline_stencil_test,
845 tri_pipeline_stencil_test,
846 atlas_cache: Rc::new(RefCell::new(None)),
847 layer_cache: HashMap::new(),
848 blit_pipeline,
849 blit_bgl,
850 blit_sampler,
851 backdrop_pipeline,
852 backdrop_bgl,
853 format,
857 active_layer_ids: std::collections::HashSet::new(),
859 frame_layer_sizes: HashMap::new(),
860 composition_scratch: mgui_core::CompositionScratch::default(),
861 gpu_profiler: crate::gpu_profiler::GpuProfiler::new(device),
863 batch_pools: HashMap::new(),
865 image_cache: Rc::new(RefCell::new(ImageTextureCache { evict_enabled: true, ..Default::default() })),
866 msaa_scratch: HashMap::new(),
867 stencil_scratch: HashMap::new(),
868 snapshot_scratch: HashMap::new(),
869 last_stats: RenderStats::default(),
870 }
871 }
872
873 pub(crate) fn ensure_atlas(
879 &mut self,
880 device: &wgpu::Device,
881 queue: &wgpu::Queue,
882 ) -> (wgpu::TextureView, wgpu::Sampler) {
883 let snap = crate::text::atlas_snapshot();
884 let mut atlas_cache = self.atlas_cache.borrow_mut();
885
886 let need_recreate = match atlas_cache.as_ref() {
887 None => true,
888 Some(c) => c.cached_size != (snap.width, snap.height),
889 };
890
891 if need_recreate {
892 log::info!("atlas: rebuild texture (size {}x{}, dirty={})", snap.width, snap.height, snap.dirty);
893 let (dy0, dy1) = snap.dirty_y;
895 let rows = dy1.saturating_sub(dy0);
896 let pixels = snap.pixels.as_deref().filter(|p| !p.is_empty()).unwrap_or(&[]);
897 let texture = device.create_texture(&wgpu::TextureDescriptor {
898 label: Some("glyph-atlas"),
899 size: wgpu::Extent3d { width: snap.width, height: snap.height, depth_or_array_layers: 1 },
900 mip_level_count: 1,
901 sample_count: 1,
902 dimension: wgpu::TextureDimension::D2,
903 format: wgpu::TextureFormat::R8Unorm,
904 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
905 view_formats: &[],
906 });
907 if rows > 0 && !pixels.is_empty() {
908 queue.write_texture(
909 wgpu::TexelCopyTextureInfo {
910 texture: &texture,
911 mip_level: 0,
912 origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
913 aspect: wgpu::TextureAspect::All,
914 },
915 pixels,
916 wgpu::TexelCopyBufferLayout {
917 offset: 0,
918 bytes_per_row: Some(snap.width),
919 rows_per_image: Some(rows),
920 },
921 wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
922 );
923 }
924 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
925 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
926 address_mode_u: wgpu::AddressMode::ClampToEdge,
927 address_mode_v: wgpu::AddressMode::ClampToEdge,
928 address_mode_w: wgpu::AddressMode::ClampToEdge,
929 mag_filter: wgpu::FilterMode::Linear,
930 min_filter: wgpu::FilterMode::Linear,
931 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
932 ..Default::default()
933 });
934 *atlas_cache = Some(AtlasGpu { texture, view, sampler, cached_size: (snap.width, snap.height) });
935 } else if snap.dirty {
936 let (dy0, dy1) = snap.dirty_y;
937 let rows = dy1.saturating_sub(dy0);
938 log::info!("atlas: upload {} KB (rows {}..{})", (snap.width * rows) as usize / 1024, dy0, dy1);
939 if rows > 0 {
941 if let (Some(cache), Some(pixels)) = (atlas_cache.as_ref(), snap.pixels.as_deref()) {
942 queue.write_texture(
943 wgpu::TexelCopyTextureInfo {
944 texture: &cache.texture,
945 mip_level: 0,
946 origin: wgpu::Origin3d { x: 0, y: dy0, z: 0 },
947 aspect: wgpu::TextureAspect::All,
948 },
949 pixels,
950 wgpu::TexelCopyBufferLayout {
951 offset: 0,
952 bytes_per_row: Some(snap.width),
953 rows_per_image: Some(rows),
954 },
955 wgpu::Extent3d { width: snap.width, height: rows, depth_or_array_layers: 1 },
956 );
957 }
958 }
959 }
960
961 if snap.dirty {
963 crate::text::atlas_clear_dirty();
964 }
965
966 let atlas = atlas_cache.as_ref().expect("atlas cache populated");
967 (atlas.view.clone(), atlas.sampler.clone())
968 }
969
970 pub(crate) fn ensure_all_layer_caches(
1003 &mut self,
1004 device: &wgpu::Device,
1005 layer_paints: &[LayerPaint],
1006 dpr: f32,
1007 screen_size: (f32, f32),
1008 ) {
1009 let max_dim = device.limits().max_texture_dimension_2d.max(1);
1010 let (targets, scale) =
1011 layer_texture_targets(layer_paints, dpr, screen_size, max_dim, LAYER_TEXTURE_BUDGET_BYTES);
1012 if scale < 0.999 {
1013 log::debug!(
1014 target: "mgui_profile",
1015 "layer texture budget exceeded: rendering {} layers at {:.0}% resolution",
1016 targets.len(),
1017 scale * 100.0
1018 );
1019 }
1020
1021 for (layer_id, tex_size) in targets {
1022 let need_create = match self.layer_cache.get(&layer_id) {
1025 None => true,
1026 Some(c) => c.cached_size != tex_size,
1027 };
1028 if need_create {
1029 let resolve_tex = device.create_texture(&wgpu::TextureDescriptor {
1030 label: Some("layer-resolve"),
1031 size: wgpu::Extent3d { width: tex_size.0, height: tex_size.1, depth_or_array_layers: 1 },
1032 mip_level_count: 1,
1033 sample_count: 1,
1034 dimension: wgpu::TextureDimension::D2,
1035 format: self.format,
1036 usage: wgpu::TextureUsages::RENDER_ATTACHMENT
1038 | wgpu::TextureUsages::TEXTURE_BINDING
1039 | wgpu::TextureUsages::COPY_SRC,
1040 view_formats: &[],
1041 });
1042 let resolve_view = resolve_tex.create_view(&wgpu::TextureViewDescriptor::default());
1043 self.layer_cache.insert(
1044 layer_id,
1045 LayerGpuCache { resolve_texture: resolve_tex, resolve_view, cached_size: tex_size },
1046 );
1047 }
1048 }
1049 }
1050
1051 pub(super) fn msaa_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
1053 if let Some(v) = self.msaa_scratch.get(&size) {
1054 return v.clone();
1055 }
1056 let tex = device.create_texture(&wgpu::TextureDescriptor {
1057 label: Some("scratch-msaa"),
1058 size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1059 mip_level_count: 1,
1060 sample_count: 4,
1061 dimension: wgpu::TextureDimension::D2,
1062 format: self.format,
1063 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1064 view_formats: &[],
1065 });
1066 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1067 self.msaa_scratch.insert(size, view.clone());
1068 view
1069 }
1070
1071 pub(super) fn stencil_scratch_view(&mut self, device: &wgpu::Device, size: (u32, u32)) -> wgpu::TextureView {
1073 if let Some(v) = self.stencil_scratch.get(&size) {
1074 return v.clone();
1075 }
1076 let tex = device.create_texture(&wgpu::TextureDescriptor {
1077 label: Some("scratch-stencil"),
1078 size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1079 mip_level_count: 1,
1080 sample_count: 4,
1081 dimension: wgpu::TextureDimension::D2,
1082 format: wgpu::TextureFormat::Stencil8,
1083 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
1084 view_formats: &[],
1085 });
1086 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1087 self.stencil_scratch.insert(size, view.clone());
1088 view
1089 }
1090
1091 pub(super) fn snapshot_scratch(
1093 &mut self,
1094 device: &wgpu::Device,
1095 size: (u32, u32),
1096 ) -> (wgpu::Texture, wgpu::TextureView) {
1097 if let Some((tex, view)) = self.snapshot_scratch.get(&size) {
1098 return (tex.clone(), view.clone());
1099 }
1100 let tex = device.create_texture(&wgpu::TextureDescriptor {
1101 label: Some("scratch-snapshot"),
1102 size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1 },
1103 mip_level_count: 1,
1104 sample_count: 1,
1105 dimension: wgpu::TextureDimension::D2,
1106 format: self.format,
1107 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
1108 view_formats: &[],
1109 });
1110 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
1111 self.snapshot_scratch.insert(size, (tex.clone(), view.clone()));
1112 (tex, view)
1113 }
1114
1115 }
1119
1120#[cfg(test)]
1126pub(crate) fn build_blit_uniform(lp: &LayerPaint, layer_logical_size: &Size, screen_size: (f32, f32)) -> BlitUniform {
1127 let comp = LayerComposition::single(lp, *layer_logical_size);
1128 build_blit_uniform_composed(lp, &comp, layer_logical_size, screen_size)
1129}
1130
1131pub(crate) fn build_blit_uniform_composed(
1136 lp: &LayerPaint,
1137 comp: &LayerComposition,
1138 layer_logical_size: &Size,
1139 screen_size: (f32, f32),
1140) -> BlitUniform {
1141 let mut flags: u32 = 0;
1142 let mut rotation = 0.0_f32;
1143 let mut scale_x = 1.0_f32;
1144 let mut scale_y = 1.0_f32;
1145 let mut translate_x = 0.0_f32;
1146 let mut translate_y = 0.0_f32;
1147 let mut clip_radius = 0.0_f32;
1148
1149 match lp.effect {
1150 LayerEffect::None => {}
1151 LayerEffect::Transform(t) => {
1152 if !t.is_identity() {
1153 flags |= effect_flags::HAS_TRANSFORM;
1154 }
1155 rotation = t.rotation;
1156 scale_x = t.scale_x;
1157 scale_y = t.scale_y;
1158 translate_x = t.translate.x;
1159 translate_y = t.translate.y;
1160 }
1161 LayerEffect::Opacity(_) => {}
1162 LayerEffect::ClipRRect(RRectDef { radius }) => {
1163 clip_radius = radius;
1164 }
1165 }
1166 if comp.opacity < 1.0 {
1167 flags |= effect_flags::HAS_OPACITY;
1168 }
1169 if !comp.clips.is_empty() {
1170 flags |= effect_flags::HAS_CLIP;
1171 }
1172
1173 let w = layer_logical_size.width;
1174 let h = layer_logical_size.height;
1175 let mut clip_rect0 = [0.0; 4];
1176 let mut clip_rect1 = [0.0; 4];
1177 let mut clip_params = [0.0; 4];
1178 if let Some(c) = comp.clips.first() {
1179 clip_rect0 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
1180 clip_params[0] = c.radius;
1181 }
1182 if let Some(c) = comp.clips.get(1) {
1183 clip_rect1 = [c.rect.x, c.rect.y, c.rect.width, c.rect.height];
1184 clip_params[1] = c.radius;
1185 }
1186 clip_params[2] = comp.clips.len().min(2) as f32;
1187
1188 BlitUniform {
1189 offset: [lp.offset.x, lp.offset.y],
1190 size: [w, h],
1191 screen: [screen_size.0, screen_size.1],
1192 effect_flags: flags,
1193 opacity: comp.opacity,
1194 rotation,
1195 scale_x,
1196 translate_x,
1197 translate_y,
1198 clip_radius,
1199 scale_y,
1200 quad_offset: [lp.offset.x, lp.offset.y],
1201 quad_size: [w, h],
1202 phys_screen: [0.0, 0.0],
1204 affine: [comp.affine.a, comp.affine.b, comp.affine.c, comp.affine.d],
1205 affine_translate: [comp.affine.tx, comp.affine.ty],
1206 _affine_pad: [0.0; 2],
1207 clip_rect0,
1208 clip_rect1,
1209 clip_params,
1210 }
1211}