1use std::any::TypeId;
2use std::borrow::Cow;
3use std::collections::{HashMap, HashSet};
4use std::hash::{Hash, Hasher};
5use std::num::NonZeroU64;
6#[cfg(feature = "winit-surface")]
7use std::panic::{AssertUnwindSafe, catch_unwind};
8use std::sync::{Arc, Mutex, Weak};
9
10use repose_core::color::{ChromaSiting, ColorInfo, PixelFormat};
11use repose_core::{
12 BlendMode, Brush, ColorFilter, CompositingStrategy, Dp, FontStyle, GradientStops,
13 ImageAlignment, ImageFilter, ImageFit, ImagePaintStyle, ImageSourceRect, MAX_GRADIENT_STOPS,
14 PathCommand, Px, ResolvedShape, Scene, SceneNode, ShapePath, StrokeCap, TextPaintStyle,
15 TileMode, Transform, Vec2,
16};
17#[cfg(feature = "winit-surface")]
18use repose_core::{GlyphRasterConfig, PresentModePref, RenderBackend, request_frame};
19#[cfg(feature = "winit-surface")]
20use wgpu::Instance;
21
22mod slug;
23
24fn align_up(value: u64, alignment: u64) -> anyhow::Result<u64> {
25 if !alignment.is_power_of_two() {
26 anyhow::bail!("alignment must be a power of two");
27 }
28 value
29 .checked_add(alignment - 1)
30 .map(|v| v & !(alignment - 1))
31 .ok_or_else(|| anyhow::anyhow!("alignment overflow"))
32}
33
34fn mesh_uniform_stride(size: u64, base: u64) -> u64 {
42 let rounded = size.saturating_add(base.saturating_sub(1)) / base * base;
43 rounded.next_power_of_two().max(base)
44}
45
46mod commands;
47pub use commands::RenderCommandFailure;
48pub use commands::RenderCommandReport;
49pub use commands::apply_render_commands;
50
51pub mod offscreen;
52
53mod callback;
54pub use callback::{
55 Callback, CallbackRenderPass, CallbackResources, ScreenDescriptor, WgpuCallback,
56};
57
58mod depth_composite;
59pub use depth_composite::{BlitRenderPass, DepthComposite, ScenePassOps};
60
61#[derive(Clone)]
62struct UploadRing {
63 buf: wgpu::Buffer,
64 cap: u64,
65 head: u64,
66 usage: wgpu::BufferUsages,
67}
68
69impl UploadRing {
70 fn new(device: &wgpu::Device, label: &str, cap: u64, usage: wgpu::BufferUsages) -> Self {
71 let max = device.limits().max_buffer_size;
72 let cap = cap.max(4).min(max).min(MAX_UPLOAD_RING_BYTES).max(4);
73 let buf = device.create_buffer(&wgpu::BufferDescriptor {
74 label: Some(label),
75 size: cap,
76 usage,
77 mapped_at_creation: false,
78 });
79 Self {
80 buf,
81 cap,
82 head: 0,
83 usage,
84 }
85 }
86
87 fn reset(&mut self) {
88 self.head = 0;
89 }
90
91 fn grow_to_fit(
92 &mut self,
93 device: &wgpu::Device,
94 encoder: &mut wgpu::CommandEncoder,
95 needed: u64,
96 ) -> anyhow::Result<()> {
97 if needed == 0 {
98 return Ok(());
99 }
100 let start = align_up(self.head, 4)?;
101 let end = start
102 .checked_add(needed)
103 .ok_or_else(|| anyhow::anyhow!("upload ring offset overflow"))?;
104 if end <= self.cap {
105 return Ok(());
106 }
107 let required = align_up(end, 4)?;
108 let doubled = self.cap.checked_mul(2).unwrap_or(0);
109 let new_cap = required.max(doubled).max(256);
110 let new_cap = align_up(new_cap, 4)?;
111 if new_cap > device.limits().max_buffer_size || new_cap > MAX_UPLOAD_RING_BYTES {
112 anyhow::bail!("upload ring exceeds resource budget");
113 }
114 if !self.usage.contains(wgpu::BufferUsages::COPY_SRC) {
115 anyhow::bail!("upload ring growth requires COPY_SRC");
116 }
117 let old = self.buf.clone();
118 self.buf = device.create_buffer(&wgpu::BufferDescriptor {
119 label: Some("upload ring (grown)"),
120 size: new_cap,
121 usage: self.usage,
122 mapped_at_creation: false,
123 });
124 self.cap = new_cap;
125 if self.head > 0 {
126 let copy_size = align_up(self.head, 4)?;
127 if copy_size > old.size() {
128 anyhow::bail!("upload ring old data exceeds old buffer");
129 }
130 encoder.copy_buffer_to_buffer(&old, 0, &self.buf, 0, copy_size);
131 }
132 Ok(())
133 }
134
135 fn alloc_write(&mut self, queue: &wgpu::Queue, bytes: &[u8]) -> anyhow::Result<u64> {
136 let len = u64::try_from(bytes.len())
137 .map_err(|_| anyhow::anyhow!("upload byte length exceeds u64"))?;
138 let start = align_up(self.head, 4)?;
139 let end = start
140 .checked_add(len)
141 .ok_or_else(|| anyhow::anyhow!("upload ring offset overflow"))?;
142 if end > self.cap {
143 anyhow::bail!(
144 "upload ring overflow: start={start} len={len} cap={}",
145 self.cap
146 );
147 }
148 queue.write_buffer(&self.buf, start, bytes);
149 self.head = end;
150 Ok(start)
151 }
152}
153
154struct InstancedPipe<I: bytemuck::Pod> {
155 ring: UploadRing,
156 _marker: std::marker::PhantomData<I>,
157}
158
159impl<I: bytemuck::Pod> InstancedPipe<I> {
160 fn new(ring: UploadRing) -> Self {
161 Self {
162 ring,
163 _marker: std::marker::PhantomData,
164 }
165 }
166
167 fn upload(
168 &mut self,
169 device: &wgpu::Device,
170 queue: &wgpu::Queue,
171 encoder: &mut wgpu::CommandEncoder,
172 data: &[I],
173 ) -> Option<(u64, u32)> {
174 if data.is_empty() {
175 return None;
176 }
177 let count = u32::try_from(data.len()).ok()?;
178 let bytes = bytemuck::cast_slice(data);
179 let byte_len = u64::try_from(bytes.len()).ok()?;
180 if byte_len == 0 || byte_len > device.limits().max_buffer_size {
181 return None;
182 }
183 self.ring
184 .grow_to_fit(device, encoder, byte_len)
185 .map_err(|error| log::error!("{error:#}"))
186 .ok()?;
187 let off = self
188 .ring
189 .alloc_write(queue, bytes)
190 .map_err(|error| log::error!("{error:#}"))
191 .ok()?;
192 Some((off, count))
193 }
194
195 fn reset(&mut self) {
196 self.ring.reset();
197 }
198}
199
200#[repr(C)]
201#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
202struct Globals {
203 ndc_to_px: [f32; 2],
204 _pad: [f32; 2],
205}
206
207fn make_globals(target_w: f32, target_h: f32) -> Globals {
208 Globals {
209 ndc_to_px: [target_w * 0.5, target_h * 0.5],
210 _pad: [0.0, 0.0],
211 }
212}
213
214const MAX_SHAPE_GRADIENT_TABLES: u32 = 256;
215const SHAPE_STOPS_TEXELS: u32 = 17;
217
218#[derive(Clone, Copy)]
220struct ShapeGradientStopsGpu {
221 texels: [[f32; 4]; SHAPE_STOPS_TEXELS as usize],
222}
223
224impl ShapeGradientStopsGpu {
225 fn from_stops(stops: &repose_core::GradientStops) -> Self {
226 let mut texels = [[0.0f32; 4]; SHAPE_STOPS_TEXELS as usize];
227 let packed = pack_gradient_stops(stops);
228 for (slot, color) in texels.iter_mut().take(8).zip(packed.0.iter()) {
229 *slot = *color;
230 }
231 for i in 0..8 {
232 texels[8 + i][0] = packed.1[i / 4][i % 4];
233 }
234 texels[16][0] = packed.2.min(repose_core::MAX_GRADIENT_STOPS as u32) as f32;
235 Self { texels }
236 }
237}
238
239pub struct WgpuSceneRenderer {
240 pub device: wgpu::Device,
241 pub queue: wgpu::Queue,
242 pub output_format: wgpu::TextureFormat,
243 surface_format: wgpu::TextureFormat,
245 pub output_width: u32,
246 pub output_height: u32,
247 pub pixels_per_point: f32,
249
250 surface_pipes: Pipelines,
253 working_space_pipes: Pipelines,
254 layer_pipes: Pipelines,
255 working_space_layer_pipes: Pipelines,
256
257 rects: InstancedPipe<RectInstance>,
259 borders: InstancedPipe<BorderInstance>,
260 ellipses: InstancedPipe<EllipseInstance>,
261 ellipse_borders: InstancedPipe<EllipseBorderInstance>,
262 arcs: InstancedPipe<ArcInstance>,
263 glyph_mask: InstancedPipe<GlyphInstance>,
264 glyph_color: InstancedPipe<GlyphInstance>,
265
266 image_bind_layout_rgba: wgpu::BindGroupLayout,
268 image_bind_layout_nv12: wgpu::BindGroupLayout,
269 image_sampler: wgpu::Sampler,
270 image_sampler_nearest: wgpu::Sampler,
271 image_sampler_repeat: wgpu::Sampler,
272 image_sampler_repeat_nearest: wgpu::Sampler,
273 layer_sampler: wgpu::Sampler,
274 layer_sampler_linear: wgpu::Sampler,
275
276 blur_ring: UploadRing,
278
279 text_bind_layout: wgpu::BindGroupLayout,
280
281 clip_ring: UploadRing,
283
284 projective_ring: UploadRing,
287
288 blend_ring: UploadRing,
290
291 slug_enabled: bool,
293 slug_ring: UploadRing,
294 slug_cache: slug::GlyphSlugCache,
295 slug_draw_cache: HashMap<SlugDrawKey, SlugDrawCacheEntry>,
296 slug_draw_cache_bytes_total: u64,
297
298 nv12: InstancedPipe<Nv12Instance>,
300
301 mesh_cache: HashMap<MeshCacheKey, MeshCacheEntry>,
302 mesh_cache_bytes_total: u64,
303 mesh_uniform_buf: wgpu::Buffer,
304 mesh_bind: wgpu::BindGroup,
305 mesh_uniform_head: u64,
306 mesh_uniform_alignment: u64,
307 mesh_uniform_cap: u64,
308 mesh_instance_buf: wgpu::Buffer,
312 mesh_instance_head: u64,
313 mesh_instance_cap: u64,
314
315 flatten_layer_ids: Vec<u32>,
319
320 blur_scratch_ids: HashMap<(u32, u32), u32>,
325 blur_scratch_next: u32,
326
327 blend_snapshots: std::collections::HashMap<u32, BlendSnapshot>,
331 blend_snapshot_pool: HashMap<BlendSnapshotKey, BlendSnapshot>,
332 blend_copies: Vec<BlendCopy>,
336
337 msaa_samples: u32,
338 working_space_msaa_samples: u32,
339
340 depth_stencil_tex: wgpu::Texture,
342 depth_stencil_view: wgpu::TextureView,
343
344 msaa_tex: Option<wgpu::Texture>,
346 msaa_view: Option<wgpu::TextureView>,
347 ws_msaa_tex: Option<wgpu::Texture>,
348 ws_msaa_view: Option<wgpu::TextureView>,
349 surface_resolve_tex: Option<wgpu::Texture>,
350 surface_resolve_view: Option<wgpu::TextureView>,
351 surface_resolve_bytes: u64,
352 msaa_bytes: u64,
353 ws_msaa_bytes: u64,
354 depth_stencil_bytes: u64,
355 working_space_bytes: u64,
356 gpu_budget_bytes: u64,
357
358 globals_buf: wgpu::Buffer,
359 globals_bind: wgpu::BindGroup,
360 globals_staging: wgpu::Buffer,
361 globals_staging_cap: u64,
362
363 shape_stops_tex: wgpu::Texture,
364 shape_stops_bind: wgpu::BindGroup,
365
366 atlas_mask: AtlasA8,
368 atlas_color: AtlasRGBA,
369 atlas_mask_bind: wgpu::BindGroup,
370 atlas_color_bind: wgpu::BindGroup,
371 atlas_generation: u64,
372 atlas_mask_pending: AtlasPending,
373 atlas_color_pending: AtlasPending,
374 atlas_last_compact_frame: u64,
375 atlas_mask_failures: HashSet<repose_text::CacheKey>,
376 atlas_color_failures: HashSet<repose_text::CacheKey>,
377 atlas_mask_deferred: HashSet<repose_text::CacheKey>,
380 atlas_color_deferred: HashSet<repose_text::CacheKey>,
381
382 glyph_outline_cache: HashMap<repose_text::CacheKey, GlyphOutlineEntry>,
383 legacy_shaped_text_cache: HashMap<TextShapeKey, TextShapeCacheEntry>,
384
385 next_image_handle: u64,
387 images: HashMap<u64, ImageTex>,
388 retained: HashMap<u64, RetainedImage>,
389 retained_bytes_total: u64,
390
391 next_coverage_handle: u64,
394 coverages: HashMap<u64, CoverageTex>,
395
396 frame_index: u64,
398 cache_touch_clock: u64,
399 image_bytes_total: u64,
400 image_evict_after_frames: u64,
401 image_budget_bytes: u64,
402
403 layer_pool: HashMap<u32, LayerTarget>,
406 producer_layer_ids: HashSet<u32>,
407 layer_bytes_total: u64,
408 transient_layer_bytes_total: u64,
409
410 working_space: bool,
414 ws_tex: Option<wgpu::Texture>,
415 ws_view: Option<wgpu::TextureView>,
416 ws_bind: Option<wgpu::BindGroup>,
417 display_pipeline: Option<wgpu::RenderPipeline>,
418 display_layout: Option<wgpu::BindGroupLayout>,
419
420 pub callback_resources: CallbackResources,
421 callback_scoped_resources: HashMap<CallbackScopeKey, CallbackResources>,
422 callback_scope_uses: HashMap<CallbackScopeKey, CallbackScopeUse>,
423 callback_scope_payloads: HashMap<CallbackScopeKey, Weak<Callback>>,
424 callback_scope_clock: u64,
425 blend_snapshot_bytes_total: u64,
426 frame_active: bool,
427 last_render_error: Option<String>,
428}
429
430pub struct WgpuSurfaceBackend {
431 #[cfg(feature = "winit-surface")]
432 instance: Option<wgpu::Instance>,
433 #[cfg(feature = "winit-surface")]
434 window: Option<Arc<winit::window::Window>>,
435 pub surface: Option<wgpu::Surface<'static>>,
436 pub surface_config: Option<wgpu::SurfaceConfiguration>,
437 #[cfg_attr(not(feature = "winit-surface"), allow(dead_code))]
438 pending_reconfigure: bool,
439 pub renderer: WgpuSceneRenderer,
440 device_lost: Arc<Mutex<Option<(wgpu::DeviceLostReason, String)>>>,
441}
442
443impl std::ops::Deref for WgpuSurfaceBackend {
444 type Target = WgpuSceneRenderer;
445 fn deref(&self) -> &Self::Target {
446 &self.renderer
447 }
448}
449impl std::ops::DerefMut for WgpuSurfaceBackend {
450 fn deref_mut(&mut self) -> &mut Self::Target {
451 &mut self.renderer
452 }
453}
454
455#[cfg(feature = "winit-surface")]
456pub type WgpuBackend = WgpuSurfaceBackend;
457
458pub fn clamp_output_size(width: u32, height: u32, max: u32) -> (u32, u32) {
468 if width == 0 || height == 0 {
469 return (0, 0);
470 }
471 let max = max.max(1);
472 if width <= max && height <= max {
473 return (width, height);
474 }
475 let scale = max as f64 / width.max(height) as f64;
476 let clamped = |v: u32| ((v as f64 * scale).round() as u32).clamp(1, max);
477 (clamped(width), clamped(height))
478}
479
480fn blur_sigma(radius: f32) -> f32 {
483 (radius.max(0.0) * 0.577_350_3 + 0.5).max(0.0)
484}
485
486fn blur_pad(radius: f32) -> f32 {
489 (blur_sigma(radius) * 3.0).ceil().max(0.0)
490}
491
492const BLUR_SCRATCH_ID_BASE: u32 = 0xE000_0000;
495
496const BLUR_SLOT_CONTENT: u32 = 0;
498const BLUR_SLOT_SHADOW: u32 = 1;
502
503impl Drop for WgpuSceneRenderer {
504 fn drop(&mut self) {
505 let _ = self.device.poll(wgpu::PollType::Poll);
506 #[cfg(not(target_arch = "wasm32"))]
507 {
508 let _ = self.device.poll(wgpu::PollType::Wait {
509 submission_index: None,
510 timeout: Some(web_time::Duration::from_millis(100)),
511 });
512 }
513 }
514}
515
516#[derive(Clone)]
517struct LayerTarget {
518 texture: wgpu::Texture,
519 view: wgpu::TextureView,
520 bind: wgpu::BindGroup,
521 bind_linear: wgpu::BindGroup,
522 depth_stencil_view: wgpu::TextureView,
523 width: u32,
524 height: u32,
525 format: wgpu::TextureFormat,
526 bytes: u64,
527 rect_px: (f32, f32, f32, f32),
528 transient: bool,
529}
530
531#[derive(Clone, Copy, PartialEq, Eq, Hash)]
535struct BlendSnapshotKey {
536 format: wgpu::TextureFormat,
537 width: u32,
538 height: u32,
539}
540
541#[derive(Clone)]
542struct BlendSnapshot {
543 key: BlendSnapshotKey,
544 texture: wgpu::Texture,
545 bind: wgpu::BindGroup,
546 bytes: u64,
547}
548
549struct BlendCopy {
550 pass_id: u64,
551 blend_id: u32,
552 target: PassTarget,
553 region: repose_core::Rect,
554}
555
556#[derive(Clone)]
557enum ActiveClip {
558 Rect {
559 off: u64,
560 cnt: u32,
561 rect: repose_core::Rect,
562 radii: [f32; 4],
563 scissor: (u32, u32, u32, u32),
568 difference: bool,
569 applied: bool,
570 blocked: bool,
571 },
572 Vector {
573 mesh: Option<MeshGpu>,
574 source: Arc<repose_core::VectorMeshData>,
575 uoff: u64,
576 ioff: u64,
579 icnt: u32,
580 affine: [f32; 6],
581 scissor: (u32, u32, u32, u32),
582 difference: bool,
583 applied: bool,
584 blocked: bool,
585 },
586}
587
588impl ActiveClip {
589 fn difference(&self) -> bool {
590 match self {
591 Self::Rect { difference, .. } | Self::Vector { difference, .. } => *difference,
592 }
593 }
594
595 fn blocked(&self) -> bool {
596 match self {
597 Self::Rect { blocked, .. } | Self::Vector { blocked, .. } => *blocked,
598 }
599 }
600}
601
602#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
604enum PassTarget {
605 Surface,
606 Layer(u32),
607}
608
609#[derive(Clone, Debug, PartialEq, Eq, Hash)]
610struct CallbackIdentity {
611 type_id: TypeId,
612 key: Option<Arc<str>>,
615 reusable: bool,
616}
617
618#[derive(Clone, Debug, PartialEq, Eq, Hash)]
630struct CallbackScopeKey {
631 callback: CallbackIdentity,
632 target: PassTarget,
633 target_format: wgpu::TextureFormat,
634 sample_count: u32,
635}
636
637#[derive(Clone, Copy)]
638struct CallbackScopeUse {
639 tick: u64,
640 frame: u64,
641}
642
643fn callback_identity(callback: &Callback, fallback: usize) -> CallbackIdentity {
644 match callback.0.resource_key() {
645 Some(key) => CallbackIdentity {
646 type_id: callback.0.resource_type_id(),
647 key: Some(Arc::from(key)),
648 reusable: true,
649 },
650 None => CallbackIdentity {
651 type_id: TypeId::of::<Callback>(),
652 key: Some(Arc::from(fallback.to_string())),
653 reusable: false,
654 },
655 }
656}
657
658fn callback_scope_key(
659 callback: &Callback,
660 fallback: usize,
661 target: PassTarget,
662 descriptor: &ScreenDescriptor,
663) -> CallbackScopeKey {
664 CallbackScopeKey {
665 callback: callback_identity(callback, fallback),
666 target,
667 target_format: descriptor.target_format,
668 sample_count: descriptor.sample_count,
669 }
670}
671
672const FIXED_FUNCTION_BLENDS: [repose_core::BlendMode; 5] = [
677 repose_core::BlendMode::Add,
678 repose_core::BlendMode::Multiply,
679 repose_core::BlendMode::Screen,
680 repose_core::BlendMode::Darken,
681 repose_core::BlendMode::Lighten,
682];
683
684fn fixed_function_blend(mode: repose_core::BlendMode) -> Option<wgpu::BlendState> {
688 let premult_alpha = wgpu::BlendComponent::OVER;
689 let additive = wgpu::BlendComponent {
690 src_factor: wgpu::BlendFactor::One,
691 dst_factor: wgpu::BlendFactor::One,
692 operation: wgpu::BlendOperation::Add,
693 };
694 Some(match mode {
695 repose_core::BlendMode::Add => wgpu::BlendState {
696 color: additive,
697 alpha: additive,
698 },
699 repose_core::BlendMode::Multiply => wgpu::BlendState {
700 color: wgpu::BlendComponent {
701 src_factor: wgpu::BlendFactor::Dst,
702 dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
703 operation: wgpu::BlendOperation::Add,
704 },
705 alpha: premult_alpha,
706 },
707 repose_core::BlendMode::Screen => wgpu::BlendState {
708 color: wgpu::BlendComponent {
709 src_factor: wgpu::BlendFactor::One,
710 dst_factor: wgpu::BlendFactor::OneMinusSrc,
711 operation: wgpu::BlendOperation::Add,
712 },
713 alpha: premult_alpha,
714 },
715 repose_core::BlendMode::Darken => wgpu::BlendState {
716 color: wgpu::BlendComponent {
717 src_factor: wgpu::BlendFactor::One,
718 dst_factor: wgpu::BlendFactor::One,
719 operation: wgpu::BlendOperation::Min,
720 },
721 alpha: premult_alpha,
722 },
723 repose_core::BlendMode::Lighten => wgpu::BlendState {
724 color: wgpu::BlendComponent {
725 src_factor: wgpu::BlendFactor::One,
726 dst_factor: wgpu::BlendFactor::One,
727 operation: wgpu::BlendOperation::Max,
728 },
729 alpha: premult_alpha,
730 },
731 _ => return None,
732 })
733}
734
735fn color_filter_fields(filter: ColorFilter) -> ([f32; 4], u32) {
739 match filter {
740 ColorFilter::None => ([0.0; 4], 0),
741 ColorFilter::Tint(_) => ([0.0; 4], 0),
742 ColorFilter::Blend { color, mode } => (color.to_linear(), mode.shader_mode()),
743 }
744}
745
746fn projected_rect(map: &[f32; 9], rect: repose_core::Rect) -> repose_core::Rect {
749 let corners = [
750 (rect.x, rect.y),
751 (rect.x + rect.w, rect.y),
752 (rect.x + rect.w, rect.y + rect.h),
753 (rect.x, rect.y + rect.h),
754 ];
755 let mut min_x = f32::INFINITY;
756 let mut min_y = f32::INFINITY;
757 let mut max_x = f32::NEG_INFINITY;
758 let mut max_y = f32::NEG_INFINITY;
759 for (x, y) in corners {
760 let w = map[6] * x + map[7] * y + map[8];
761 let w = if w.abs() < 1e-6 {
762 if w < 0.0 { -1e-6 } else { 1e-6 }
763 } else {
764 w
765 };
766 let px = (map[0] * x + map[1] * y + map[2]) / w;
767 let py = (map[3] * x + map[4] * y + map[5]) / w;
768 min_x = min_x.min(px);
769 min_y = min_y.min(py);
770 max_x = max_x.max(px);
771 max_y = max_y.max(py);
772 }
773 repose_core::Rect {
774 x: min_x,
775 y: min_y,
776 w: (max_x - min_x).max(0.0),
777 h: (max_y - min_y).max(0.0),
778 }
779}
780
781fn layer_group_color(alpha: f32, filter: ColorFilter) -> [f32; 4] {
785 let mut color = [1.0f32, 1.0, 1.0, alpha];
786 if let ColorFilter::Tint(tint) = filter {
787 let tint = tint.to_linear();
788 for i in 0..4 {
789 color[i] *= tint[i];
790 }
791 }
792 color
793}
794
795fn uv_for_layer(layer: &LayerTarget) -> (f32, f32) {
796 (
797 layer.rect_px.2 / layer.width.max(1) as f32,
798 layer.rect_px.3 / layer.height.max(1) as f32,
799 )
800}
801
802#[derive(Clone)]
807struct Pipelines {
808 rects: wgpu::RenderPipeline,
809 borders: wgpu::RenderPipeline,
810 ellipses: wgpu::RenderPipeline,
811 ellipse_borders: wgpu::RenderPipeline,
812 arcs: wgpu::RenderPipeline,
813 text_mask: wgpu::RenderPipeline,
814 text_color: wgpu::RenderPipeline,
815 image_rgba: wgpu::RenderPipeline,
816 image_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()],
820 coverage: wgpu::RenderPipeline,
824 image_nv12: wgpu::RenderPipeline,
825 image_nv12_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()],
828 blur: wgpu::RenderPipeline,
829 inset_shadow: wgpu::RenderPipeline,
830 blur_content: wgpu::RenderPipeline,
831 blur_content_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()],
834 clip_bin: wgpu::RenderPipeline,
835 clip_dec: wgpu::RenderPipeline,
836 slug: Option<wgpu::RenderPipeline>,
837 mesh: wgpu::RenderPipeline,
841 mesh_overlay: wgpu::RenderPipeline,
844 mesh_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()],
849 blend_layer: wgpu::RenderPipeline,
853 mesh_clip_inc: wgpu::RenderPipeline,
855 mesh_clip_dec: wgpu::RenderPipeline,
857 projective_layer: wgpu::RenderPipeline,
861 projective_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()],
864}
865
866fn vattrs(spec: &[(u32, u64, wgpu::VertexFormat)]) -> Vec<wgpu::VertexAttribute> {
870 spec.iter()
871 .map(|&(shader_location, offset, format)| wgpu::VertexAttribute {
872 shader_location,
873 offset,
874 format,
875 })
876 .collect()
877}
878
879macro_rules! field_offset {
882 ($ty:ty, $field:ident) => {
883 std::mem::offset_of!($ty, $field) as u64
884 };
885}
886
887impl Pipelines {
888 fn create(
889 device: &wgpu::Device,
890 format: wgpu::TextureFormat,
891 sample_count: u32,
892 globals_layout: &wgpu::BindGroupLayout,
893 shape_stops_layout: &wgpu::BindGroupLayout,
894 text_bind_layout: &wgpu::BindGroupLayout,
895 image_bind_layout_nv12: &wgpu::BindGroupLayout,
896 clip_pipeline_layout: &wgpu::PipelineLayout,
897 stencil_for_content: &wgpu::DepthStencilState,
898 stencil_for_clip_inc: &wgpu::DepthStencilState,
899 stencil_for_clip_dec: &wgpu::DepthStencilState,
900 clip_vertex_layout: &wgpu::VertexBufferLayout,
901 mesh_bind_layout: &wgpu::BindGroupLayout,
902 ) -> Self {
903 let msaa_state = wgpu::MultisampleState {
904 count: sample_count,
905 mask: !0,
906 alpha_to_coverage_enabled: false,
907 };
908
909 macro_rules! make_content_pipeline {
910 ($name:ident, $shader:literal, $inst_type:ty, $attrs:expr) => {
911 let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
912 label: Some(concat!($shader, ".wgsl")),
913 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(concat!(
914 env!("OUT_DIR"),
915 "/",
916 $shader,
917 ".wgsl"
918 )))),
919 });
920 let pipeline_layout =
921 device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
922 label: Some(concat!($shader, " pipeline layout")),
923 bind_group_layouts: &[Some(globals_layout), Some(shape_stops_layout)],
924 immediate_size: 0,
925 });
926 let $name = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
927 label: Some(concat!($shader, " pipeline")),
928 layout: Some(&pipeline_layout),
929 vertex: wgpu::VertexState {
930 module: &shader_module,
931 entry_point: Some("vs_main"),
932 buffers: &[Some(wgpu::VertexBufferLayout {
933 array_stride: std::mem::size_of::<$inst_type>() as u64,
934 step_mode: wgpu::VertexStepMode::Instance,
935 attributes: $attrs,
936 })],
937 compilation_options: wgpu::PipelineCompilationOptions::default(),
938 },
939 fragment: Some(wgpu::FragmentState {
940 module: &shader_module,
941 entry_point: Some("fs_main"),
942 targets: &[Some(wgpu::ColorTargetState {
943 format,
944 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
945 write_mask: wgpu::ColorWrites::ALL,
946 })],
947 compilation_options: wgpu::PipelineCompilationOptions::default(),
948 }),
949 primitive: wgpu::PrimitiveState::default(),
950 depth_stencil: Some(stencil_for_content.clone()),
951 multisample: msaa_state,
952 multiview_mask: None,
953 cache: None,
954 });
955 };
956 }
957
958 let rect_attrs = vattrs(&[
959 (
960 0,
961 field_offset!(RectInstance, xywh),
962 wgpu::VertexFormat::Float32x4,
963 ),
964 (
965 1,
966 field_offset!(RectInstance, radii),
967 wgpu::VertexFormat::Float32x4,
968 ),
969 (
970 2,
971 field_offset!(RectInstance, color0),
972 wgpu::VertexFormat::Float32x4,
973 ),
974 (
975 3,
976 field_offset!(RectInstance, color1),
977 wgpu::VertexFormat::Float32x4,
978 ),
979 (
980 4,
981 field_offset!(RectInstance, fwd_mat),
982 wgpu::VertexFormat::Float32x4,
983 ),
984 (
985 5,
986 field_offset!(RectInstance, grad),
987 wgpu::VertexFormat::Float32x4,
988 ),
989 (
990 6,
991 field_offset!(RectInstance, bits),
992 wgpu::VertexFormat::Uint32,
993 ),
994 ]);
995 let border_attrs = vattrs(&[
996 (
997 0,
998 field_offset!(BorderInstance, xywh),
999 wgpu::VertexFormat::Float32x4,
1000 ),
1001 (
1002 1,
1003 field_offset!(BorderInstance, radii),
1004 wgpu::VertexFormat::Float32x4,
1005 ),
1006 (
1007 2,
1008 field_offset!(BorderInstance, color0),
1009 wgpu::VertexFormat::Float32x4,
1010 ),
1011 (
1012 3,
1013 field_offset!(BorderInstance, color1),
1014 wgpu::VertexFormat::Float32x4,
1015 ),
1016 (
1017 4,
1018 field_offset!(BorderInstance, fwd_mat),
1019 wgpu::VertexFormat::Float32x4,
1020 ),
1021 (
1022 5,
1023 field_offset!(BorderInstance, grad),
1024 wgpu::VertexFormat::Float32x4,
1025 ),
1026 (
1027 6,
1028 field_offset!(BorderInstance, bits),
1029 wgpu::VertexFormat::Uint32,
1030 ),
1031 (
1032 7,
1033 field_offset!(BorderInstance, stroke),
1034 wgpu::VertexFormat::Float32,
1035 ),
1036 ]);
1037 let ellipse_attrs = vattrs(&[
1038 (
1039 0,
1040 field_offset!(EllipseInstance, xywh),
1041 wgpu::VertexFormat::Float32x4,
1042 ),
1043 (
1044 1,
1045 field_offset!(EllipseInstance, color0),
1046 wgpu::VertexFormat::Float32x4,
1047 ),
1048 (
1049 2,
1050 field_offset!(EllipseInstance, color1),
1051 wgpu::VertexFormat::Float32x4,
1052 ),
1053 (
1054 3,
1055 field_offset!(EllipseInstance, fwd_mat),
1056 wgpu::VertexFormat::Float32x4,
1057 ),
1058 (
1059 4,
1060 field_offset!(EllipseInstance, grad),
1061 wgpu::VertexFormat::Float32x4,
1062 ),
1063 (
1064 5,
1065 field_offset!(EllipseInstance, bits),
1066 wgpu::VertexFormat::Uint32,
1067 ),
1068 ]);
1069 let ellipse_border_attrs = vattrs(&[
1070 (
1071 0,
1072 field_offset!(EllipseBorderInstance, xywh),
1073 wgpu::VertexFormat::Float32x4,
1074 ),
1075 (
1076 1,
1077 field_offset!(EllipseBorderInstance, color0),
1078 wgpu::VertexFormat::Float32x4,
1079 ),
1080 (
1081 2,
1082 field_offset!(EllipseBorderInstance, color1),
1083 wgpu::VertexFormat::Float32x4,
1084 ),
1085 (
1086 3,
1087 field_offset!(EllipseBorderInstance, fwd_mat),
1088 wgpu::VertexFormat::Float32x4,
1089 ),
1090 (
1091 4,
1092 field_offset!(EllipseBorderInstance, grad),
1093 wgpu::VertexFormat::Float32x4,
1094 ),
1095 (
1096 5,
1097 field_offset!(EllipseBorderInstance, bits),
1098 wgpu::VertexFormat::Uint32,
1099 ),
1100 (
1101 6,
1102 field_offset!(EllipseBorderInstance, stroke),
1103 wgpu::VertexFormat::Float32,
1104 ),
1105 (
1106 7,
1107 field_offset!(EllipseBorderInstance, pad),
1108 wgpu::VertexFormat::Float32,
1109 ),
1110 ]);
1111
1112 make_content_pipeline!(rects, "rect", RectInstance, &rect_attrs);
1113 make_content_pipeline!(borders, "border", BorderInstance, &border_attrs);
1114 make_content_pipeline!(ellipses, "ellipse", EllipseInstance, &ellipse_attrs);
1115 make_content_pipeline!(
1116 ellipse_borders,
1117 "ellipse_border",
1118 EllipseBorderInstance,
1119 &ellipse_border_attrs
1120 );
1121
1122 let arc_attrs = vattrs(&[
1123 (
1124 0,
1125 field_offset!(ArcInstance, xywh),
1126 wgpu::VertexFormat::Float32x4,
1127 ),
1128 (
1129 1,
1130 field_offset!(ArcInstance, color0),
1131 wgpu::VertexFormat::Float32x4,
1132 ),
1133 (
1134 2,
1135 field_offset!(ArcInstance, color1),
1136 wgpu::VertexFormat::Float32x4,
1137 ),
1138 (
1139 3,
1140 field_offset!(ArcInstance, fwd_mat),
1141 wgpu::VertexFormat::Float32x4,
1142 ),
1143 (
1144 4,
1145 field_offset!(ArcInstance, grad),
1146 wgpu::VertexFormat::Float32x4,
1147 ),
1148 (
1149 5,
1150 field_offset!(ArcInstance, bits),
1151 wgpu::VertexFormat::Uint32,
1152 ),
1153 (
1154 6,
1155 field_offset!(ArcInstance, start_angle),
1156 wgpu::VertexFormat::Float32,
1157 ),
1158 (
1159 7,
1160 field_offset!(ArcInstance, sweep_angle),
1161 wgpu::VertexFormat::Float32,
1162 ),
1163 (
1164 8,
1165 field_offset!(ArcInstance, stroke),
1166 wgpu::VertexFormat::Float32,
1167 ),
1168 (
1169 9,
1170 field_offset!(ArcInstance, pad),
1171 wgpu::VertexFormat::Float32,
1172 ),
1173 ]);
1174
1175 make_content_pipeline!(arcs, "arc", ArcInstance, &arc_attrs);
1176
1177 let text_mask_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1179 label: Some("text.wgsl"),
1180 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shaders/text.wgsl"))),
1181 });
1182 let text_color_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1184 label: Some("text_color.wgsl"),
1185 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
1186 "shaders/text_color.wgsl"
1187 ))),
1188 });
1189 let text_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1190 label: Some("text pipeline layout"),
1191 bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
1192 immediate_size: 0,
1193 });
1194 let glyph_vertex = wgpu::VertexBufferLayout {
1195 array_stride: std::mem::size_of::<GlyphInstance>() as u64,
1196 step_mode: wgpu::VertexStepMode::Instance,
1197 attributes: &[
1198 wgpu::VertexAttribute {
1199 shader_location: 0,
1200 offset: 0,
1201 format: wgpu::VertexFormat::Float32x4,
1202 },
1203 wgpu::VertexAttribute {
1204 shader_location: 1,
1205 offset: 16,
1206 format: wgpu::VertexFormat::Float32x4,
1207 },
1208 wgpu::VertexAttribute {
1209 shader_location: 2,
1210 offset: 32,
1211 format: wgpu::VertexFormat::Float32x4,
1212 },
1213 wgpu::VertexAttribute {
1214 shader_location: 3,
1215 offset: 48,
1216 format: wgpu::VertexFormat::Float32x4,
1217 },
1218 ],
1219 };
1220 let text_mask = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1221 label: Some("text pipeline (mask)"),
1222 layout: Some(&text_pipeline_layout),
1223 vertex: wgpu::VertexState {
1224 module: &text_mask_shader,
1225 entry_point: Some("vs_main"),
1226 buffers: &[Some(glyph_vertex.clone())],
1227 compilation_options: wgpu::PipelineCompilationOptions::default(),
1228 },
1229 fragment: Some(wgpu::FragmentState {
1230 module: &text_mask_shader,
1231 entry_point: Some("fs_main"),
1232 targets: &[Some(wgpu::ColorTargetState {
1233 format,
1234 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
1235 write_mask: wgpu::ColorWrites::ALL,
1236 })],
1237 compilation_options: wgpu::PipelineCompilationOptions::default(),
1238 }),
1239 primitive: wgpu::PrimitiveState::default(),
1240 depth_stencil: Some(stencil_for_content.clone()),
1241 multisample: msaa_state,
1242 multiview_mask: None,
1243 cache: None,
1244 });
1245 let text_color_pipeline =
1246 |label: &'static str, blend: wgpu::BlendState| -> wgpu::RenderPipeline {
1247 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1248 label: Some(label),
1249 layout: Some(&text_pipeline_layout),
1250 vertex: wgpu::VertexState {
1251 module: &text_color_shader,
1252 entry_point: Some("vs_main"),
1253 buffers: &[Some(glyph_vertex.clone())],
1254 compilation_options: wgpu::PipelineCompilationOptions::default(),
1255 },
1256 fragment: Some(wgpu::FragmentState {
1257 module: &text_color_shader,
1258 entry_point: Some("fs_main"),
1259 targets: &[Some(wgpu::ColorTargetState {
1260 format,
1261 blend: Some(blend),
1262 write_mask: wgpu::ColorWrites::ALL,
1263 })],
1264 compilation_options: wgpu::PipelineCompilationOptions::default(),
1265 }),
1266 primitive: wgpu::PrimitiveState::default(),
1267 depth_stencil: Some(stencil_for_content.clone()),
1268 multisample: msaa_state,
1269 multiview_mask: None,
1270 cache: None,
1271 })
1272 };
1273 let text_color = text_color_pipeline(
1274 "text pipeline (color)",
1275 wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
1276 );
1277 let image_rgba = text_color.clone();
1279 let image_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()] =
1282 std::array::from_fn(|index| {
1283 let blend = fixed_function_blend(FIXED_FUNCTION_BLENDS[index])
1284 .unwrap_or(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING);
1285 text_color_pipeline("image pipeline (blend)", blend)
1286 });
1287
1288 let coverage_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1292 label: Some("coverage.wgsl"),
1293 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shaders/coverage.wgsl"))),
1294 });
1295 let coverage = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1296 label: Some("coverage pipeline (tinted a8)"),
1297 layout: Some(&text_pipeline_layout),
1298 vertex: wgpu::VertexState {
1299 module: &coverage_shader,
1300 entry_point: Some("vs_main"),
1301 buffers: &[Some(glyph_vertex.clone())],
1302 compilation_options: wgpu::PipelineCompilationOptions::default(),
1303 },
1304 fragment: Some(wgpu::FragmentState {
1305 module: &coverage_shader,
1306 entry_point: Some("fs_main"),
1307 targets: &[Some(wgpu::ColorTargetState {
1308 format,
1309 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
1310 write_mask: wgpu::ColorWrites::ALL,
1311 })],
1312 compilation_options: wgpu::PipelineCompilationOptions::default(),
1313 }),
1314 primitive: wgpu::PrimitiveState::default(),
1315 depth_stencil: Some(stencil_for_content.clone()),
1316 multisample: msaa_state,
1317 multiview_mask: None,
1318 cache: None,
1319 });
1320
1321 let blur_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1322 label: Some("blur_separable.wgsl"),
1323 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
1324 "shaders/blur_separable.wgsl"
1325 ))),
1326 });
1327 let blur_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1328 label: Some("blur pipeline layout"),
1329 bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
1330 immediate_size: 0,
1331 });
1332 let blur_layout = wgpu::VertexBufferLayout {
1333 array_stride: std::mem::size_of::<BlurInstance>() as u64,
1334 step_mode: wgpu::VertexStepMode::Instance,
1335 attributes: &[
1336 wgpu::VertexAttribute {
1337 shader_location: 0,
1338 offset: 0,
1339 format: wgpu::VertexFormat::Float32x4,
1340 },
1341 wgpu::VertexAttribute {
1342 shader_location: 1,
1343 offset: 16,
1344 format: wgpu::VertexFormat::Float32x4,
1345 },
1346 wgpu::VertexAttribute {
1347 shader_location: 2,
1348 offset: 32,
1349 format: wgpu::VertexFormat::Float32x4,
1350 },
1351 wgpu::VertexAttribute {
1352 shader_location: 3,
1353 offset: 48,
1354 format: wgpu::VertexFormat::Float32x2,
1355 },
1356 wgpu::VertexAttribute {
1357 shader_location: 4,
1358 offset: 56,
1359 format: wgpu::VertexFormat::Float32x4,
1360 },
1361 wgpu::VertexAttribute {
1362 shader_location: 5,
1363 offset: 72,
1364 format: wgpu::VertexFormat::Uint32,
1365 },
1366 wgpu::VertexAttribute {
1367 shader_location: 6,
1368 offset: 76,
1369 format: wgpu::VertexFormat::Uint32,
1370 },
1371 wgpu::VertexAttribute {
1372 shader_location: 7,
1373 offset: 80,
1374 format: wgpu::VertexFormat::Float32x4,
1375 },
1376 ],
1377 };
1378 let blur = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1379 label: Some("blur pipeline"),
1380 layout: Some(&blur_pipeline_layout),
1381 vertex: wgpu::VertexState {
1382 module: &blur_shader,
1383 entry_point: Some("vs_main"),
1384 buffers: &[Some(blur_layout.clone())],
1385 compilation_options: wgpu::PipelineCompilationOptions::default(),
1386 },
1387 fragment: Some(wgpu::FragmentState {
1388 module: &blur_shader,
1389 entry_point: Some("fs_alpha"),
1390 targets: &[Some(wgpu::ColorTargetState {
1391 format,
1392 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
1393 write_mask: wgpu::ColorWrites::ALL,
1394 })],
1395 compilation_options: wgpu::PipelineCompilationOptions::default(),
1396 }),
1397 primitive: wgpu::PrimitiveState::default(),
1398 depth_stencil: Some(stencil_for_content.clone()),
1399 multisample: msaa_state,
1400 multiview_mask: None,
1401 cache: None,
1402 });
1403
1404 let inset_shadow = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1405 label: Some("inset shadow pipeline"),
1406 layout: Some(&blur_pipeline_layout),
1407 vertex: wgpu::VertexState {
1408 module: &blur_shader,
1409 entry_point: Some("vs_main"),
1410 buffers: &[Some(blur_layout.clone())],
1411 compilation_options: wgpu::PipelineCompilationOptions::default(),
1412 },
1413 fragment: Some(wgpu::FragmentState {
1414 module: &blur_shader,
1415 entry_point: Some("fs_inset"),
1416 targets: &[Some(wgpu::ColorTargetState {
1417 format,
1418 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
1419 write_mask: wgpu::ColorWrites::ALL,
1420 })],
1421 compilation_options: wgpu::PipelineCompilationOptions::default(),
1422 }),
1423 primitive: wgpu::PrimitiveState::default(),
1424 depth_stencil: Some(stencil_for_content.clone()),
1425 multisample: msaa_state,
1426 multiview_mask: None,
1427 cache: None,
1428 });
1429
1430 let blur_content_pipeline = |label: &'static str, blend: wgpu::BlendState| {
1431 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1432 label: Some(label),
1433 layout: Some(&blur_pipeline_layout),
1434 vertex: wgpu::VertexState {
1435 module: &blur_shader,
1436 entry_point: Some("vs_main"),
1437 buffers: &[Some(blur_layout.clone())],
1438 compilation_options: wgpu::PipelineCompilationOptions::default(),
1439 },
1440 fragment: Some(wgpu::FragmentState {
1441 module: &blur_shader,
1442 entry_point: Some("fs_color"),
1443 targets: &[Some(wgpu::ColorTargetState {
1444 format,
1445 blend: Some(blend),
1446 write_mask: wgpu::ColorWrites::ALL,
1447 })],
1448 compilation_options: wgpu::PipelineCompilationOptions::default(),
1449 }),
1450 primitive: wgpu::PrimitiveState::default(),
1451 depth_stencil: Some(stencil_for_content.clone()),
1452 multisample: msaa_state,
1453 multiview_mask: None,
1454 cache: None,
1455 })
1456 };
1457 let blur_content = blur_content_pipeline(
1458 "blur content pipeline",
1459 wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
1460 );
1461 let blur_content_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()] =
1462 std::array::from_fn(|index| {
1463 let blend = fixed_function_blend(FIXED_FUNCTION_BLENDS[index])
1464 .unwrap_or(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING);
1465 blur_content_pipeline("blur content pipeline (blend)", blend)
1466 });
1467
1468 let image_nv12_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1470 label: Some("image_nv12.wgsl"),
1471 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
1472 "shaders/image_nv12.wgsl"
1473 ))),
1474 });
1475 let image_nv12_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1476 label: Some("image nv12 pipeline layout"),
1477 bind_group_layouts: &[Some(globals_layout), Some(image_bind_layout_nv12)],
1478 immediate_size: 0,
1479 });
1480 let nv12_vertex_layout = wgpu::VertexBufferLayout {
1481 array_stride: std::mem::size_of::<Nv12Instance>() as u64,
1482 step_mode: wgpu::VertexStepMode::Instance,
1483 attributes: &[
1484 wgpu::VertexAttribute {
1485 shader_location: 0,
1486 offset: 0,
1487 format: wgpu::VertexFormat::Float32x4,
1488 },
1489 wgpu::VertexAttribute {
1490 shader_location: 1,
1491 offset: 16,
1492 format: wgpu::VertexFormat::Float32x4,
1493 },
1494 wgpu::VertexAttribute {
1495 shader_location: 2,
1496 offset: 32,
1497 format: wgpu::VertexFormat::Float32x4,
1498 },
1499 wgpu::VertexAttribute {
1500 shader_location: 3,
1501 offset: 48,
1502 format: wgpu::VertexFormat::Float32,
1503 },
1504 wgpu::VertexAttribute {
1505 shader_location: 4,
1506 offset: 52,
1507 format: wgpu::VertexFormat::Float32,
1508 },
1509 wgpu::VertexAttribute {
1510 shader_location: 5,
1511 offset: 56,
1512 format: wgpu::VertexFormat::Float32x4,
1513 },
1514 ],
1515 };
1516 let nv12_pipeline =
1517 |label: &'static str, blend: wgpu::BlendState| -> wgpu::RenderPipeline {
1518 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1519 label: Some(label),
1520 layout: Some(&image_nv12_layout),
1521 vertex: wgpu::VertexState {
1522 module: &image_nv12_shader,
1523 entry_point: Some("vs_main"),
1524 buffers: &[Some(nv12_vertex_layout.clone())],
1525 compilation_options: wgpu::PipelineCompilationOptions::default(),
1526 },
1527 fragment: Some(wgpu::FragmentState {
1528 module: &image_nv12_shader,
1529 entry_point: Some("fs_main"),
1530 targets: &[Some(wgpu::ColorTargetState {
1531 format,
1532 blend: Some(blend),
1533 write_mask: wgpu::ColorWrites::ALL,
1534 })],
1535 compilation_options: wgpu::PipelineCompilationOptions::default(),
1536 }),
1537 primitive: wgpu::PrimitiveState::default(),
1538 depth_stencil: Some(stencil_for_content.clone()),
1539 multisample: msaa_state,
1540 multiview_mask: None,
1541 cache: None,
1542 })
1543 };
1544 let image_nv12 = nv12_pipeline(
1545 "image nv12 pipeline",
1546 wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
1547 );
1548 let image_nv12_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()] =
1549 std::array::from_fn(|index| {
1550 let blend = fixed_function_blend(FIXED_FUNCTION_BLENDS[index])
1551 .unwrap_or(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING);
1552 nv12_pipeline("image nv12 pipeline (blend)", blend)
1553 });
1554
1555 let clip_color_target = wgpu::ColorTargetState {
1556 format,
1557 blend: None,
1558 write_mask: wgpu::ColorWrites::empty(),
1559 };
1560
1561 let clip_shader_bin = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1563 label: Some("clip_round_rect_bin.wgsl"),
1564 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
1565 "shaders/clip_round_rect_bin.wgsl"
1566 ))),
1567 });
1568 let clip_bin = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1569 label: Some("clip pipeline (bin)"),
1570 layout: Some(clip_pipeline_layout),
1571 vertex: wgpu::VertexState {
1572 module: &clip_shader_bin,
1573 entry_point: Some("vs_main"),
1574 buffers: &[Some(clip_vertex_layout.clone())],
1575 compilation_options: wgpu::PipelineCompilationOptions::default(),
1576 },
1577 fragment: Some(wgpu::FragmentState {
1578 module: &clip_shader_bin,
1579 entry_point: Some("fs_main"),
1580 targets: &[Some(clip_color_target.clone())],
1581 compilation_options: wgpu::PipelineCompilationOptions::default(),
1582 }),
1583 primitive: wgpu::PrimitiveState::default(),
1584 depth_stencil: Some(stencil_for_clip_inc.clone()),
1585 multisample: wgpu::MultisampleState {
1586 count: sample_count,
1587 mask: !0,
1588 alpha_to_coverage_enabled: false,
1589 },
1590 multiview_mask: None,
1591 cache: None,
1592 });
1593 let clip_dec = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1594 label: Some("clip pipeline (dec)"),
1595 layout: Some(clip_pipeline_layout),
1596 vertex: wgpu::VertexState {
1597 module: &clip_shader_bin,
1598 entry_point: Some("vs_main"),
1599 buffers: &[Some(clip_vertex_layout.clone())],
1600 compilation_options: wgpu::PipelineCompilationOptions::default(),
1601 },
1602 fragment: Some(wgpu::FragmentState {
1603 module: &clip_shader_bin,
1604 entry_point: Some("fs_main"),
1605 targets: &[Some(clip_color_target.clone())],
1606 compilation_options: wgpu::PipelineCompilationOptions::default(),
1607 }),
1608 primitive: wgpu::PrimitiveState::default(),
1609 depth_stencil: Some(stencil_for_clip_dec.clone()),
1610 multisample: wgpu::MultisampleState {
1611 count: sample_count,
1612 mask: !0,
1613 alpha_to_coverage_enabled: false,
1614 },
1615 multiview_mask: None,
1616 cache: None,
1617 });
1618
1619 let slug = Some(slug::create_pipeline(
1620 device,
1621 format,
1622 sample_count,
1623 stencil_for_content,
1624 ));
1625
1626 let mesh_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1628 label: Some("mesh.wgsl"),
1629 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shaders/mesh.wgsl"))),
1630 });
1631 let mesh_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1632 label: Some("mesh pipeline layout"),
1633 bind_group_layouts: &[Some(globals_layout), Some(mesh_bind_layout)],
1634 immediate_size: 0,
1635 });
1636 let mesh_vertex_layout = wgpu::VertexBufferLayout {
1637 array_stride: std::mem::size_of::<MeshVertex>() as u64,
1638 step_mode: wgpu::VertexStepMode::Vertex,
1639 attributes: &[
1640 wgpu::VertexAttribute {
1641 shader_location: 0,
1642 offset: 0,
1643 format: wgpu::VertexFormat::Float32x2,
1644 },
1645 wgpu::VertexAttribute {
1646 shader_location: 1,
1647 offset: 8,
1648 format: wgpu::VertexFormat::Float32x4,
1649 },
1650 wgpu::VertexAttribute {
1651 shader_location: 2,
1652 offset: 24,
1653 format: wgpu::VertexFormat::Float32x2,
1654 },
1655 ],
1656 };
1657 let mesh_instance_layout = wgpu::VertexBufferLayout {
1658 array_stride: std::mem::size_of::<MeshInstance>() as u64,
1659 step_mode: wgpu::VertexStepMode::Instance,
1660 attributes: &[
1661 wgpu::VertexAttribute {
1662 shader_location: 3,
1663 offset: 0,
1664 format: wgpu::VertexFormat::Float32x4,
1665 },
1666 wgpu::VertexAttribute {
1667 shader_location: 4,
1668 offset: 16,
1669 format: wgpu::VertexFormat::Float32x4,
1670 },
1671 ],
1672 };
1673 let make_mesh_pipeline =
1674 |label: &str, depth: &wgpu::DepthStencilState, color: &wgpu::ColorTargetState| {
1675 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1676 label: Some(label),
1677 layout: Some(&mesh_pipeline_layout),
1678 vertex: wgpu::VertexState {
1679 module: &mesh_shader,
1680 entry_point: Some("vs_main"),
1681 buffers: &[
1682 Some(mesh_vertex_layout.clone()),
1683 Some(mesh_instance_layout.clone()),
1684 ],
1685 compilation_options: wgpu::PipelineCompilationOptions::default(),
1686 },
1687 fragment: Some(wgpu::FragmentState {
1688 module: &mesh_shader,
1689 entry_point: Some("fs_main"),
1690 targets: &[Some(color.clone())],
1691 compilation_options: wgpu::PipelineCompilationOptions::default(),
1692 }),
1693 primitive: wgpu::PrimitiveState {
1694 topology: wgpu::PrimitiveTopology::TriangleList,
1695 ..Default::default()
1696 },
1697 depth_stencil: Some(depth.clone()),
1698 multisample: msaa_state,
1699 multiview_mask: None,
1700 cache: None,
1701 })
1702 };
1703 let mesh_color_target = wgpu::ColorTargetState {
1704 format,
1705 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
1706 write_mask: wgpu::ColorWrites::ALL,
1707 };
1708 let mut stencil_for_mesh = stencil_for_content.clone();
1709 stencil_for_mesh.stencil.front.compare = wgpu::CompareFunction::Equal;
1710 stencil_for_mesh.stencil.back.compare = wgpu::CompareFunction::Equal;
1711 let mut stencil_for_overlay = stencil_for_content.clone();
1712 stencil_for_overlay.stencil.front.compare = wgpu::CompareFunction::LessEqual;
1713 stencil_for_overlay.stencil.back.compare = wgpu::CompareFunction::LessEqual;
1714 let mesh = make_mesh_pipeline("mesh pipeline", &stencil_for_mesh, &mesh_color_target);
1715 let mesh_overlay = make_mesh_pipeline(
1716 "mesh overlay pipeline",
1717 &stencil_for_overlay,
1718 &mesh_color_target,
1719 );
1720 let mesh_clip_inc = make_mesh_pipeline(
1721 "mesh clip (inc) pipeline",
1722 stencil_for_clip_inc,
1723 &clip_color_target,
1724 );
1725 let mesh_clip_dec = make_mesh_pipeline(
1726 "mesh clip (dec) pipeline",
1727 stencil_for_clip_dec,
1728 &clip_color_target,
1729 );
1730 let mesh_blend_target = |blend: wgpu::BlendState| wgpu::ColorTargetState {
1731 format,
1732 blend: Some(blend),
1733 write_mask: wgpu::ColorWrites::ALL,
1734 };
1735 let mesh_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()] =
1736 std::array::from_fn(|index| {
1737 let mode = FIXED_FUNCTION_BLENDS[index];
1738 let blend = fixed_function_blend(mode).unwrap_or(wgpu::BlendState::REPLACE);
1739 make_mesh_pipeline(
1740 match mode {
1741 repose_core::BlendMode::Add => "mesh pipeline (add)",
1742 repose_core::BlendMode::Multiply => "mesh pipeline (multiply)",
1743 repose_core::BlendMode::Screen => "mesh pipeline (screen)",
1744 repose_core::BlendMode::Darken => "mesh pipeline (darken)",
1745 _ => "mesh pipeline (lighten)",
1746 },
1747 &stencil_for_mesh,
1748 &mesh_blend_target(blend),
1749 )
1750 });
1751 let projective_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1756 label: Some("projective_layer.wgsl"),
1757 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
1758 "shaders/projective_layer.wgsl"
1759 ))),
1760 });
1761 let projective_pipeline_layout =
1762 device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1763 label: Some("projective layer pipeline layout"),
1764 bind_group_layouts: &[Some(globals_layout), Some(text_bind_layout)],
1765 immediate_size: 0,
1766 });
1767 let projective_vertex_layout = wgpu::VertexBufferLayout {
1768 array_stride: std::mem::size_of::<ProjectiveInstance>() as u64,
1769 step_mode: wgpu::VertexStepMode::Instance,
1770 attributes: &[
1771 wgpu::VertexAttribute {
1772 shader_location: 0,
1773 offset: 0,
1774 format: wgpu::VertexFormat::Float32x2,
1775 },
1776 wgpu::VertexAttribute {
1777 shader_location: 1,
1778 offset: 8,
1779 format: wgpu::VertexFormat::Float32x2,
1780 },
1781 wgpu::VertexAttribute {
1782 shader_location: 2,
1783 offset: 16,
1784 format: wgpu::VertexFormat::Float32x2,
1785 },
1786 wgpu::VertexAttribute {
1787 shader_location: 3,
1788 offset: 24,
1789 format: wgpu::VertexFormat::Float32x2,
1790 },
1791 wgpu::VertexAttribute {
1792 shader_location: 4,
1793 offset: 32,
1794 format: wgpu::VertexFormat::Float32x4,
1795 },
1796 wgpu::VertexAttribute {
1797 shader_location: 5,
1798 offset: 48,
1799 format: wgpu::VertexFormat::Float32x4,
1800 },
1801 wgpu::VertexAttribute {
1802 shader_location: 6,
1803 offset: field_offset!(ProjectiveInstance, alpha),
1804 format: wgpu::VertexFormat::Float32,
1805 },
1806 wgpu::VertexAttribute {
1807 shader_location: 7,
1808 offset: field_offset!(ProjectiveInstance, tint),
1809 format: wgpu::VertexFormat::Float32x3,
1810 },
1811 ],
1812 };
1813 let projective_pipeline = |label: &'static str, blend: wgpu::BlendState| {
1814 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1815 label: Some(label),
1816 layout: Some(&projective_pipeline_layout),
1817 vertex: wgpu::VertexState {
1818 module: &projective_shader,
1819 entry_point: Some("vs_main"),
1820 buffers: &[Some(projective_vertex_layout.clone())],
1821 compilation_options: wgpu::PipelineCompilationOptions::default(),
1822 },
1823 fragment: Some(wgpu::FragmentState {
1824 module: &projective_shader,
1825 entry_point: Some("fs_main"),
1826 targets: &[Some(wgpu::ColorTargetState {
1827 format,
1828 blend: Some(blend),
1829 write_mask: wgpu::ColorWrites::ALL,
1830 })],
1831 compilation_options: wgpu::PipelineCompilationOptions::default(),
1832 }),
1833 primitive: wgpu::PrimitiveState::default(),
1834 depth_stencil: Some(stencil_for_content.clone()),
1835 multisample: msaa_state,
1836 multiview_mask: None,
1837 cache: None,
1838 })
1839 };
1840 let projective_layer = projective_pipeline(
1841 "projective layer composite pipeline",
1842 wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
1843 );
1844 let projective_blends: [wgpu::RenderPipeline; FIXED_FUNCTION_BLENDS.len()] =
1845 std::array::from_fn(|index| {
1846 let blend = fixed_function_blend(FIXED_FUNCTION_BLENDS[index])
1847 .unwrap_or(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING);
1848 projective_pipeline("projective layer composite pipeline (blend)", blend)
1849 });
1850
1851 let blend_layer_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
1852 label: Some("blend_layer.wgsl"),
1853 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!(
1854 "shaders/blend_layer.wgsl"
1855 ))),
1856 });
1857 let blend_layer_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
1858 label: Some("blend layer pipeline layout"),
1859 bind_group_layouts: &[
1860 Some(globals_layout),
1861 Some(text_bind_layout),
1862 Some(text_bind_layout),
1863 ],
1864 immediate_size: 0,
1865 });
1866 let blend_vertex_layout = wgpu::VertexBufferLayout {
1867 array_stride: std::mem::size_of::<BlendInstance>() as u64,
1868 step_mode: wgpu::VertexStepMode::Instance,
1869 attributes: &[
1870 wgpu::VertexAttribute {
1871 shader_location: 0,
1872 offset: field_offset!(BlendInstance, xywh),
1873 format: wgpu::VertexFormat::Float32x4,
1874 },
1875 wgpu::VertexAttribute {
1876 shader_location: 1,
1877 offset: field_offset!(BlendInstance, uv),
1878 format: wgpu::VertexFormat::Float32x4,
1879 },
1880 wgpu::VertexAttribute {
1881 shader_location: 2,
1882 offset: field_offset!(BlendInstance, color),
1883 format: wgpu::VertexFormat::Float32x4,
1884 },
1885 wgpu::VertexAttribute {
1886 shader_location: 3,
1887 offset: field_offset!(BlendInstance, fwd_mat),
1888 format: wgpu::VertexFormat::Float32x4,
1889 },
1890 wgpu::VertexAttribute {
1891 shader_location: 4,
1892 offset: field_offset!(BlendInstance, filter_color),
1893 format: wgpu::VertexFormat::Float32x4,
1894 },
1895 wgpu::VertexAttribute {
1896 shader_location: 5,
1897 offset: field_offset!(BlendInstance, mode),
1898 format: wgpu::VertexFormat::Uint32,
1899 },
1900 wgpu::VertexAttribute {
1901 shader_location: 6,
1902 offset: field_offset!(BlendInstance, filter_mode),
1903 format: wgpu::VertexFormat::Uint32,
1904 },
1905 ],
1906 };
1907 let blend_layer = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
1908 label: Some("blend layer pipeline"),
1909 layout: Some(&blend_layer_layout),
1910 vertex: wgpu::VertexState {
1911 module: &blend_layer_shader,
1912 entry_point: Some("vs_main"),
1913 buffers: &[Some(blend_vertex_layout)],
1914 compilation_options: wgpu::PipelineCompilationOptions::default(),
1915 },
1916 fragment: Some(wgpu::FragmentState {
1917 module: &blend_layer_shader,
1918 entry_point: Some("fs_main"),
1919 targets: &[Some(wgpu::ColorTargetState {
1920 format,
1921 blend: None,
1922 write_mask: wgpu::ColorWrites::ALL,
1923 })],
1924 compilation_options: wgpu::PipelineCompilationOptions::default(),
1925 }),
1926 primitive: wgpu::PrimitiveState::default(),
1927 depth_stencil: Some(stencil_for_content.clone()),
1928 multisample: msaa_state,
1929 multiview_mask: None,
1930 cache: None,
1931 });
1932
1933 Self {
1934 rects,
1935 borders,
1936 ellipses,
1937 ellipse_borders,
1938 arcs,
1939 text_mask,
1940 text_color,
1941 image_rgba,
1942 image_blends,
1943 image_nv12,
1944 image_nv12_blends,
1945 coverage,
1946 blur,
1947 inset_shadow,
1948 blur_content,
1949 blur_content_blends,
1950 clip_bin,
1951 clip_dec,
1952 slug,
1953 mesh,
1954 mesh_blends,
1955 blend_layer,
1956 mesh_overlay,
1957 mesh_clip_inc,
1958 mesh_clip_dec,
1959 projective_layer,
1960 projective_blends,
1961 }
1962 }
1963}
1964
1965fn transform_is_projective(transform: &Transform) -> bool {
1972 transform.rotation_x != 0.0 || transform.rotation_y != 0.0 || {
1973 let m = transform.projective_matrix();
1974 m[6] != 0.0 || m[7] != 0.0 || m[8] != 1.0
1975 }
1976}
1977
1978fn make_projective_instance(
1982 map: &[f32; 9],
1983 rect: repose_core::Rect,
1984 fb_w: f32,
1985 fb_h: f32,
1986 uv: [f32; 4],
1987 alpha: f32,
1988 tint: [f32; 3],
1989) -> Option<ProjectiveInstance> {
1990 let corners = [
1991 (rect.x, rect.y),
1992 (rect.x + rect.w, rect.y),
1993 (rect.x + rect.w, rect.y + rect.h),
1994 (rect.x, rect.y + rect.h),
1995 ];
1996 let mut ndc = [[0.0f32; 2]; 4];
1997 let mut ws = [1.0f32; 4];
1998 let mut all_behind = true;
1999 for (i, (x, y)) in corners.iter().enumerate() {
2000 let w_raw = map[6] * x + map[7] * y + map[8];
2001 let w = if w_raw.abs() < 1e-6 {
2002 if w_raw < 0.0 { -1e-6 } else { 1e-6 }
2003 } else {
2004 w_raw
2005 };
2006 if w > 0.0 {
2007 all_behind = false;
2008 }
2009 let px = (map[0] * x + map[1] * y + map[2]) / w;
2010 let py = (map[3] * x + map[4] * y + map[5]) / w;
2011 ndc[i] = [px / fb_w * 2.0 - 1.0, 1.0 - py / fb_h * 2.0];
2012 ws[i] = w;
2013 }
2014 if all_behind {
2015 return None;
2016 }
2017 Some(ProjectiveInstance {
2018 c0: ndc[0],
2019 c1: ndc[1],
2020 c2: ndc[2],
2021 c3: ndc[3],
2022 uv,
2023 w: ws,
2024 alpha,
2025 tint,
2026 })
2027}
2028
2029fn affine_aabb(transform: &Transform, rect: &repose_core::Rect) -> repose_core::Rect {
2032 let m = transform.linear();
2033 let (tx, ty) = (transform.translate_x, transform.translate_y);
2034 let corners = [
2035 (rect.x, rect.y),
2036 (rect.x + rect.w, rect.y),
2037 (rect.x, rect.y + rect.h),
2038 (rect.x + rect.w, rect.y + rect.h),
2039 ];
2040 let mut min_x = f32::INFINITY;
2041 let mut min_y = f32::INFINITY;
2042 let mut max_x = f32::NEG_INFINITY;
2043 let mut max_y = f32::NEG_INFINITY;
2044 for (x, y) in corners {
2045 let wx = m[0] * x + m[1] * y + tx;
2046 let wy = m[2] * x + m[3] * y + ty;
2047 min_x = min_x.min(wx);
2048 min_y = min_y.min(wy);
2049 max_x = max_x.max(wx);
2050 max_y = max_y.max(wy);
2051 }
2052 repose_core::Rect {
2053 x: min_x,
2054 y: min_y,
2055 w: (max_x - min_x).max(0.0),
2056 h: (max_y - min_y).max(0.0),
2057 }
2058}
2059
2060fn rect_to_instance_ndc(
2065 rect: repose_core::Rect,
2066 transform: &Transform,
2067 fb_w: f32,
2068 fb_h: f32,
2069) -> ([f32; 4], [f32; 4]) {
2070 let cx = rect.x + rect.w * 0.5;
2071 let cy = rect.y + rect.h * 0.5;
2072
2073 let m = transform.linear();
2074 let tx = m[0] * cx + m[1] * cy + transform.translate_x;
2075 let ty = m[2] * cx + m[3] * cy + transform.translate_y;
2076
2077 let ndc_cx = (tx / fb_w) * 2.0 - 1.0;
2078 let ndc_cy = 1.0 - (ty / fb_h) * 2.0;
2079 let ndc_w = (rect.w * transform.scale_x / fb_w) * 2.0;
2081 let ndc_h = (rect.h * transform.scale_y / fb_h) * 2.0;
2082
2083 ([ndc_cx, ndc_cy, ndc_w, ndc_h], forward_rs_mat(transform))
2084}
2085
2086fn forward_rs_mat(transform: &Transform) -> [f32; 4] {
2090 let c = transform.rotate.cos();
2091 let s = transform.rotate.sin();
2092 let (hx, hy) = (transform.shear_x, transform.shear_y);
2093 let m = [c - s * hy, c * hx - s, s + c * hy, s * hx + c];
2094 if (m[0] * m[3] - m[1] * m[2]).abs() < 1e-6 {
2095 return [1.0, 0.0, 0.0, 1.0];
2096 }
2097 m
2098}
2099
2100struct Pass {
2102 id: u64,
2103 target: PassTarget,
2104 initial_scissor: (u32, u32, u32, u32),
2106 active_scissor: Option<(u32, u32, u32, u32)>,
2109 clear_color: Option<[f32; 4]>,
2112 cmds: Vec<Cmd>,
2113}
2114
2115struct LayerState {
2116 layer_id: u32,
2117 parent_target: PassTarget,
2118 parent_scissors: Vec<repose_core::Rect>,
2119 parent_root_clip: repose_core::Rect,
2120 parent_size: (f32, f32),
2121 parent_transform: Transform,
2122 parent_scissor: Option<(u32, u32, u32, u32)>,
2123 parent_clips: Vec<ActiveClip>,
2124 alpha: f32,
2125 blur: (f32, f32),
2126 rectangle_edge: bool,
2127 blend_mode: BlendMode,
2128 color_filter: ColorFilter,
2129 compositing_strategy: CompositingStrategy,
2130 projective: bool,
2134}
2135
2136struct FlattenRecord {
2140 stack_len: usize,
2143 layer_id: u32,
2144 map: [f32; 9],
2147 layer_rect: repose_core::Rect,
2149 saved_scissor_stack: Vec<repose_core::Rect>,
2150 saved_root: repose_core::Rect,
2151 saved_size: (f32, f32),
2152 saved_active_scissor: Option<(u32, u32, u32, u32)>,
2153 saved_clips: Vec<ActiveClip>,
2154}
2155
2156const FLATTEN_ID_BASE: u32 = 0xF000_0000;
2160const MAX_GRAPHICS_LAYERS: usize = 128;
2161const MAX_GRAPHICS_LAYER_BYTES: u64 = 256 * 1024 * 1024;
2162const MAX_TRANSIENT_GRAPHICS_LAYERS: usize = 64;
2163const MAX_TRANSIENT_GRAPHICS_LAYER_BYTES: u64 = 128 * 1024 * 1024;
2164const STENCIL_BASE: u32 = 128;
2165const STENCIL_MAX_DEPTH: u32 = 127;
2166
2167#[allow(non_snake_case)]
2168enum Cmd {
2169 ClipPush {
2170 off: u64,
2171 cnt: u32,
2172 scissor: (u32, u32, u32, u32),
2173 difference: bool,
2174 applied: bool,
2175 },
2176 ClipPop {
2177 off: u64,
2178 cnt: u32,
2179 scissor: (u32, u32, u32, u32),
2181 stencil_scissor: (u32, u32, u32, u32),
2184 difference: bool,
2185 applied: bool,
2186 },
2187 Rect {
2188 off: u64,
2189 cnt: u32,
2190 },
2191 Border {
2192 off: u64,
2193 cnt: u32,
2194 },
2195 Ellipse {
2196 off: u64,
2197 cnt: u32,
2198 },
2199 EllipseBorder {
2200 off: u64,
2201 cnt: u32,
2202 },
2203 Arc {
2204 off: u64,
2205 cnt: u32,
2206 },
2207 GlyphsMask {
2208 off: u64,
2209 cnt: u32,
2210 },
2211 GlyphsColor {
2212 off: u64,
2213 cnt: u32,
2214 },
2215 GlyphsVector {
2216 off: u64,
2217 cnt: u32,
2218 },
2219 ImageRgba {
2220 off: u64,
2221 cnt: u32,
2222 handle: u64,
2223 filter: ImageFilter,
2224 tile: bool,
2226 blend: repose_core::BlendMode,
2228 },
2229 Coverage {
2233 off: u64,
2234 cnt: u32,
2235 handle: u64,
2236 },
2237 ImageNv12 {
2238 off: u64,
2239 cnt: u32,
2240 handle: u64,
2241 filter: ImageFilter,
2242 blend: repose_core::BlendMode,
2244 },
2245 CompositeLayer {
2251 off: u64,
2252 cnt: u32,
2253 layer_id: u32,
2254 blend: repose_core::BlendMode,
2255 color: [f32; 4],
2256 },
2257 CompositeShadow {
2263 off: u64,
2264 cnt: u32,
2265 layer_id: u32,
2266 spread_px: f32,
2268 inset: bool,
2269 },
2270 CompositeBlur {
2273 off: u64,
2274 cnt: u32,
2275 layer_id: u32,
2276 blend: BlendMode,
2277 },
2278 CompositeProjective {
2283 off: u64,
2284 cnt: u32,
2285 layer_id: u32,
2286 blend: BlendMode,
2287 },
2288 VectorMesh {
2290 mesh: MeshGpu,
2291 uoff: u64,
2292 ioff: u64,
2295 icnt: u32,
2296 blend: repose_core::BlendMode,
2297 },
2298 BlendLayer {
2305 off: u64,
2306 cnt: u32,
2307 src_layer: u32,
2308 dst_layer: Option<u32>,
2309 parent: PassTarget,
2310 scissor: (u32, u32, u32, u32),
2311 },
2312 VectorOverlay {
2314 mesh: MeshGpu,
2315 uoff: u64,
2316 ioff: u64,
2317 icnt: u32,
2318 },
2319 VectorClipPush {
2324 mesh: MeshGpu,
2325 uoff: u64,
2326 ioff: u64,
2327 icnt: u32,
2328 scissor: (u32, u32, u32, u32),
2329 difference: bool,
2330 applied: bool,
2331 },
2332 VectorClipPop {
2334 mesh: MeshGpu,
2335 uoff: u64,
2336 ioff: u64,
2337 icnt: u32,
2338 scissor: (u32, u32, u32, u32),
2339 stencil_scissor: (u32, u32, u32, u32),
2340 difference: bool,
2341 applied: bool,
2342 },
2343 Callback {
2344 rect: repose_core::Rect,
2345 clip_rect: repose_core::Rect,
2346 scissor: (u32, u32, u32, u32),
2347 restore_scissor: (u32, u32, u32, u32),
2348 callback_id: usize,
2349 payload: repose_core::PaintCallbackPayload,
2350 },
2351}
2352
2353struct CoverageTex {
2358 #[allow(dead_code)]
2360 tex: wgpu::Texture,
2361 bind: wgpu::BindGroup,
2362 w: u32,
2363 h: u32,
2364 last_used_frame: u64,
2365 bytes: u64,
2366}
2367
2368struct ImageBinds {
2369 linear: wgpu::BindGroup,
2370 nearest: wgpu::BindGroup,
2371 tile_linear: wgpu::BindGroup,
2373 tile_nearest: wgpu::BindGroup,
2374}
2375
2376impl ImageBinds {
2377 fn get(&self, filter: ImageFilter, tile: bool) -> &wgpu::BindGroup {
2378 match (filter, tile) {
2379 (ImageFilter::Linear, false) => &self.linear,
2380 (ImageFilter::Nearest, false) => &self.nearest,
2381 (ImageFilter::Linear, true) => &self.tile_linear,
2382 (ImageFilter::Nearest, true) => &self.tile_nearest,
2383 }
2384 }
2385}
2386
2387enum ImageTex {
2388 Rgba {
2389 tex: wgpu::Texture,
2390 binds: ImageBinds,
2391 w: u32,
2392 h: u32,
2393 format: wgpu::TextureFormat,
2394 last_used_frame: u64,
2395 bytes: u64,
2396 },
2397 User {
2399 binds: ImageBinds,
2400 w: u32,
2401 h: u32,
2402 last_used_frame: u64,
2403 bytes: u64,
2404 },
2405 Nv12 {
2406 tex_y: wgpu::Texture,
2407 tex_uv: wgpu::Texture,
2408 binds: ImageBinds,
2409 yuv_buf: wgpu::Buffer,
2410 w: u32,
2411 h: u32,
2412 pixel_format: PixelFormat,
2413 fourcc: Option<u32>,
2414 color_info: ColorInfo,
2415 external: bool,
2416 last_used_frame: u64,
2417 bytes: u64,
2418 },
2419}
2420
2421impl ImageTex {
2422 fn evictable(&self) -> bool {
2423 match self {
2424 Self::Rgba { .. } => true,
2425 Self::User { .. } => false,
2426 Self::Nv12 { external, .. } => !*external,
2427 }
2428 }
2429}
2430
2431#[derive(Clone)]
2432struct RetainedImage {
2433 w: u32,
2434 h: u32,
2435 format: wgpu::TextureFormat,
2436 rgba: Vec<u8>,
2437 last_used_frame: u64,
2438}
2439
2440struct ResolvedImageSource {
2441 width: f32,
2442 height: f32,
2443 uv_min: [f32; 2],
2444 uv_max: [f32; 2],
2445}
2446
2447fn resolve_image_source(
2448 source_rect: Option<ImageSourceRect>,
2449 image_width: u32,
2450 image_height: u32,
2451) -> Option<ResolvedImageSource> {
2452 if image_width == 0 || image_height == 0 {
2453 return None;
2454 }
2455 let Some(source) = source_rect else {
2456 return Some(ResolvedImageSource {
2457 width: image_width as f32,
2458 height: image_height as f32,
2459 uv_min: [0.0, 0.0],
2460 uv_max: [1.0, 1.0],
2461 });
2462 };
2463 if source.is_empty() {
2464 return None;
2465 }
2466 let right = source.x.checked_add(source.width)?;
2467 let bottom = source.y.checked_add(source.height)?;
2468 if right > image_width || bottom > image_height {
2469 return None;
2470 }
2471 Some(ResolvedImageSource {
2472 width: source.width as f32,
2473 height: source.height as f32,
2474 uv_min: [
2475 source.x as f32 / image_width as f32,
2476 source.y as f32 / image_height as f32,
2477 ],
2478 uv_max: [
2479 right as f32 / image_width as f32,
2480 bottom as f32 / image_height as f32,
2481 ],
2482 })
2483}
2484
2485fn image_fit_geometry(
2494 rect: repose_core::Rect,
2495 fit: ImageFit,
2496 alignment: ImageAlignment,
2497 source: &ResolvedImageSource,
2498) -> Option<(repose_core::Rect, [f32; 4])> {
2499 let src_w = source.width;
2500 let src_h = source.height;
2501 let dst_w = rect.w.max(0.0);
2502 let dst_h = rect.h.max(0.0);
2503 if src_w <= 0.0 || src_h <= 0.0 || dst_w <= 0.0 || dst_h <= 0.0 {
2504 return None;
2505 }
2506
2507 let slack = |content: f32, extent: f32| match alignment {
2510 ImageAlignment::Center => (extent - content) * 0.5,
2511 ImageAlignment::Begin => 0.0,
2512 ImageAlignment::End => extent - content,
2513 };
2514
2515 let tiled = matches!(fit, ImageFit::Tile);
2518 let (scale_x, scale_y) = fit.scale_factor((src_w, src_h), (dst_w, dst_h));
2519 let drawn = if tiled {
2520 repose_core::Rect {
2521 x: rect.x,
2522 y: rect.y,
2523 w: dst_w,
2524 h: dst_h,
2525 }
2526 } else {
2527 let (w, h) = (src_w * scale_x, src_h * scale_y);
2528 repose_core::Rect {
2529 x: rect.x + slack(w, dst_w),
2530 y: rect.y + slack(h, dst_h),
2531 w,
2532 h,
2533 }
2534 };
2535
2536 let uv_min = source.uv_min;
2537 let uv_max = source.uv_max;
2538 let repeats = if tiled {
2539 [dst_w / src_w, dst_h / src_h]
2540 } else {
2541 [1.0, 1.0]
2542 };
2543 let mut uv = [
2544 uv_min[0],
2545 uv_max[1],
2546 uv_min[0] + (uv_max[0] - uv_min[0]) * repeats[0],
2547 uv_max[1] - (uv_max[1] - uv_min[1]) * repeats[1],
2548 ];
2549
2550 let clipped = intersect(drawn, rect);
2551 if clipped.w <= 0.0 || clipped.h <= 0.0 {
2552 return None;
2553 }
2554 let du = uv[2] - uv[0];
2555 let dv = uv[3] - uv[1];
2556 uv = [
2557 uv[0] + du * (clipped.x - drawn.x) / drawn.w,
2558 uv[1] + dv * (clipped.y - drawn.y) / drawn.h,
2559 uv[0] + du * (clipped.x + clipped.w - drawn.x) / drawn.w,
2560 uv[1] + dv * (clipped.y + clipped.h - drawn.y) / drawn.h,
2561 ];
2562 Some((clipped, uv))
2563}
2564
2565struct AtlasA8 {
2566 tex: wgpu::Texture,
2567 view: wgpu::TextureView,
2568 sampler: wgpu::Sampler,
2569 size: u32,
2570 next_x: u32,
2571 next_y: u32,
2572 row_h: u32,
2573 map: HashMap<repose_text::CacheKey, GlyphInfo>,
2574 used_area: u64,
2577}
2578
2579struct AtlasRGBA {
2580 tex: wgpu::Texture,
2581 view: wgpu::TextureView,
2582 sampler: wgpu::Sampler,
2583 size: u32,
2584 next_x: u32,
2585 next_y: u32,
2586 row_h: u32,
2587 map: HashMap<repose_text::CacheKey, GlyphInfo>,
2588 used_area: u64,
2589}
2590
2591#[derive(Default, Clone, Copy)]
2595struct AtlasPending {
2596 grow: bool,
2598 compact: bool,
2601}
2602
2603#[derive(Clone, Copy)]
2604struct GlyphInfo {
2605 u0: f32,
2606 v0: f32,
2607 u1: f32,
2608 v1: f32,
2609 w: f32,
2610 h: f32,
2611 last_touch: u64,
2615 last_used_frame: u64,
2616}
2617
2618#[derive(Clone, Hash, PartialEq, Eq)]
2619struct TextShapeKey {
2620 text: Arc<str>,
2621 px_bits: u32,
2622 line_height_bits: u32,
2623 font_family: Option<&'static str>,
2624 font_weight: u16,
2625 font_style: u8,
2626 letter_spacing_bits: u32,
2627 variation: Option<Arc<str>>,
2628 font_generation: u64,
2629}
2630
2631struct TextShapeCacheEntry {
2632 glyphs: Arc<[repose_text::ShapedGlyph]>,
2633 last_used_frame: u64,
2634}
2635
2636#[repr(C)]
2641#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2642struct RectInstance {
2643 xywh: [f32; 4],
2644 radii: [f32; 4],
2645 color0: [f32; 4],
2646 color1: [f32; 4],
2647 fwd_mat: [f32; 4],
2648 grad: [f32; 4],
2649 bits: u32,
2650 _pad: [f32; 3],
2651}
2652
2653#[repr(C)]
2654#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2655struct BorderInstance {
2656 xywh: [f32; 4],
2657 radii: [f32; 4],
2658 color0: [f32; 4],
2659 color1: [f32; 4],
2660 fwd_mat: [f32; 4],
2661 grad: [f32; 4],
2662 bits: u32,
2663 stroke: f32,
2664 _pad: [f32; 2],
2665}
2666
2667#[repr(C)]
2668#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2669struct EllipseInstance {
2670 xywh: [f32; 4],
2671 color0: [f32; 4],
2672 color1: [f32; 4],
2673 fwd_mat: [f32; 4],
2674 grad: [f32; 4],
2675 bits: u32,
2676 _pad: [f32; 1],
2677}
2678
2679#[repr(C)]
2680#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2681struct EllipseBorderInstance {
2682 xywh: [f32; 4],
2683 color0: [f32; 4],
2684 color1: [f32; 4],
2685 fwd_mat: [f32; 4],
2686 grad: [f32; 4],
2687 bits: u32,
2688 stroke: f32,
2689 pad: f32,
2690 _pad: f32,
2691}
2692
2693#[repr(C)]
2694#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2695struct ArcInstance {
2696 xywh: [f32; 4],
2697 color0: [f32; 4],
2698 color1: [f32; 4],
2699 fwd_mat: [f32; 4],
2700 grad: [f32; 4],
2701 bits: u32,
2702 start_angle: f32,
2703 sweep_angle: f32,
2704 stroke: f32,
2705 pad: f32,
2706 _pad: f32,
2707}
2708
2709#[repr(C)]
2710#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2711struct GlyphInstance {
2712 xywh: [f32; 4],
2713 uv: [f32; 4],
2714 color: [f32; 4],
2715 fwd_mat: [f32; 4],
2716}
2717
2718#[repr(C)]
2719#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2720struct BlurInstance {
2721 xywh: [f32; 4],
2722 uv: [f32; 4],
2723 color: [f32; 4],
2724 sigma_px: [f32; 2],
2725 fwd_mat: [f32; 4],
2726 axis: u32,
2727 edge_mode: u32,
2728 shape: [f32; 4],
2732}
2733
2734#[repr(C)]
2740#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2741struct ProjectiveInstance {
2742 c0: [f32; 2],
2743 c1: [f32; 2],
2744 c2: [f32; 2],
2745 c3: [f32; 2],
2746 uv: [f32; 4],
2747 w: [f32; 4],
2748 alpha: f32,
2749 tint: [f32; 3],
2751}
2752
2753#[repr(C)]
2756#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2757struct YuvTransformRaw {
2758 row0: [f32; 4],
2759 row1: [f32; 4],
2760 row2: [f32; 4],
2761 b: [f32; 4],
2762 transfer: [f32; 4],
2763}
2764
2765fn make_yuv_transform_raw(color_info: ColorInfo, pixel_format: PixelFormat) -> YuvTransformRaw {
2766 let yuv = color_info.to_yuv_transform();
2767 let sample_scale = match pixel_format {
2768 PixelFormat::P010 => 65535.0 / (64.0 * 1020.0),
2769 _ => 1.0,
2770 };
2771 let transfer_mode = match color_info.transfer {
2772 repose_core::color::Transfer::Srgb => 0.0,
2773 repose_core::color::Transfer::Bt709 => 1.0,
2774 repose_core::color::Transfer::Linear => 2.0,
2775 repose_core::color::Transfer::Pq => 3.0,
2776 repose_core::color::Transfer::Hlg => 4.0,
2777 };
2778 YuvTransformRaw {
2779 row0: [yuv.m[0][0], yuv.m[0][1], yuv.m[0][2], 0.0],
2780 row1: [yuv.m[1][0], yuv.m[1][1], yuv.m[1][2], 0.0],
2781 row2: [yuv.m[2][0], yuv.m[2][1], yuv.m[2][2], 0.0],
2782 b: [yuv.b[0], yuv.b[1], yuv.b[2], sample_scale],
2783 transfer: [transfer_mode, 0.0, 0.0, 0.0],
2784 }
2785}
2786
2787#[repr(C)]
2788#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2789struct Nv12Instance {
2790 xywh: [f32; 4],
2791 uv: [f32; 4],
2792 color: [f32; 4],
2793 uv_x_offset: f32,
2794 uv_y_offset: f32,
2795 fwd_mat: [f32; 4],
2796}
2797
2798#[repr(C)]
2799#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2800struct ClipInstance {
2801 xywh: [f32; 4],
2802 radii: [f32; 4],
2803 fwd_mat: [f32; 4],
2804}
2805
2806#[repr(C)]
2812#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2813struct BlendInstance {
2814 xywh: [f32; 4],
2815 uv: [f32; 4],
2816 color: [f32; 4],
2817 fwd_mat: [f32; 4],
2818 filter_color: [f32; 4],
2819 mode: u32,
2820 filter_mode: u32,
2821}
2822
2823#[repr(C)]
2824#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2825struct MeshVertex {
2826 pos: [f32; 2],
2827 color: [f32; 4],
2828 uv: [f32; 2],
2829}
2830
2831#[derive(Clone)]
2832struct MeshGpu {
2833 vertices: wgpu::Buffer,
2834 indices: wgpu::Buffer,
2835 vertex_count: u32,
2836 index_count: u32,
2837 bytes: u64,
2838}
2839
2840#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2841struct MeshCacheKey {
2842 source: usize,
2843 index: usize,
2844 kind: u8,
2845 vertex_len: usize,
2846 index_len: usize,
2847}
2848
2849#[derive(Clone)]
2850enum MeshOwner {
2851 Object(Arc<repose_core::VectorMeshData>),
2852 Overlay(Arc<[repose_core::VectorMeshData]>),
2853 Shape(Arc<ShapePath>, u32, Option<u32>),
2854}
2855
2856struct MeshCacheEntry {
2857 owner: MeshOwner,
2858 gpu: MeshGpu,
2859 last_used_frame: u64,
2860 last_touch_frame: u64,
2861}
2862
2863#[derive(Clone, PartialEq, Eq, Hash)]
2864struct SlugDrawKey {
2865 cache_key: repose_text::CacheKey,
2866 fill: bool,
2867 stroke: Option<slug::StrokeTessKey>,
2870 transform: [u32; 11],
2871 origin: [u32; 2],
2872 px_bits: u32,
2873 target: [u32; 2],
2874 color: [u32; 4],
2875}
2876
2877struct SlugDrawCacheEntry {
2878 vertices: Arc<[slug::TessVertex]>,
2879 bytes: u64,
2880 last_used_frame: u64,
2881 last_touch_frame: u64,
2882}
2883
2884struct GlyphOutlineEntry {
2888 commands: Option<Arc<[repose_text::Command]>>,
2889 last_touch: u64,
2890}
2891
2892fn evict_atlas_lru(
2897 map: &mut HashMap<repose_text::CacheKey, GlyphInfo>,
2898 used_area: &mut u64,
2899 frame_index: u64,
2900 target_area: u64,
2901) -> bool {
2902 let mut victims: Vec<(u64, repose_text::CacheKey)> = map
2903 .iter()
2904 .filter(|(_, info)| info.last_used_frame != frame_index)
2905 .map(|(key, info)| (info.last_touch, key.clone()))
2906 .collect();
2907 if victims.is_empty() {
2908 return false;
2909 }
2910 victims.sort_unstable_by_key(|victim| victim.0);
2912 let mut evicted = false;
2913 for (_, key) in victims {
2914 if *used_area <= target_area || map.len() <= 1 {
2915 break;
2916 }
2917 if let Some(info) = map.remove(&key) {
2918 *used_area = used_area.saturating_sub(glyph_cell_area(&info));
2919 evicted = true;
2920 }
2921 }
2922 evicted
2923}
2924
2925fn glyph_cell_area(info: &GlyphInfo) -> u64 {
2928 (info.w as u64).saturating_mul(info.h as u64)
2929}
2930
2931fn defer_atlas_glyph(deferred: &mut HashSet<repose_text::CacheKey>, key: repose_text::CacheKey) {
2935 if deferred.len() >= MAX_GLYPH_ATLAS_ENTRIES {
2936 deferred.clear();
2937 }
2938 deferred.insert(key);
2939}
2940
2941fn slug_draw_cache_entry_bytes(vertices: usize) -> u64 {
2945 let per_entry = (std::mem::size_of::<SlugDrawKey>()
2946 + std::mem::size_of::<SlugDrawCacheEntry>()
2947 + std::mem::size_of::<(SlugDrawKey, SlugDrawCacheEntry)>()) as u64;
2948 u64::try_from(vertices)
2949 .ok()
2950 .and_then(|count| count.checked_mul(std::mem::size_of::<slug::TessVertex>() as u64))
2951 .and_then(|payload| payload.checked_add(per_entry))
2952 .unwrap_or(u64::MAX)
2953}
2954
2955#[repr(C)]
2962#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2963struct MeshUniform {
2964 paint: [u32; 4],
2965 color0: [f32; 4],
2966 color1: [f32; 4],
2967 grad_start: [f32; 2],
2968 _p3: [f32; 2],
2969 grad_end: [f32; 2],
2970 _p4: [f32; 2],
2971 stop_colors: [[f32; 4]; MAX_GRADIENT_STOPS],
2972 stop_offsets: [[f32; 4]; MAX_GRADIENT_STOPS / 4],
2973}
2974
2975const MESH_UNIFORM_BYTES: usize = 240;
2979const _: () = assert!(std::mem::size_of::<MeshUniform>() == MESH_UNIFORM_BYTES);
2980
2981const MESH_UNIFORM_CAP: u64 = 4 * 1024 * 1024;
2982
2983#[repr(C)]
2987#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
2988struct MeshInstance {
2989 xf0: [f32; 4],
2990 xf1: [f32; 4],
2991}
2992
2993impl MeshInstance {
2994 fn new(affine: [f32; 6]) -> Self {
2995 Self {
2996 xf0: [affine[0], affine[1], affine[2], 0.0],
2997 xf1: [affine[3], affine[4], affine[5], 0.0],
2998 }
2999 }
3000}
3001
3002const MESH_INSTANCE_CAP: u64 = 8 * 1024 * 1024;
3006
3007const IDENTITY_AFFINE: [f32; 6] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
3010const MAX_RETAINED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
3011const MAX_RETAINED_IMAGES: usize = 512;
3012const MAX_BLEND_SNAPSHOT_BYTES: u64 = 64 * 1024 * 1024;
3013const MAX_BLEND_SNAPSHOT_POOL_ENTRIES: usize = 64;
3014const MAX_GLYPH_ATLAS_ENTRIES: usize = 32768;
3015const MAX_GLYPH_ATLAS_SIZE: u32 = 4096;
3018const ATLAS_COMPACT_KEEP_NUM: u64 = 3;
3022const ATLAS_COMPACT_KEEP_DEN: u64 = 4;
3023const ATLAS_COMPACT_MIN_FRAME_INTERVAL: u64 = 30;
3027const MAX_GPU_RESOURCE_BYTES: u64 = 1024 * 1024 * 1024;
3028const MAX_UPLOAD_RING_BYTES: u64 = 64 * 1024 * 1024;
3029const MAX_MESH_CACHE_BYTES: u64 = 256 * 1024 * 1024;
3030const MAX_MESH_CACHE_ENTRIES: usize = 512;
3031const MAX_SLUG_DRAW_CACHE_ENTRIES: usize = 2048;
3032const MAX_SLUG_DRAW_CACHE_BYTES: u64 = 32 * 1024 * 1024;
3033const MAX_LEGACY_SHAPED_TEXT_CACHE_ENTRIES: usize = 256;
3034const MAX_GLYPH_OUTLINE_CACHE_ENTRIES: usize = 4096;
3035const MAX_IMAGE_DECODE_BYTES: u64 = 64 * 1024 * 1024;
3036const MAX_CALLBACK_SCOPES: usize = 256;
3037const NV12_FOURCC: u32 = 0x3231_564e;
3038const P010_FOURCC: u32 = 0x3031_3050;
3039
3040fn canonical_fourcc(format: PixelFormat) -> u32 {
3041 match format {
3042 PixelFormat::P010 => P010_FOURCC,
3043 _ => NV12_FOURCC,
3044 }
3045}
3046
3047impl MeshUniform {
3048 fn identity() -> Self {
3049 Self {
3050 paint: [0; 4],
3051 color0: [0.0; 4],
3052 color1: [0.0; 4],
3053 grad_start: [0.0; 2],
3054 _p3: [0.0; 2],
3055 grad_end: [0.0; 2],
3056 _p4: [0.0; 2],
3057 stop_colors: [[0.0; 4]; MAX_GRADIENT_STOPS],
3058 stop_offsets: [[0.0; 4]; MAX_GRADIENT_STOPS / 4],
3059 }
3060 }
3061}
3062
3063type PackedStops = (
3065 [[f32; 4]; MAX_GRADIENT_STOPS],
3066 [[f32; 4]; MAX_GRADIENT_STOPS / 4],
3067 u32,
3068);
3069
3070fn pack_gradient_stops(stops: &GradientStops) -> PackedStops {
3076 let mut stop_colors = [[0.0f32; 4]; MAX_GRADIENT_STOPS];
3077 let mut flat = [0.0f32; MAX_GRADIENT_STOPS];
3078 let mut count = 0u32;
3079 let mut prev = 0.0f32;
3080 for ((color, offset), stop) in stop_colors
3081 .iter_mut()
3082 .zip(flat.iter_mut())
3083 .zip(stops.as_slice())
3084 {
3085 let clamped = stop.offset.clamp(0.0, 1.0).max(prev);
3086 prev = clamped;
3087 *color = stop.color.to_linear();
3088 *offset = clamped;
3089 count += 1;
3090 }
3091 let mut stop_offsets = [[0.0f32; 4]; MAX_GRADIENT_STOPS / 4];
3092 for (dst, src) in stop_offsets.iter_mut().zip(flat.as_chunks::<4>().0) {
3093 *dst = *src;
3094 }
3095 (stop_colors, stop_offsets, count)
3096}
3097
3098fn mesh_uniform_from_paint(paint: &repose_core::PaintDesc) -> MeshUniform {
3099 let no_stops = GradientStops::default();
3100 let (paint_type, paint_kind, stops, color0, color1, grad_start, grad_end) = match paint {
3101 repose_core::PaintDesc::Solid => {
3102 (0u32, 0u32, no_stops, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2])
3103 }
3104 repose_core::PaintDesc::Linear {
3105 start,
3106 end,
3107 start_color,
3108 end_color,
3109 } => (
3110 1u32,
3111 0u32,
3112 no_stops,
3113 start_color.to_linear(),
3114 end_color.to_linear(),
3115 [start.x, start.y],
3116 [end.x, end.y],
3117 ),
3118 repose_core::PaintDesc::Radial {
3119 center,
3120 radius,
3121 start_color,
3122 end_color,
3123 } => (
3124 1u32,
3125 1u32,
3126 no_stops,
3127 start_color.to_linear(),
3128 end_color.to_linear(),
3129 [center.x, center.y],
3130 [radius.max(0.0), 0.0],
3131 ),
3132 repose_core::PaintDesc::Sweep {
3133 center,
3134 start_color,
3135 end_color,
3136 } => (
3137 1u32,
3138 2u32,
3139 no_stops,
3140 start_color.to_linear(),
3141 end_color.to_linear(),
3142 [center.x, center.y],
3143 [0.0, 0.0],
3144 ),
3145 repose_core::PaintDesc::LinearStops { start, end, stops } => (
3146 1u32,
3147 3u32,
3148 *stops,
3149 [0.0; 4],
3150 [0.0; 4],
3151 [start.x, start.y],
3152 [end.x, end.y],
3153 ),
3154 repose_core::PaintDesc::RadialStops {
3155 center,
3156 radius,
3157 stops,
3158 } => (
3159 1u32,
3160 4u32,
3161 *stops,
3162 [0.0; 4],
3163 [0.0; 4],
3164 [center.x, center.y],
3165 [radius.max(0.0), 0.0],
3166 ),
3167 _ => (0u32, 0u32, no_stops, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2]),
3168 };
3169 let (stop_colors, stop_offsets, count) = pack_gradient_stops(&stops);
3170 MeshUniform {
3171 paint: [paint_type, paint_kind, count, 0],
3172 color0,
3173 color1,
3174 grad_start,
3175 _p3: [0.0; 2],
3176 grad_end,
3177 _p4: [0.0; 2],
3178 stop_colors,
3179 stop_offsets,
3180 }
3181}
3182
3183fn combine_mesh_affine(current: &Transform, mesh: [f32; 6]) -> [f32; 6] {
3184 let cm = current.linear();
3185 let (cm00, cm01, cm10, cm11) = (cm[0], cm[1], cm[2], cm[3]);
3186 let mm00 = mesh[0];
3187 let mm01 = mesh[1];
3188 let mm10 = mesh[2];
3189 let mm11 = mesh[3];
3190 let mtx = mesh[4];
3191 let mty = mesh[5];
3192 let r00 = cm00 * mm00 + cm01 * mm10;
3193 let r01 = cm00 * mm01 + cm01 * mm11;
3194 let r10 = cm10 * mm00 + cm11 * mm10;
3195 let r11 = cm10 * mm01 + cm11 * mm11;
3196 let tx = cm00 * mtx + cm01 * mty + current.translate_x;
3197 let ty = cm10 * mtx + cm11 * mty + current.translate_y;
3198 [r00, r01, tx, r10, r11, ty]
3201}
3202
3203fn mesh_blend_needs_isolation(
3210 blend: repose_core::BlendMode,
3211 mesh: &repose_core::VectorMeshData,
3212 paint: &repose_core::PaintDesc,
3213) -> bool {
3214 if blend.needs_isolation() {
3215 return true;
3216 }
3217 let paint_alpha = match paint {
3218 repose_core::PaintDesc::Linear {
3219 start_color,
3220 end_color,
3221 ..
3222 }
3223 | repose_core::PaintDesc::Radial {
3224 start_color,
3225 end_color,
3226 ..
3227 }
3228 | repose_core::PaintDesc::Sweep {
3229 start_color,
3230 end_color,
3231 ..
3232 } => Some(start_color.3.min(end_color.3) as f32 / 255.0),
3233 repose_core::PaintDesc::LinearStops { stops, .. }
3234 | repose_core::PaintDesc::RadialStops { stops, .. } => Some(stops.min_alpha()),
3235 _ => None,
3236 };
3237 matches!(
3238 blend,
3239 repose_core::BlendMode::Add
3240 | repose_core::BlendMode::Multiply
3241 | repose_core::BlendMode::Screen
3242 | repose_core::BlendMode::Darken
3243 | repose_core::BlendMode::Lighten
3244 ) && (mesh.vertices.iter().any(|vertex| vertex.color[3] < 0.9999)
3245 || paint_alpha.is_some_and(|alpha| alpha < 0.9999))
3246}
3247
3248fn mesh_aabb(mesh: &repose_core::VectorMeshData, affine: [f32; 6]) -> repose_core::Rect {
3249 let mut min_x = f32::INFINITY;
3250 let mut min_y = f32::INFINITY;
3251 let mut max_x = f32::NEG_INFINITY;
3252 let mut max_y = f32::NEG_INFINITY;
3253 for v in mesh.vertices.iter() {
3254 let x = affine[0] * v.pos[0] + affine[1] * v.pos[1] + affine[2];
3255 let y = affine[3] * v.pos[0] + affine[4] * v.pos[1] + affine[5];
3256 min_x = min_x.min(x);
3257 min_y = min_y.min(y);
3258 max_x = max_x.max(x);
3259 max_y = max_y.max(y);
3260 }
3261 let w = (max_x - min_x).max(0.0);
3262 let h = (max_y - min_y).max(0.0);
3263 if !min_x.is_finite() || !min_y.is_finite() {
3264 return repose_core::Rect {
3265 x: 0.0,
3266 y: 0.0,
3267 w: 0.0,
3268 h: 0.0,
3269 };
3270 }
3271 repose_core::Rect {
3272 x: min_x,
3273 y: min_y,
3274 w,
3275 h,
3276 }
3277}
3278
3279fn quantize_glyph_px(px: f32) -> f32 {
3280 if !px.is_finite() || px <= 0.0 {
3281 return 1.0;
3282 }
3283 ((px * 4.0).round() / 4.0).max(0.25)
3284}
3285
3286fn swash_to_a8_coverage(content: repose_text::SwashContent, data: &[u8]) -> Option<Vec<u8>> {
3287 match content {
3288 repose_text::SwashContent::Mask => Some(data.to_vec()),
3289 repose_text::SwashContent::SubpixelMask => {
3290 let mut out = Vec::with_capacity(data.len() / 4);
3291 for px in data.as_chunks::<4>().0 {
3292 let r = px[0];
3293 let g = px[1];
3294 let b = px[2];
3295 out.push(r.max(g).max(b));
3296 }
3297 Some(out)
3298 }
3299 repose_text::SwashContent::Color => None,
3300 }
3301}
3302
3303impl WgpuSceneRenderer {
3304 pub fn from_device(
3315 device: wgpu::Device,
3316 queue: wgpu::Queue,
3317 output_format: wgpu::TextureFormat,
3318 msaa_samples: u32,
3319 ) -> anyhow::Result<Self> {
3320 validate_sample_count("msaa_samples", msaa_samples)?;
3321 Self::from_device_with_working_space_msaa(
3322 device,
3323 queue,
3324 output_format,
3325 msaa_samples,
3326 msaa_samples,
3327 )
3328 }
3329
3330 pub fn try_from_device_with_adapter(
3334 adapter: &wgpu::Adapter,
3335 device: wgpu::Device,
3336 queue: wgpu::Queue,
3337 output_format: wgpu::TextureFormat,
3338 requested_msaa: u32,
3339 ) -> anyhow::Result<Self> {
3340 let msaa = pick_surface_msaa(adapter, output_format, requested_msaa);
3341 validate_render_target_format(adapter, output_format, msaa)?;
3342 let working_space_msaa =
3343 pick_surface_msaa_for_mode(adapter, wgpu::TextureFormat::Rgba16Float, msaa, true);
3344 let mut renderer = Self::from_device_with_working_space_msaa(
3345 device,
3346 queue,
3347 output_format,
3348 msaa,
3349 working_space_msaa,
3350 )?;
3351 renderer
3355 .callback_resources
3356 .insert(adapter.get_downlevel_capabilities());
3357 Ok(renderer)
3358 }
3359
3360 pub fn with_surface_format(
3364 mut self,
3365 surface_format: wgpu::TextureFormat,
3366 ) -> anyhow::Result<Self> {
3367 if surface_format != self.output_format
3368 && surface_format.add_srgb_suffix() != self.output_format
3369 {
3370 anyhow::bail!(
3371 "surface format {surface_format:?} cannot be reinterpreted as {:?}",
3372 self.output_format
3373 );
3374 }
3375 if self.surface_format != surface_format {
3376 self.surface_format = surface_format;
3377 self.recreate_msaa_and_depth_stencil();
3378 }
3379 Ok(self)
3380 }
3381
3382 pub fn from_device_with_working_space_msaa(
3383 device: wgpu::Device,
3384 queue: wgpu::Queue,
3385 output_format: wgpu::TextureFormat,
3386 msaa_samples: u32,
3387 working_space_msaa_samples: u32,
3388 ) -> anyhow::Result<Self> {
3389 validate_sample_count("msaa_samples", msaa_samples)?;
3390 validate_sample_count("working_space_msaa_samples", working_space_msaa_samples)?;
3391 let msaa_samples = msaa_samples.max(1);
3392 let working_space_msaa_samples = working_space_msaa_samples.max(1);
3393 let mesh_uniform_size = std::mem::size_of::<MeshUniform>() as u64;
3394 let base_mesh_alignment =
3395 u64::from(device.limits().min_uniform_buffer_offset_alignment).max(4);
3396 let mesh_uniform_alignment = mesh_uniform_stride(mesh_uniform_size, base_mesh_alignment);
3397 let mesh_instance_cap = MESH_INSTANCE_CAP
3398 .min(device.limits().max_buffer_size)
3399 .max(4);
3400 let mesh_uniform_cap = align_up(
3401 MESH_UNIFORM_CAP
3402 .min(device.limits().max_buffer_size)
3403 .max(mesh_uniform_alignment),
3404 base_mesh_alignment,
3405 )
3406 .unwrap_or(mesh_uniform_alignment);
3407 let globals_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3408 label: Some("globals layout"),
3409 entries: &[wgpu::BindGroupLayoutEntry {
3410 binding: 0,
3411 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
3412 ty: wgpu::BindingType::Buffer {
3413 ty: wgpu::BufferBindingType::Uniform,
3414 has_dynamic_offset: false,
3415 min_binding_size: None,
3416 },
3417 count: None,
3418 }],
3419 });
3420
3421 let globals_buf = device.create_buffer(&wgpu::BufferDescriptor {
3422 label: Some("globals buf"),
3423 size: std::mem::size_of::<Globals>() as u64,
3424 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
3425 mapped_at_creation: false,
3426 });
3427
3428 let globals_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
3429 label: Some("globals bind"),
3430 layout: &globals_layout,
3431 entries: &[wgpu::BindGroupEntry {
3432 binding: 0,
3433 resource: globals_buf.as_entire_binding(),
3434 }],
3435 });
3436 let globals_staging_cap =
3437 (64 * std::mem::size_of::<Globals>() as u64).max(std::mem::size_of::<Globals>() as u64);
3438 let globals_staging = device.create_buffer(&wgpu::BufferDescriptor {
3439 label: Some("globals staging"),
3440 size: globals_staging_cap,
3441 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
3442 mapped_at_creation: false,
3443 });
3444
3445 let shape_stops_layout =
3446 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3447 label: Some("shape gradient stops layout"),
3448 entries: &[wgpu::BindGroupLayoutEntry {
3449 binding: 0,
3450 visibility: wgpu::ShaderStages::FRAGMENT,
3451 ty: wgpu::BindingType::Texture {
3452 sample_type: wgpu::TextureSampleType::Float { filterable: false },
3453 view_dimension: wgpu::TextureViewDimension::D2,
3454 multisampled: false,
3455 },
3456 count: None,
3457 }],
3458 });
3459 let shape_stops_tex = device.create_texture(&wgpu::TextureDescriptor {
3460 label: Some("shape gradient stops"),
3461 size: wgpu::Extent3d {
3462 width: SHAPE_STOPS_TEXELS,
3463 height: MAX_SHAPE_GRADIENT_TABLES,
3464 depth_or_array_layers: 1,
3465 },
3466 mip_level_count: 1,
3467 sample_count: 1,
3468 dimension: wgpu::TextureDimension::D2,
3469 format: wgpu::TextureFormat::Rgba32Float,
3470 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
3471 view_formats: &[],
3472 });
3473 let shape_stops_view = shape_stops_tex.create_view(&wgpu::TextureViewDescriptor::default());
3474 let shape_stops_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
3475 label: Some("shape gradient stops bind"),
3476 layout: &shape_stops_layout,
3477 entries: &[wgpu::BindGroupEntry {
3478 binding: 0,
3479 resource: wgpu::BindingResource::TextureView(&shape_stops_view),
3480 }],
3481 });
3482
3483 let ds_format = wgpu::TextureFormat::Depth24PlusStencil8;
3484
3485 let stencil_for_content = wgpu::DepthStencilState {
3486 format: ds_format,
3487 depth_write_enabled: Some(false),
3488 depth_compare: Some(wgpu::CompareFunction::Always),
3489 stencil: wgpu::StencilState {
3490 front: wgpu::StencilFaceState {
3491 compare: wgpu::CompareFunction::Equal,
3498 fail_op: wgpu::StencilOperation::Keep,
3499 depth_fail_op: wgpu::StencilOperation::Keep,
3500 pass_op: wgpu::StencilOperation::Keep,
3501 },
3502 back: wgpu::StencilFaceState {
3503 compare: wgpu::CompareFunction::Equal,
3504 fail_op: wgpu::StencilOperation::Keep,
3505 depth_fail_op: wgpu::StencilOperation::Keep,
3506 pass_op: wgpu::StencilOperation::Keep,
3507 },
3508 read_mask: 0xFF,
3509 write_mask: 0x00,
3510 },
3511 bias: wgpu::DepthBiasState::default(),
3512 };
3513
3514 let stencil_for_clip_inc = wgpu::DepthStencilState {
3515 format: ds_format,
3516 depth_write_enabled: Some(false),
3517 depth_compare: Some(wgpu::CompareFunction::Always),
3518 stencil: wgpu::StencilState {
3519 front: wgpu::StencilFaceState {
3520 compare: wgpu::CompareFunction::Always,
3521 fail_op: wgpu::StencilOperation::Keep,
3522 depth_fail_op: wgpu::StencilOperation::Keep,
3523 pass_op: wgpu::StencilOperation::IncrementClamp,
3524 },
3525 back: wgpu::StencilFaceState {
3526 compare: wgpu::CompareFunction::Always,
3527 fail_op: wgpu::StencilOperation::Keep,
3528 depth_fail_op: wgpu::StencilOperation::Keep,
3529 pass_op: wgpu::StencilOperation::IncrementClamp,
3530 },
3531 read_mask: 0xFF,
3532 write_mask: 0xFF,
3533 },
3534 bias: wgpu::DepthBiasState::default(),
3535 };
3536
3537 let stencil_for_clip_dec = wgpu::DepthStencilState {
3538 format: ds_format,
3539 depth_write_enabled: Some(false),
3540 depth_compare: Some(wgpu::CompareFunction::Always),
3541 stencil: wgpu::StencilState {
3542 front: wgpu::StencilFaceState {
3543 compare: wgpu::CompareFunction::Always,
3544 fail_op: wgpu::StencilOperation::Keep,
3545 depth_fail_op: wgpu::StencilOperation::Keep,
3546 pass_op: wgpu::StencilOperation::DecrementClamp,
3547 },
3548 back: wgpu::StencilFaceState {
3549 compare: wgpu::CompareFunction::Always,
3550 fail_op: wgpu::StencilOperation::Keep,
3551 depth_fail_op: wgpu::StencilOperation::Keep,
3552 pass_op: wgpu::StencilOperation::DecrementClamp,
3553 },
3554 read_mask: 0xFF,
3555 write_mask: 0xFF,
3556 },
3557 bias: wgpu::DepthBiasState::default(),
3558 };
3559
3560 let _multisample_state = wgpu::MultisampleState {
3561 count: msaa_samples,
3562 mask: !0,
3563 alpha_to_coverage_enabled: false,
3564 };
3565
3566 let image_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
3570 label: Some("image/text sampler"),
3571 address_mode_u: wgpu::AddressMode::ClampToEdge,
3572 address_mode_v: wgpu::AddressMode::ClampToEdge,
3573 mag_filter: wgpu::FilterMode::Linear,
3574 min_filter: wgpu::FilterMode::Linear,
3575 mipmap_filter: wgpu::MipmapFilterMode::Linear,
3576 ..Default::default()
3577 });
3578 let image_sampler_nearest = device.create_sampler(&wgpu::SamplerDescriptor {
3579 label: Some("image nearest sampler"),
3580 address_mode_u: wgpu::AddressMode::ClampToEdge,
3581 address_mode_v: wgpu::AddressMode::ClampToEdge,
3582 mag_filter: wgpu::FilterMode::Nearest,
3583 min_filter: wgpu::FilterMode::Nearest,
3584 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
3585 ..Default::default()
3586 });
3587
3588 let image_sampler_repeat = device.create_sampler(&wgpu::SamplerDescriptor {
3591 label: Some("image repeat sampler"),
3592 address_mode_u: wgpu::AddressMode::Repeat,
3593 address_mode_v: wgpu::AddressMode::Repeat,
3594 mag_filter: wgpu::FilterMode::Linear,
3595 min_filter: wgpu::FilterMode::Linear,
3596 mipmap_filter: wgpu::MipmapFilterMode::Linear,
3597 ..Default::default()
3598 });
3599 let image_sampler_repeat_nearest = device.create_sampler(&wgpu::SamplerDescriptor {
3600 label: Some("image repeat nearest sampler"),
3601 address_mode_u: wgpu::AddressMode::Repeat,
3602 address_mode_v: wgpu::AddressMode::Repeat,
3603 mag_filter: wgpu::FilterMode::Nearest,
3604 min_filter: wgpu::FilterMode::Nearest,
3605 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
3606 ..Default::default()
3607 });
3608
3609 let layer_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
3611 label: Some("layer nearest sampler"),
3612 address_mode_u: wgpu::AddressMode::ClampToEdge,
3613 address_mode_v: wgpu::AddressMode::ClampToEdge,
3614 mag_filter: wgpu::FilterMode::Nearest,
3615 min_filter: wgpu::FilterMode::Nearest,
3616 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
3617 ..Default::default()
3618 });
3619
3620 let layer_sampler_linear = device.create_sampler(&wgpu::SamplerDescriptor {
3623 label: Some("layer linear sampler"),
3624 address_mode_u: wgpu::AddressMode::ClampToEdge,
3625 address_mode_v: wgpu::AddressMode::ClampToEdge,
3626 mag_filter: wgpu::FilterMode::Linear,
3627 min_filter: wgpu::FilterMode::Linear,
3628 mipmap_filter: wgpu::MipmapFilterMode::Linear,
3629 ..Default::default()
3630 });
3631
3632 let text_bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3634 label: Some("text/rgba bind layout"),
3635 entries: &[
3636 wgpu::BindGroupLayoutEntry {
3637 binding: 0,
3638 visibility: wgpu::ShaderStages::FRAGMENT,
3639 ty: wgpu::BindingType::Texture {
3640 multisampled: false,
3641 view_dimension: wgpu::TextureViewDimension::D2,
3642 sample_type: wgpu::TextureSampleType::Float { filterable: true },
3643 },
3644 count: None,
3645 },
3646 wgpu::BindGroupLayoutEntry {
3647 binding: 1,
3648 visibility: wgpu::ShaderStages::FRAGMENT,
3649 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3650 count: None,
3651 },
3652 ],
3653 });
3654 let image_bind_layout_rgba = text_bind_layout.clone();
3656
3657 let image_bind_layout_nv12 =
3659 device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3660 label: Some("image bind layout nv12"),
3661 entries: &[
3662 wgpu::BindGroupLayoutEntry {
3664 binding: 0,
3665 visibility: wgpu::ShaderStages::FRAGMENT,
3666 ty: wgpu::BindingType::Texture {
3667 multisampled: false,
3668 view_dimension: wgpu::TextureViewDimension::D2,
3669 sample_type: wgpu::TextureSampleType::Float { filterable: true },
3670 },
3671 count: None,
3672 },
3673 wgpu::BindGroupLayoutEntry {
3675 binding: 1,
3676 visibility: wgpu::ShaderStages::FRAGMENT,
3677 ty: wgpu::BindingType::Texture {
3678 multisampled: false,
3679 view_dimension: wgpu::TextureViewDimension::D2,
3680 sample_type: wgpu::TextureSampleType::Float { filterable: true },
3681 },
3682 count: None,
3683 },
3684 wgpu::BindGroupLayoutEntry {
3686 binding: 2,
3687 visibility: wgpu::ShaderStages::FRAGMENT,
3688 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3689 count: None,
3690 },
3691 wgpu::BindGroupLayoutEntry {
3693 binding: 3,
3694 visibility: wgpu::ShaderStages::FRAGMENT,
3695 ty: wgpu::BindingType::Buffer {
3696 ty: wgpu::BufferBindingType::Uniform,
3697 has_dynamic_offset: false,
3698 min_binding_size: None,
3699 },
3700 count: None,
3701 },
3702 ],
3703 });
3704
3705 let clip_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
3707 label: Some("clip pipeline layout"),
3708 bind_group_layouts: &[Some(&globals_layout)],
3709 immediate_size: 0,
3710 });
3711 let clip_vertex_layout = wgpu::VertexBufferLayout {
3712 array_stride: std::mem::size_of::<ClipInstance>() as u64,
3713 step_mode: wgpu::VertexStepMode::Instance,
3714 attributes: &[
3715 wgpu::VertexAttribute {
3716 shader_location: 0,
3717 offset: 0,
3718 format: wgpu::VertexFormat::Float32x4,
3719 },
3720 wgpu::VertexAttribute {
3721 shader_location: 1,
3722 offset: 16,
3723 format: wgpu::VertexFormat::Float32x4,
3724 },
3725 wgpu::VertexAttribute {
3726 shader_location: 2,
3727 offset: 32,
3728 format: wgpu::VertexFormat::Float32x4,
3729 },
3730 ],
3731 };
3732 let mesh_bind_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3734 label: Some("mesh uniform layout"),
3735 entries: &[wgpu::BindGroupLayoutEntry {
3736 binding: 0,
3737 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
3738 ty: wgpu::BindingType::Buffer {
3739 ty: wgpu::BufferBindingType::Uniform,
3740 has_dynamic_offset: true,
3741 min_binding_size: NonZeroU64::new(mesh_uniform_size),
3742 },
3743 count: None,
3744 }],
3745 });
3746 let mesh_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
3747 label: Some("mesh uniform buffer"),
3748 size: mesh_uniform_cap,
3749 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
3750 mapped_at_creation: false,
3751 });
3752 let mesh_instance_buf = device.create_buffer(&wgpu::BufferDescriptor {
3753 label: Some("mesh instance buffer"),
3754 size: mesh_instance_cap,
3755 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
3756 mapped_at_creation: false,
3757 });
3758 let mesh_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
3759 label: Some("mesh uniform bind"),
3760 layout: &mesh_bind_layout,
3761 entries: &[wgpu::BindGroupEntry {
3762 binding: 0,
3763 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
3764 buffer: &mesh_uniform_buf,
3765 offset: 0,
3766 size: NonZeroU64::new(mesh_uniform_size),
3767 }),
3768 }],
3769 });
3770
3771 let surface_pipes = Pipelines::create(
3774 &device,
3775 output_format,
3776 msaa_samples,
3777 &globals_layout,
3778 &shape_stops_layout,
3779 &text_bind_layout,
3780 &image_bind_layout_nv12,
3781 &clip_pipeline_layout,
3782 &stencil_for_content,
3783 &stencil_for_clip_inc,
3784 &stencil_for_clip_dec,
3785 &clip_vertex_layout,
3786 &mesh_bind_layout,
3787 );
3788 let working_space_pipes = Pipelines::create(
3789 &device,
3790 wgpu::TextureFormat::Rgba16Float,
3791 working_space_msaa_samples,
3792 &globals_layout,
3793 &shape_stops_layout,
3794 &text_bind_layout,
3795 &image_bind_layout_nv12,
3796 &clip_pipeline_layout,
3797 &stencil_for_content,
3798 &stencil_for_clip_inc,
3799 &stencil_for_clip_dec,
3800 &clip_vertex_layout,
3801 &mesh_bind_layout,
3802 );
3803 let layer_pipes = if msaa_samples == 1 {
3804 surface_pipes.clone()
3805 } else {
3806 Pipelines::create(
3807 &device,
3808 output_format,
3809 1,
3810 &globals_layout,
3811 &shape_stops_layout,
3812 &text_bind_layout,
3813 &image_bind_layout_nv12,
3814 &clip_pipeline_layout,
3815 &stencil_for_content,
3816 &stencil_for_clip_inc,
3817 &stencil_for_clip_dec,
3818 &clip_vertex_layout,
3819 &mesh_bind_layout,
3820 )
3821 };
3822 let working_space_layer_pipes = if working_space_msaa_samples == 1 {
3823 working_space_pipes.clone()
3824 } else {
3825 Pipelines::create(
3826 &device,
3827 wgpu::TextureFormat::Rgba16Float,
3828 1,
3829 &globals_layout,
3830 &shape_stops_layout,
3831 &text_bind_layout,
3832 &image_bind_layout_nv12,
3833 &clip_pipeline_layout,
3834 &stencil_for_content,
3835 &stencil_for_clip_inc,
3836 &stencil_for_clip_dec,
3837 &clip_vertex_layout,
3838 &mesh_bind_layout,
3839 )
3840 };
3841
3842 let slug_enabled = true;
3844
3845 let blur_ring = UploadRing::new(
3847 &device,
3848 "blur ring",
3849 1024 * 1024,
3850 wgpu::BufferUsages::VERTEX
3851 | wgpu::BufferUsages::COPY_DST
3852 | wgpu::BufferUsages::COPY_SRC,
3853 );
3854
3855 let atlas_mask = init_atlas_mask(&device);
3857 let atlas_color = init_atlas_color(&device);
3858 let atlas_mask_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
3859 label: Some("atlas mask bind"),
3860 layout: &text_bind_layout,
3861 entries: &[
3862 wgpu::BindGroupEntry {
3863 binding: 0,
3864 resource: wgpu::BindingResource::TextureView(&atlas_mask.view),
3865 },
3866 wgpu::BindGroupEntry {
3867 binding: 1,
3868 resource: wgpu::BindingResource::Sampler(&atlas_mask.sampler),
3869 },
3870 ],
3871 });
3872 let atlas_color_bind = device.create_bind_group(&wgpu::BindGroupDescriptor {
3873 label: Some("atlas color bind"),
3874 layout: &text_bind_layout,
3875 entries: &[
3876 wgpu::BindGroupEntry {
3877 binding: 0,
3878 resource: wgpu::BindingResource::TextureView(&atlas_color.view),
3879 },
3880 wgpu::BindGroupEntry {
3881 binding: 1,
3882 resource: wgpu::BindingResource::Sampler(&atlas_color.sampler),
3883 },
3884 ],
3885 });
3886
3887 let ring_rect = UploadRing::new(
3889 &device,
3890 "ring rect",
3891 1 << 20,
3892 wgpu::BufferUsages::VERTEX
3893 | wgpu::BufferUsages::COPY_DST
3894 | wgpu::BufferUsages::COPY_SRC,
3895 );
3896 let ring_border = UploadRing::new(
3897 &device,
3898 "ring border",
3899 1 << 20,
3900 wgpu::BufferUsages::VERTEX
3901 | wgpu::BufferUsages::COPY_DST
3902 | wgpu::BufferUsages::COPY_SRC,
3903 );
3904 let ring_ellipse = UploadRing::new(
3905 &device,
3906 "ring ellipse",
3907 1 << 20,
3908 wgpu::BufferUsages::VERTEX
3909 | wgpu::BufferUsages::COPY_DST
3910 | wgpu::BufferUsages::COPY_SRC,
3911 );
3912 let ring_ellipse_border = UploadRing::new(
3913 &device,
3914 "ring ellipse border",
3915 1 << 20,
3916 wgpu::BufferUsages::VERTEX
3917 | wgpu::BufferUsages::COPY_DST
3918 | wgpu::BufferUsages::COPY_SRC,
3919 );
3920 let ring_arc = UploadRing::new(
3921 &device,
3922 "ring arc",
3923 1 << 20,
3924 wgpu::BufferUsages::VERTEX
3925 | wgpu::BufferUsages::COPY_DST
3926 | wgpu::BufferUsages::COPY_SRC,
3927 );
3928 let ring_glyph_mask = UploadRing::new(
3929 &device,
3930 "ring glyph mask",
3931 1 << 20,
3932 wgpu::BufferUsages::VERTEX
3933 | wgpu::BufferUsages::COPY_DST
3934 | wgpu::BufferUsages::COPY_SRC,
3935 );
3936 let ring_glyph_color = UploadRing::new(
3937 &device,
3938 "ring glyph color",
3939 1 << 20,
3940 wgpu::BufferUsages::VERTEX
3941 | wgpu::BufferUsages::COPY_DST
3942 | wgpu::BufferUsages::COPY_SRC,
3943 );
3944 let ring_slug = UploadRing::new(
3945 &device,
3946 "ring slug",
3947 1 << 22,
3948 wgpu::BufferUsages::VERTEX
3949 | wgpu::BufferUsages::COPY_DST
3950 | wgpu::BufferUsages::COPY_SRC,
3951 );
3952 let ring_clip = UploadRing::new(
3953 &device,
3954 "ring clip",
3955 1 << 16,
3956 wgpu::BufferUsages::VERTEX
3957 | wgpu::BufferUsages::COPY_DST
3958 | wgpu::BufferUsages::COPY_SRC,
3959 );
3960 let blend_ring = UploadRing::new(
3961 &device,
3962 "ring blend",
3963 1 << 16,
3964 wgpu::BufferUsages::VERTEX
3965 | wgpu::BufferUsages::COPY_DST
3966 | wgpu::BufferUsages::COPY_SRC,
3967 );
3968 let ring_projective = UploadRing::new(
3969 &device,
3970 "ring projective",
3971 1 << 16,
3972 wgpu::BufferUsages::VERTEX
3973 | wgpu::BufferUsages::COPY_DST
3974 | wgpu::BufferUsages::COPY_SRC,
3975 );
3976 let ring_nv12 = UploadRing::new(
3977 &device,
3978 "ring nv12",
3979 1 << 20,
3980 wgpu::BufferUsages::VERTEX
3981 | wgpu::BufferUsages::COPY_DST
3982 | wgpu::BufferUsages::COPY_SRC,
3983 );
3984 let depth_stencil_tex = device.create_texture(&wgpu::TextureDescriptor {
3986 label: Some("temp ds"),
3987 size: wgpu::Extent3d {
3988 width: 1,
3989 height: 1,
3990 depth_or_array_layers: 1,
3991 },
3992 mip_level_count: 1,
3993 sample_count: 1,
3994 dimension: wgpu::TextureDimension::D2,
3995 format: wgpu::TextureFormat::Depth24PlusStencil8,
3996 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
3997 view_formats: &[],
3998 });
3999 let depth_stencil_view =
4000 depth_stencil_tex.create_view(&wgpu::TextureViewDescriptor::default());
4001
4002 let mut renderer = WgpuSceneRenderer {
4003 device,
4004 queue,
4005 output_format,
4006 surface_format: output_format,
4007 output_width: 0,
4008 output_height: 0,
4009 pixels_per_point: 1.0,
4010
4011 surface_pipes,
4012 working_space_pipes,
4013 layer_pipes,
4014 working_space_layer_pipes,
4015
4016 rects: InstancedPipe::new(ring_rect),
4017 borders: InstancedPipe::new(ring_border),
4018 ellipses: InstancedPipe::new(ring_ellipse),
4019 ellipse_borders: InstancedPipe::new(ring_ellipse_border),
4020 arcs: InstancedPipe::new(ring_arc),
4021 glyph_mask: InstancedPipe::new(ring_glyph_mask),
4022 glyph_color: InstancedPipe::new(ring_glyph_color),
4023
4024 text_bind_layout,
4025
4026 image_bind_layout_rgba,
4027 image_bind_layout_nv12,
4028 image_sampler,
4029 image_sampler_nearest,
4030 image_sampler_repeat,
4031 image_sampler_repeat_nearest,
4032 layer_sampler,
4033 layer_sampler_linear,
4034
4035 blur_ring,
4036
4037 slug_enabled,
4038 slug_ring: ring_slug,
4039 slug_cache: slug::GlyphSlugCache::new(),
4040 slug_draw_cache: HashMap::new(),
4041 slug_draw_cache_bytes_total: 0,
4042
4043 clip_ring: ring_clip,
4044
4045 nv12: InstancedPipe::new(ring_nv12),
4046
4047 mesh_cache: HashMap::new(),
4048 mesh_cache_bytes_total: 0,
4049 mesh_uniform_buf,
4050 mesh_bind,
4051 mesh_uniform_head: 0,
4052 mesh_uniform_alignment,
4053 mesh_uniform_cap,
4054 mesh_instance_buf,
4055 mesh_instance_head: 0,
4056 mesh_instance_cap,
4057
4058 projective_ring: ring_projective,
4059 blend_ring,
4060 flatten_layer_ids: Vec::new(),
4061 blur_scratch_ids: HashMap::new(),
4062 blur_scratch_next: 0,
4063 blend_snapshots: std::collections::HashMap::new(),
4064 blend_snapshot_pool: HashMap::new(),
4065 blend_copies: Vec::new(),
4066
4067 msaa_samples,
4068 working_space_msaa_samples,
4069 depth_stencil_tex,
4070 depth_stencil_view,
4071 msaa_tex: None,
4072 msaa_view: None,
4073 ws_msaa_tex: None,
4074 ws_msaa_view: None,
4075 surface_resolve_tex: None,
4076 surface_resolve_view: None,
4077 surface_resolve_bytes: 0,
4078 msaa_bytes: 0,
4079 ws_msaa_bytes: 0,
4080 depth_stencil_bytes: 0,
4081 working_space_bytes: 0,
4082 gpu_budget_bytes: MAX_GPU_RESOURCE_BYTES,
4083 globals_bind,
4084 globals_buf,
4085 globals_staging,
4086 globals_staging_cap,
4087 shape_stops_tex,
4088 shape_stops_bind,
4089
4090 atlas_mask,
4091 atlas_color,
4092 atlas_mask_bind,
4093 atlas_color_bind,
4094 atlas_generation: repose_text::font_generation(),
4095 atlas_mask_pending: AtlasPending::default(),
4096 atlas_color_pending: AtlasPending::default(),
4097 atlas_last_compact_frame: 0,
4098 atlas_mask_failures: HashSet::new(),
4099 atlas_color_failures: HashSet::new(),
4100 atlas_mask_deferred: HashSet::new(),
4101 atlas_color_deferred: HashSet::new(),
4102 glyph_outline_cache: HashMap::new(),
4103 legacy_shaped_text_cache: HashMap::new(),
4104
4105 next_image_handle: 1,
4106 images: HashMap::new(),
4107 retained: HashMap::new(),
4108 retained_bytes_total: 0,
4109
4110 next_coverage_handle: 1,
4111 coverages: HashMap::new(),
4112
4113 frame_index: 0,
4114 cache_touch_clock: 0,
4115 image_bytes_total: 0,
4116 image_evict_after_frames: 600, image_budget_bytes: 512 * 1024 * 1024, layer_pool: HashMap::new(),
4119 producer_layer_ids: HashSet::new(),
4120 layer_bytes_total: 0,
4121 transient_layer_bytes_total: 0,
4122
4123 working_space: false,
4124 ws_tex: None,
4125 ws_view: None,
4126 ws_bind: None,
4127 display_pipeline: None,
4128 display_layout: None,
4129
4130 callback_resources: CallbackResources::default(),
4131 callback_scoped_resources: HashMap::new(),
4132 callback_scope_uses: HashMap::new(),
4133 callback_scope_payloads: HashMap::new(),
4134 callback_scope_clock: 0,
4135 blend_snapshot_bytes_total: 0,
4136 frame_active: false,
4137 last_render_error: None,
4138 };
4139
4140 renderer.recreate_msaa_and_depth_stencil();
4141 Ok(renderer)
4142 }
4143}
4144
4145#[cfg(not(target_arch = "wasm32"))]
4149fn backend_by_name(name: &str) -> Option<wgpu::Backend> {
4150 match name {
4151 "gl" | "opengl" | "opengles" | "webgl" => Some(wgpu::Backend::Gl),
4152 "webgpu" | "browser-webgpu" => Some(wgpu::Backend::BrowserWebGpu),
4153 "metal" => Some(wgpu::Backend::Metal),
4154 "vulkan" => Some(wgpu::Backend::Vulkan),
4155 "dx12" | "d3d12" => Some(wgpu::Backend::Dx12),
4156 _ => None,
4157 }
4158}
4159
4160#[cfg(not(target_arch = "wasm32"))]
4164pub fn parse_backends(spec: &str) -> Option<wgpu::Backends> {
4165 let mut bits = wgpu::Backends::empty();
4166 for name in spec.split([',', ' ', '+']).filter(|n| !n.is_empty()) {
4167 match backend_by_name(&name.to_ascii_lowercase()) {
4168 Some(backend) => bits |= wgpu::Backends::from(backend),
4169 None => log::warn!(
4170 "REPOSE_WGPU_BACKENDS: ignoring unknown backend {name:?}; \
4171 expected one of noop, vulkan, metal, dx12, gl, webgpu"
4172 ),
4173 }
4174 }
4175 (!bits.is_empty()).then_some(bits)
4176}
4177
4178#[cfg(feature = "winit-surface")]
4179pub(crate) async fn surface_instance(
4180 display: Option<winit::event_loop::OwnedDisplayHandle>,
4181) -> (Instance, wgpu::Backends) {
4182 let mut desc = match display {
4187 Some(handle) => wgpu::InstanceDescriptor::new_with_display_handle(Box::new(handle)),
4188 None => wgpu::InstanceDescriptor::new_without_display_handle(),
4189 };
4190 if cfg!(target_arch = "wasm32") {
4191 desc.backends = wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL;
4192 }
4193 #[cfg(not(target_arch = "wasm32"))]
4194 if let Ok(spec) = std::env::var("REPOSE_WGPU_BACKENDS")
4195 && let Some(bits) = parse_backends(&spec)
4196 {
4197 log::info!("REPOSE_WGPU_BACKENDS={spec} -> {bits:?}");
4198 desc.backends = bits;
4199 }
4200
4201 let backends = desc.backends;
4202 let instance = if cfg!(target_arch = "wasm32") {
4203 wgpu::util::new_instance_with_webgpu_detection(desc).await
4204 } else {
4205 wgpu::Instance::new(desc)
4206 };
4207 (instance, backends)
4208}
4209
4210impl WgpuSurfaceBackend {
4211 #[cfg(feature = "winit-surface")]
4212 pub async fn new_async(
4213 window: Arc<winit::window::Window>,
4214 ) -> anyhow::Result<WgpuSurfaceBackend> {
4215 Self::new_async_with_options(window, None, 4, PresentModePref::Auto).await
4216 }
4217
4218 #[cfg(feature = "winit-surface")]
4221 pub async fn new_async_with_msaa(
4222 window: Arc<winit::window::Window>,
4223 msaa_samples: u32,
4224 ) -> anyhow::Result<WgpuSurfaceBackend> {
4225 Self::new_async_with_options(window, None, msaa_samples, PresentModePref::Auto).await
4226 }
4227
4228 #[cfg(feature = "winit-surface")]
4235 pub async fn new_async_with_options(
4236 window: Arc<winit::window::Window>,
4237 display: Option<winit::event_loop::OwnedDisplayHandle>,
4238 msaa_samples: u32,
4239 present_mode: PresentModePref,
4240 ) -> anyhow::Result<WgpuSurfaceBackend> {
4241 let (instance, backends) = surface_instance(display).await;
4242
4243 let surface = instance.create_surface(window.clone())?;
4244
4245 let adapter = instance
4246 .request_adapter(&wgpu::RequestAdapterOptions {
4247 power_preference: wgpu::PowerPreference::HighPerformance,
4248 compatible_surface: Some(&surface),
4249 force_fallback_adapter: false,
4250 apply_limit_buckets: false,
4251 })
4252 .await
4253 .map_err(|e| {
4254 anyhow::anyhow!("no adapter for this window (enabled backends {backends:?}): {e:?}")
4255 })?;
4256 log::info!(
4257 "wgpu adapter: {} backend={:?} driver={:?} type={:?}",
4258 adapter.get_info().name,
4259 adapter.get_info().backend,
4260 adapter.get_info().driver,
4261 adapter.get_info().device_type,
4262 );
4263
4264 let limits = adapter.limits();
4265
4266 let features = {
4267 let available = adapter.features();
4268 let mut features = wgpu::Features::empty();
4269 if available.contains(wgpu::Features::TEXTURE_FORMAT_16BIT_NORM) {
4270 features |= wgpu::Features::TEXTURE_FORMAT_16BIT_NORM;
4271 }
4272 #[cfg(target_os = "linux")]
4273 {
4274 if available.contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_FD) {
4275 features |= wgpu::Features::VULKAN_EXTERNAL_MEMORY_FD;
4276 }
4277 if available.contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF) {
4278 features |= wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF;
4279 }
4280 }
4281 features
4282 };
4283
4284 let (device, queue) = adapter
4285 .request_device(&wgpu::DeviceDescriptor {
4286 label: Some("repose-rs device"),
4287 required_features: features,
4288 required_limits: limits,
4289 experimental_features: wgpu::ExperimentalFeatures::disabled(),
4290 memory_hints: wgpu::MemoryHints::default(),
4291 trace: wgpu::Trace::Off,
4292 })
4293 .await
4294 .map_err(|e| anyhow::anyhow!("request_device failed: {e:?}"))?;
4295
4296 let device_lost = Arc::new(Mutex::new(None));
4297 {
4298 let device_lost = device_lost.clone();
4299 device.set_device_lost_callback(move |reason, message| {
4300 log::error!("wgpu device lost ({reason:?}): {message}");
4301 if let Ok(mut slot) = device_lost.lock() {
4302 *slot = Some((reason, message));
4303 }
4304 });
4305 }
4306
4307 let size = window.inner_size();
4308
4309 let caps = surface.get_capabilities(&adapter);
4310
4311 let Some(format) = caps.formats.first().copied() else {
4312 anyhow::bail!(
4313 "surface exposes no presentable formats (adapter {})",
4314 adapter.get_info().name
4315 );
4316 };
4317
4318 let (format, view_format) = if cfg!(target_arch = "wasm32")
4319 && adapter
4320 .get_downlevel_capabilities()
4321 .flags
4322 .contains(wgpu::DownlevelFlags::SURFACE_VIEW_FORMATS)
4323 {
4324 let non_srgb = caps
4325 .formats
4326 .iter()
4327 .copied()
4328 .find(|f| !f.is_srgb())
4329 .unwrap_or(format);
4330 (non_srgb, Some(non_srgb.add_srgb_suffix()))
4331 } else if cfg!(target_arch = "wasm32") {
4332 let fmt = caps
4333 .formats
4334 .iter()
4335 .copied()
4336 .find(|f| f.is_srgb())
4337 .unwrap_or(format);
4338 (fmt, None)
4339 } else {
4340 let fmt = caps
4341 .formats
4342 .iter()
4343 .copied()
4344 .find(|f| f.is_srgb())
4345 .unwrap_or(format);
4346 (fmt, None)
4347 };
4348
4349 let present_mode = pick_present_mode(&caps, present_mode);
4350 let alpha_mode = *caps
4351 .alpha_modes
4352 .first()
4353 .ok_or_else(|| anyhow::anyhow!("surface exposes no alpha modes"))?;
4354
4355 let render_format = view_format.unwrap_or(format);
4356 let msaa_samples = pick_surface_msaa(&adapter, render_format, msaa_samples);
4357 let mut renderer = WgpuSceneRenderer::try_from_device_with_adapter(
4358 &adapter,
4359 device,
4360 queue,
4361 render_format,
4362 msaa_samples,
4363 )?
4364 .with_surface_format(format)?;
4365 let (fw, fh) = clamp_output_size(
4366 size.width,
4367 size.height,
4368 renderer.device.limits().max_texture_dimension_2d,
4369 );
4370 renderer.resize(fw, fh);
4371
4372 let view_formats = view_format.into_iter().collect::<Vec<_>>();
4373
4374 let wanted_usage = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC;
4382 let surface_usage = wanted_usage & caps.usages;
4383 if surface_usage != wanted_usage {
4384 log::warn!(
4385 "surface {format:?} cannot be used as {:?}; swapchain-sourced blend snapshots \
4386 are skipped on this backend",
4387 wanted_usage - surface_usage
4388 );
4389 }
4390 let config = wgpu::SurfaceConfiguration {
4391 usage: surface_usage,
4392 format,
4393 width: fw.max(1),
4394 height: fh.max(1),
4395 present_mode,
4396 alpha_mode,
4397 color_space: wgpu::SurfaceColorSpace::Auto,
4398 view_formats,
4399 desired_maximum_frame_latency: 1,
4400 };
4401 surface.configure(&renderer.device, &config);
4402
4403 Ok(WgpuSurfaceBackend {
4404 #[cfg(feature = "winit-surface")]
4405 instance: Some(instance),
4406 #[cfg(feature = "winit-surface")]
4407 window: Some(window),
4408 surface: Some(surface),
4409 surface_config: Some(config),
4410 pending_reconfigure: false,
4411 renderer,
4412 device_lost,
4413 })
4414 }
4415
4416 #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
4417 pub fn new(window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
4418 pollster::block_on(Self::new_async(window))
4419 }
4420
4421 #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
4422 pub fn new_with_msaa(
4423 window: Arc<winit::window::Window>,
4424 msaa_samples: u32,
4425 ) -> anyhow::Result<WgpuSurfaceBackend> {
4426 pollster::block_on(Self::new_async_with_msaa(window, msaa_samples))
4427 }
4428
4429 #[cfg(all(feature = "winit-surface", not(target_arch = "wasm32")))]
4430 pub fn new_with_options(
4431 window: Arc<winit::window::Window>,
4432 display: Option<winit::event_loop::OwnedDisplayHandle>,
4433 msaa_samples: u32,
4434 present_mode: PresentModePref,
4435 ) -> anyhow::Result<WgpuSurfaceBackend> {
4436 pollster::block_on(Self::new_async_with_options(
4437 window,
4438 display,
4439 msaa_samples,
4440 present_mode,
4441 ))
4442 }
4443
4444 #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
4445 pub fn new(_window: Arc<winit::window::Window>) -> anyhow::Result<WgpuSurfaceBackend> {
4446 anyhow::bail!("Use WgpuSurfaceBackend::new_async(window).await on wasm32")
4447 }
4448
4449 #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
4450 pub fn new_with_msaa(
4451 _window: Arc<winit::window::Window>,
4452 _msaa_samples: u32,
4453 ) -> anyhow::Result<WgpuSurfaceBackend> {
4454 anyhow::bail!("Use WgpuSurfaceBackend::new_async_with_msaa(window, msaa).await on wasm32")
4455 }
4456
4457 #[cfg(all(feature = "winit-surface", target_arch = "wasm32"))]
4458 pub fn new_with_options(
4459 _window: Arc<winit::window::Window>,
4460 _display: Option<winit::event_loop::OwnedDisplayHandle>,
4461 _msaa_samples: u32,
4462 _present_mode: PresentModePref,
4463 ) -> anyhow::Result<WgpuSurfaceBackend> {
4464 anyhow::bail!(
4465 "Use WgpuSurfaceBackend::new_async_with_options(window, display, msaa, mode).await on wasm32"
4466 )
4467 }
4468
4469 pub fn take_device_lost(&self) -> Option<String> {
4474 let (reason, message) = self.device_lost.lock().ok()?.take()?;
4475 (reason != wgpu::DeviceLostReason::Destroyed).then_some(message)
4476 }
4477}
4478
4479#[cfg(feature = "winit-surface")]
4482fn pick_present_mode(caps: &wgpu::SurfaceCapabilities, pref: PresentModePref) -> wgpu::PresentMode {
4483 let auto = || {
4484 caps.present_modes
4485 .iter()
4486 .copied()
4487 .find(|m| *m == wgpu::PresentMode::Fifo)
4488 .or_else(|| {
4489 caps.present_modes
4490 .iter()
4491 .copied()
4492 .find(|m| *m == wgpu::PresentMode::Mailbox)
4493 })
4494 .unwrap_or(wgpu::PresentMode::Immediate)
4495 };
4496 match pref {
4497 PresentModePref::Auto => auto(),
4498 PresentModePref::Fifo if caps.present_modes.contains(&wgpu::PresentMode::Fifo) => {
4499 wgpu::PresentMode::Fifo
4500 }
4501 PresentModePref::Mailbox if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) => {
4502 wgpu::PresentMode::Mailbox
4503 }
4504 PresentModePref::Immediate
4505 if caps.present_modes.contains(&wgpu::PresentMode::Immediate) =>
4506 {
4507 wgpu::PresentMode::Immediate
4508 }
4509 _ => auto(),
4510 }
4511}
4512
4513const VALID_SAMPLE_COUNTS: [u32; 5] = [1, 2, 4, 8, 16];
4516
4517fn validate_sample_count(label: &str, samples: u32) -> anyhow::Result<()> {
4518 if !VALID_SAMPLE_COUNTS.contains(&samples) {
4519 anyhow::bail!(
4520 "{label} must be one of {VALID_SAMPLE_COUNTS:?} (wgpu-supported sample counts), got {samples}"
4521 );
4522 }
4523 Ok(())
4524}
4525
4526fn validate_render_target_format(
4532 adapter: &wgpu::Adapter,
4533 output_format: wgpu::TextureFormat,
4534 samples: u32,
4535) -> anyhow::Result<()> {
4536 let features = adapter.get_texture_format_features(output_format);
4537 let flags = features.flags;
4538 for (needed, what) in [
4539 (wgpu::TextureUsages::RENDER_ATTACHMENT, "render attachment"),
4540 (wgpu::TextureUsages::TEXTURE_BINDING, "texture binding"),
4541 ] {
4542 if !features.allowed_usages.contains(needed) {
4543 anyhow::bail!("{output_format:?} cannot be used as a {what}");
4544 }
4545 }
4546 if !flags.contains(wgpu::TextureFormatFeatureFlags::BLENDABLE) {
4547 anyhow::bail!("{output_format:?} cannot be blended into");
4548 }
4549 if samples > 1 && !flags.contains(wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE) {
4550 anyhow::bail!(
4551 "{output_format:?} cannot resolve the requested {samples}x multisampled attachment"
4552 );
4553 }
4554 let ws = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba16Float);
4556 if !ws
4557 .allowed_usages
4558 .contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
4559 || !ws
4560 .allowed_usages
4561 .contains(wgpu::TextureUsages::TEXTURE_BINDING)
4562 {
4563 anyhow::bail!(
4564 "{:?} cannot be used for linear working-space rendering",
4565 wgpu::TextureFormat::Rgba16Float
4566 );
4567 }
4568 Ok(())
4569}
4570
4571pub fn pick_surface_msaa(
4574 adapter: &wgpu::Adapter,
4575 format: wgpu::TextureFormat,
4576 requested: u32,
4577) -> u32 {
4578 pick_surface_msaa_for_mode(adapter, format, requested, false)
4579}
4580
4581pub fn pick_surface_msaa_for_mode(
4582 adapter: &wgpu::Adapter,
4583 format: wgpu::TextureFormat,
4584 requested: u32,
4585 working_space: bool,
4586) -> u32 {
4587 let requested = requested.max(1);
4588 let color_feat = adapter.get_texture_format_features(format);
4589 let working_space_feat = adapter.get_texture_format_features(wgpu::TextureFormat::Rgba16Float);
4590 let depth_feat = adapter.get_texture_format_features(wgpu::TextureFormat::Depth24PlusStencil8);
4591 let supported = |n: u32| {
4592 color_feat
4593 .allowed_usages
4594 .contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
4595 && color_feat.flags.sample_count_supported(n)
4596 && (!working_space
4597 || (working_space_feat
4598 .allowed_usages
4599 .contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
4600 && working_space_feat.flags.sample_count_supported(n)
4601 && (n == 1
4602 || working_space_feat
4603 .flags
4604 .contains(wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE))))
4605 && (n == 1
4606 || color_feat
4607 .flags
4608 .contains(wgpu::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE))
4609 && depth_feat
4610 .allowed_usages
4611 .contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
4612 && depth_feat.flags.sample_count_supported(n)
4613 };
4614 let mut candidates = vec![requested];
4615 for n in [8, 4, 2, 1] {
4616 if n < requested {
4617 candidates.push(n);
4618 }
4619 }
4620 let chosen = candidates.into_iter().find(|&n| supported(n)).unwrap_or(1);
4621 if chosen != requested {
4622 log::info!("requested MSAA x{requested}, using x{chosen}");
4623 }
4624 chosen
4625}
4626
4627impl WgpuSceneRenderer {
4628 pub fn set_image_from_bytes(
4631 &mut self,
4632 handle: u64,
4633 data: &[u8],
4634 srgb: bool,
4635 ) -> anyhow::Result<()> {
4636 validate_image_handle(handle)?;
4637 let max_dimension = self.device.limits().max_texture_dimension_2d;
4638 let (w, h, rgba) = decode_image_rgba8(data, max_dimension)?;
4639 self.set_image_rgba8(handle, w, h, &rgba, srgb)?;
4640 repose_core::set_image_intrinsic_size(handle, w, h);
4643 Ok(())
4644 }
4645
4646 pub fn set_image_rgba8(
4647 &mut self,
4648 handle: u64,
4649 w: u32,
4650 h: u32,
4651 rgba: &[u8],
4652 srgb: bool,
4653 ) -> anyhow::Result<()> {
4654 validate_image_handle(handle)?;
4655 validate_texture_dimensions(&self.device, w, h)?;
4656 let expected = checked_image_bytes_usize(w, h, 4)?;
4657 if rgba.len() < expected {
4658 return Err(anyhow::anyhow!(
4659 "RGBA buffer too small: {} < {}",
4660 rgba.len(),
4661 expected
4662 ));
4663 }
4664
4665 let format = if srgb {
4666 wgpu::TextureFormat::Rgba8UnormSrgb
4667 } else {
4668 wgpu::TextureFormat::Rgba8Unorm
4669 };
4670
4671 let needs_recreate = match self.images.get(&handle) {
4672 Some(ImageTex::Rgba {
4673 w: cw,
4674 h: ch,
4675 format: cf,
4676 ..
4677 }) => *cw != w || *ch != h || *cf != format,
4678 _ => true,
4679 };
4680
4681 if needs_recreate {
4682 self.remove_image(handle);
4683
4684 let (tex, binds) = self.create_rgba_tex(w, h, format);
4685 let bytes = checked_image_bytes(w, h, 4)?;
4686 self.image_bytes_total = self.image_bytes_total.saturating_add(bytes);
4687
4688 self.images.insert(
4689 handle,
4690 ImageTex::Rgba {
4691 tex,
4692 binds,
4693 w,
4694 h,
4695 format,
4696 last_used_frame: self.frame_index,
4697 bytes,
4698 },
4699 );
4700 }
4701
4702 if let Some(old) = self.retained.remove(&handle) {
4703 self.retained_bytes_total = self
4704 .retained_bytes_total
4705 .saturating_sub(old.rgba.len() as u64);
4706 }
4707 self.retained_bytes_total = self.retained_bytes_total.saturating_add(expected as u64);
4708 self.retained.insert(
4709 handle,
4710 RetainedImage {
4711 w,
4712 h,
4713 format,
4714 rgba: rgba[..expected].to_vec(),
4715 last_used_frame: self.frame_index,
4716 },
4717 );
4718 self.evict_retained_excess();
4719
4720 let tex = match self.images.get(&handle) {
4721 Some(ImageTex::Rgba { tex, .. }) => tex,
4722 _ => unreachable!(),
4723 };
4724
4725 self.queue.write_texture(
4726 wgpu::TexelCopyTextureInfo {
4727 texture: tex,
4728 mip_level: 0,
4729 origin: wgpu::Origin3d::ZERO,
4730 aspect: wgpu::TextureAspect::All,
4731 },
4732 &rgba[..expected],
4733 wgpu::TexelCopyBufferLayout {
4734 offset: 0,
4735 bytes_per_row: Some(4 * w),
4736 rows_per_image: Some(h),
4737 },
4738 wgpu::Extent3d {
4739 width: w,
4740 height: h,
4741 depth_or_array_layers: 1,
4742 },
4743 );
4744
4745 self.evict_budget_excess();
4747
4748 Ok(())
4749 }
4750
4751 fn create_image_binds(
4754 &self,
4755 view: &wgpu::TextureView,
4756 label: &str,
4757 sampler: Option<&wgpu::Sampler>,
4758 ) -> ImageBinds {
4759 let make = |name: &str, sampler: &wgpu::Sampler| {
4760 self.device.create_bind_group(&wgpu::BindGroupDescriptor {
4761 label: Some(name),
4762 layout: &self.image_bind_layout_rgba,
4763 entries: &[
4764 wgpu::BindGroupEntry {
4765 binding: 0,
4766 resource: wgpu::BindingResource::TextureView(view),
4767 },
4768 wgpu::BindGroupEntry {
4769 binding: 1,
4770 resource: wgpu::BindingResource::Sampler(sampler),
4771 },
4772 ],
4773 })
4774 };
4775 match sampler {
4776 Some(sampler) => {
4777 let bind = make(label, sampler);
4778 ImageBinds {
4779 linear: make(label, sampler),
4780 nearest: bind.clone(),
4781 tile_linear: bind.clone(),
4782 tile_nearest: bind,
4783 }
4784 }
4785 None => ImageBinds {
4786 linear: make(label, &self.image_sampler),
4787 nearest: make(label, &self.image_sampler_nearest),
4788 tile_linear: make(label, &self.image_sampler_repeat),
4789 tile_nearest: make(label, &self.image_sampler_repeat_nearest),
4790 },
4791 }
4792 }
4793
4794 fn create_nv12_binds(
4795 &self,
4796 view_y: &wgpu::TextureView,
4797 view_uv: &wgpu::TextureView,
4798 yuv_buf: &wgpu::Buffer,
4799 label: &str,
4800 ) -> ImageBinds {
4801 let make = |name: &str, sampler: &wgpu::Sampler| {
4802 self.device.create_bind_group(&wgpu::BindGroupDescriptor {
4803 label: Some(name),
4804 layout: &self.image_bind_layout_nv12,
4805 entries: &[
4806 wgpu::BindGroupEntry {
4807 binding: 0,
4808 resource: wgpu::BindingResource::TextureView(view_y),
4809 },
4810 wgpu::BindGroupEntry {
4811 binding: 1,
4812 resource: wgpu::BindingResource::TextureView(view_uv),
4813 },
4814 wgpu::BindGroupEntry {
4815 binding: 2,
4816 resource: wgpu::BindingResource::Sampler(sampler),
4817 },
4818 wgpu::BindGroupEntry {
4819 binding: 3,
4820 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
4821 buffer: yuv_buf,
4822 offset: 0,
4823 size: None,
4824 }),
4825 },
4826 ],
4827 })
4828 };
4829 ImageBinds {
4830 linear: make(label, &self.image_sampler),
4831 nearest: make(label, &self.image_sampler_nearest),
4832 tile_linear: make(label, &self.image_sampler_repeat),
4833 tile_nearest: make(label, &self.image_sampler_repeat_nearest),
4834 }
4835 }
4836
4837 fn create_rgba_tex(
4838 &self,
4839 w: u32,
4840 h: u32,
4841 format: wgpu::TextureFormat,
4842 ) -> (wgpu::Texture, ImageBinds) {
4843 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
4844 label: Some("user image rgba"),
4845 size: wgpu::Extent3d {
4846 width: w,
4847 height: h,
4848 depth_or_array_layers: 1,
4849 },
4850 mip_level_count: 1,
4851 sample_count: 1,
4852 dimension: wgpu::TextureDimension::D2,
4853 format,
4854 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4855 view_formats: &[],
4856 });
4857 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
4858 let binds = self.create_image_binds(&view, "image bind rgba", None);
4859 (tex, binds)
4860 }
4861
4862 fn validate_native_texture_view(
4864 &self,
4865 view: &wgpu::TextureView,
4866 width: u32,
4867 height: u32,
4868 ) -> anyhow::Result<()> {
4869 if width == 0 || height == 0 {
4870 anyhow::bail!("native texture dimensions must be non-zero");
4871 }
4872 let texture = view.texture();
4873 if texture.sample_count() != 1
4874 || texture.dimension() != wgpu::TextureDimension::D2
4875 || texture.depth_or_array_layers() != 1
4876 || texture.mip_level_count() == 0
4877 {
4878 anyhow::bail!("native texture must be a single-sample 2D texture with mip levels");
4879 }
4880 if width > self.device.limits().max_texture_dimension_2d
4881 || height > self.device.limits().max_texture_dimension_2d
4882 {
4883 anyhow::bail!("native texture dimensions exceed the device limit");
4884 }
4885 if !texture
4886 .usage()
4887 .contains(wgpu::TextureUsages::TEXTURE_BINDING)
4888 {
4889 anyhow::bail!("native texture lacks TEXTURE_BINDING usage");
4890 }
4891 if !native_format_supported(texture.format(), self.device.features()) {
4892 anyhow::bail!(
4893 "native texture format {:?} is not a filterable alpha color format",
4894 texture.format()
4895 );
4896 }
4897 if texture.width() < width || texture.height() < height {
4898 anyhow::bail!(
4899 "native texture is {}x{}, smaller than requested {width}x{height}",
4900 texture.width(),
4901 texture.height()
4902 );
4903 }
4904 Ok(())
4905 }
4906
4907 pub fn register_native_texture(
4908 &mut self,
4909 view: &wgpu::TextureView,
4910 width: u32,
4911 height: u32,
4912 ) -> u64 {
4913 if let Err(error) = self.validate_native_texture_view(view, width, height) {
4914 log::warn!("register_native_texture: {error:#}");
4915 return 0;
4916 }
4917 let handle = self.next_image_handle;
4918 self.next_image_handle += 1;
4919 let binds = self.create_image_binds(view, "user native image", None);
4920 self.images.insert(
4921 handle,
4922 ImageTex::User {
4923 binds,
4924 w: width,
4925 h: height,
4926 last_used_frame: self.frame_index,
4927 bytes: 0,
4928 },
4929 );
4930 handle
4931 }
4932
4933 pub fn register_native_texture_with_sampler(
4935 &mut self,
4936 view: &wgpu::TextureView,
4937 sampler_desc: wgpu::SamplerDescriptor<'_>,
4938 width: u32,
4939 height: u32,
4940 ) -> u64 {
4941 if let Err(error) = self.validate_native_texture_view(view, width, height) {
4942 log::warn!("register_native_texture: {error:#}");
4943 return 0;
4944 }
4945 if let Err(error) = validate_sampler_descriptor(&self.device, &sampler_desc) {
4946 log::warn!("register_native_texture: {error:#}");
4947 return 0;
4948 }
4949 let handle = self.next_image_handle;
4950 self.next_image_handle += 1;
4951 let sampler = self.device.create_sampler(&sampler_desc);
4952 let binds = self.create_image_binds(view, "user native image sampleropts", Some(&sampler));
4953 self.images.insert(
4954 handle,
4955 ImageTex::User {
4956 binds,
4957 w: width,
4958 h: height,
4959 last_used_frame: self.frame_index,
4960 bytes: 0,
4961 },
4962 );
4963 handle
4964 }
4965
4966 pub fn update_native_texture(&mut self, handle: u64, view: &wgpu::TextureView) {
4968 if handle == 0 {
4969 log::warn!("update_native_texture: reserved handle");
4970 return;
4971 }
4972 let Some((w, h)) = self.images.get(&handle).and_then(|entry| match entry {
4973 ImageTex::User { w, h, .. } => Some((*w, *h)),
4974 _ => None,
4975 }) else {
4976 log::warn!("update_native_texture: handle {handle} is not a native image");
4977 return;
4978 };
4979 if let Err(error) = self.validate_native_texture_view(view, w, h) {
4980 log::warn!("update_native_texture: {error:#}");
4981 return;
4982 }
4983 let binds = self.create_image_binds(view, "user native image update", None);
4984 if let Some(entry) = self.images.get_mut(&handle) {
4985 *entry = ImageTex::User {
4986 binds,
4987 w,
4988 h,
4989 last_used_frame: self.frame_index,
4990 bytes: 0,
4991 };
4992 }
4993 }
4994
4995 pub fn set_image_nv12(
4996 &mut self,
4997 handle: u64,
4998 w: u32,
4999 h: u32,
5000 y: &[u8],
5001 uv: &[u8],
5002 color_info: ColorInfo,
5003 ) -> anyhow::Result<()> {
5004 validate_image_handle(handle)?;
5005 validate_texture_dimensions(&self.device, w, h)?;
5006 if self
5007 .images
5008 .get(&handle)
5009 .is_some_and(|image| matches!(image, ImageTex::Nv12 { external: true, .. }))
5010 {
5011 anyhow::bail!("cannot overwrite an external DMA-BUF image");
5012 }
5013 let y_expected = checked_image_bytes_usize(w, h, 1)?;
5014 let uv_w = w.div_ceil(2);
5015 let uv_h = h.div_ceil(2);
5016 let uv_expected = checked_image_bytes_usize(uv_w, uv_h, 2)?;
5017
5018 if y.len() < y_expected {
5019 return Err(anyhow::anyhow!("Y plane too small"));
5020 }
5021 if uv.len() < uv_expected {
5022 return Err(anyhow::anyhow!("UV plane too small"));
5023 }
5024
5025 let needs_recreate = match self.images.get(&handle) {
5026 Some(ImageTex::Nv12 {
5027 w: ww,
5028 h: hh,
5029 pixel_format,
5030 ..
5031 }) => *ww != w || *hh != h || *pixel_format != PixelFormat::Nv12,
5032 _ => true,
5033 };
5034
5035 let yuv_raw = make_yuv_transform_raw(color_info, PixelFormat::Nv12);
5037
5038 if needs_recreate {
5039 self.remove_image(handle);
5040
5041 let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
5042 label: Some("nv12 Y"),
5043 size: wgpu::Extent3d {
5044 width: w,
5045 height: h,
5046 depth_or_array_layers: 1,
5047 },
5048 mip_level_count: 1,
5049 sample_count: 1,
5050 dimension: wgpu::TextureDimension::D2,
5051 format: wgpu::TextureFormat::R8Unorm,
5052 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
5053 view_formats: &[],
5054 });
5055 let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
5056
5057 let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
5058 label: Some("nv12 UV"),
5059 size: wgpu::Extent3d {
5060 width: uv_w,
5061 height: uv_h,
5062 depth_or_array_layers: 1,
5063 },
5064 mip_level_count: 1,
5065 sample_count: 1,
5066 dimension: wgpu::TextureDimension::D2,
5067 format: wgpu::TextureFormat::Rg8Unorm,
5068 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
5069 view_formats: &[],
5070 });
5071 let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
5072
5073 let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
5075 label: Some("nv12 yuv transform"),
5076 size: std::mem::size_of::<YuvTransformRaw>() as u64,
5077 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5078 mapped_at_creation: false,
5079 });
5080
5081 self.queue
5083 .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
5084
5085 let binds = self.create_nv12_binds(&view_y, &view_uv, &yuv_buf, "nv12 bind");
5086
5087 let bytes = checked_image_bytes(w, h, 1)?
5088 .checked_add(checked_image_bytes(uv_w, uv_h, 2)?)
5089 .and_then(|bytes| bytes.checked_add(std::mem::size_of::<YuvTransformRaw>() as u64))
5090 .ok_or_else(|| anyhow::anyhow!("NV12 image byte size overflow"))?;
5091 self.image_bytes_total = self.image_bytes_total.saturating_add(bytes);
5092
5093 self.images.insert(
5094 handle,
5095 ImageTex::Nv12 {
5096 tex_y,
5097 tex_uv,
5098 binds,
5099 yuv_buf,
5100 w,
5101 h,
5102 pixel_format: PixelFormat::Nv12,
5103 fourcc: Some(NV12_FOURCC),
5104 color_info,
5105 external: false,
5106 last_used_frame: self.frame_index,
5107 bytes,
5108 },
5109 );
5110 } else {
5111 if let Some(ImageTex::Nv12 {
5113 yuv_buf,
5114 color_info: stored_color,
5115 last_used_frame,
5116 ..
5117 }) = self.images.get_mut(&handle)
5118 {
5119 *stored_color = color_info;
5120 *last_used_frame = self.frame_index;
5121 self.queue
5122 .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
5123 }
5124 }
5125
5126 let (tex_y, tex_uv, _binds) = match self.images.get(&handle) {
5127 Some(ImageTex::Nv12 {
5128 tex_y,
5129 tex_uv,
5130 binds,
5131 ..
5132 }) => (tex_y, tex_uv, binds),
5133 _ => return Err(anyhow::anyhow!("Handle is not NV12")),
5134 };
5135
5136 self.queue.write_texture(
5137 wgpu::TexelCopyTextureInfo {
5138 texture: tex_y,
5139 mip_level: 0,
5140 origin: wgpu::Origin3d::ZERO,
5141 aspect: wgpu::TextureAspect::All,
5142 },
5143 &y[..y_expected],
5144 wgpu::TexelCopyBufferLayout {
5145 offset: 0,
5146 bytes_per_row: Some(w),
5147 rows_per_image: Some(h),
5148 },
5149 wgpu::Extent3d {
5150 width: w,
5151 height: h,
5152 depth_or_array_layers: 1,
5153 },
5154 );
5155
5156 self.queue.write_texture(
5157 wgpu::TexelCopyTextureInfo {
5158 texture: tex_uv,
5159 mip_level: 0,
5160 origin: wgpu::Origin3d::ZERO,
5161 aspect: wgpu::TextureAspect::All,
5162 },
5163 &uv[..uv_expected],
5164 wgpu::TexelCopyBufferLayout {
5165 offset: 0,
5166 bytes_per_row: Some(2 * uv_w),
5167 rows_per_image: Some(uv_h),
5168 },
5169 wgpu::Extent3d {
5170 width: uv_w,
5171 height: uv_h,
5172 depth_or_array_layers: 1,
5173 },
5174 );
5175
5176 self.evict_budget_excess();
5177 Ok(())
5178 }
5179
5180 pub fn set_image_planes(
5181 &mut self,
5182 handle: u64,
5183 w: u32,
5184 h: u32,
5185 pixel_format: PixelFormat,
5186 planes: &[&[u8]],
5187 color_info: ColorInfo,
5188 ) -> anyhow::Result<()> {
5189 validate_image_handle(handle)?;
5190 if planes.len() != pixel_format.num_planes() as usize {
5191 anyhow::bail!(
5192 "{} requires {} planes, got {}",
5193 match pixel_format {
5194 PixelFormat::Nv12 => "NV12",
5195 PixelFormat::P010 => "P010",
5196 PixelFormat::I420 => "I420",
5197 PixelFormat::I444 => "I444",
5198 PixelFormat::Rgba => "RGBA",
5199 },
5200 pixel_format.num_planes(),
5201 planes.len()
5202 );
5203 }
5204 match pixel_format {
5205 PixelFormat::Nv12 => {
5206 let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
5207 let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
5208 self.set_image_nv12(handle, w, h, y, uv, color_info)
5209 }
5210 PixelFormat::P010 => {
5211 let y = planes.first().ok_or(anyhow::anyhow!("missing Y plane"))?;
5212 let uv = planes.get(1).ok_or(anyhow::anyhow!("missing UV plane"))?;
5213 self.set_image_p010(handle, w, h, y, uv, color_info)
5214 }
5215 PixelFormat::I420 | PixelFormat::I444 => Err(anyhow::anyhow!(
5216 "I420/I444 not implemented and unlikely -> cheap to convert to NV12 (better for the GPU too)"
5217 )),
5218 PixelFormat::Rgba => {
5219 let rgba = planes
5220 .first()
5221 .ok_or(anyhow::anyhow!("missing RGBA plane"))?;
5222 self.set_image_rgba8(handle, w, h, rgba, false)
5223 }
5224 }
5225 }
5226
5227 fn set_image_p010(
5228 &mut self,
5229 handle: u64,
5230 w: u32,
5231 h: u32,
5232 y: &[u8],
5233 uv: &[u8],
5234 color_info: ColorInfo,
5235 ) -> anyhow::Result<()> {
5236 validate_image_handle(handle)?;
5237 validate_texture_dimensions(&self.device, w, h)?;
5238 if self
5239 .images
5240 .get(&handle)
5241 .is_some_and(|image| matches!(image, ImageTex::Nv12 { external: true, .. }))
5242 {
5243 anyhow::bail!("cannot overwrite an external DMA-BUF image");
5244 }
5245 if !self
5246 .device
5247 .features()
5248 .contains(wgpu::Features::TEXTURE_FORMAT_16BIT_NORM)
5249 {
5250 anyhow::bail!("P010 requires TEXTURE_FORMAT_16BIT_NORM");
5251 }
5252 let uv_w = w.div_ceil(2);
5253 let uv_h = h.div_ceil(2);
5254
5255 let y_expected = checked_image_bytes_usize(w, h, 2)?;
5256 let uv_expected = checked_image_bytes_usize(uv_w, uv_h, 4)?;
5257
5258 if y.len() < y_expected {
5259 return Err(anyhow::anyhow!("P010 Y plane too small"));
5260 }
5261 if uv.len() < uv_expected {
5262 return Err(anyhow::anyhow!("P010 UV plane too small"));
5263 }
5264
5265 let needs_recreate = match self.images.get(&handle) {
5269 Some(ImageTex::Nv12 {
5270 w: ww,
5271 h: hh,
5272 pixel_format,
5273 ..
5274 }) => *ww != w || *hh != h || *pixel_format != PixelFormat::P010,
5275 _ => true,
5276 };
5277
5278 let yuv_raw = make_yuv_transform_raw(color_info, PixelFormat::P010);
5279
5280 if needs_recreate {
5281 self.remove_image(handle);
5282
5283 let tex_y = self.device.create_texture(&wgpu::TextureDescriptor {
5284 label: Some("p010 Y"),
5285 size: wgpu::Extent3d {
5286 width: w,
5287 height: h,
5288 depth_or_array_layers: 1,
5289 },
5290 mip_level_count: 1,
5291 sample_count: 1,
5292 dimension: wgpu::TextureDimension::D2,
5293 format: wgpu::TextureFormat::R16Unorm,
5294 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
5295 view_formats: &[],
5296 });
5297 let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
5298
5299 let tex_uv = self.device.create_texture(&wgpu::TextureDescriptor {
5300 label: Some("p010 UV"),
5301 size: wgpu::Extent3d {
5302 width: uv_w,
5303 height: uv_h,
5304 depth_or_array_layers: 1,
5305 },
5306 mip_level_count: 1,
5307 sample_count: 1,
5308 dimension: wgpu::TextureDimension::D2,
5309 format: wgpu::TextureFormat::Rg16Unorm,
5310 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
5311 view_formats: &[],
5312 });
5313 let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
5314
5315 let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
5316 label: Some("p010 yuv transform"),
5317 size: std::mem::size_of::<YuvTransformRaw>() as u64,
5318 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5319 mapped_at_creation: false,
5320 });
5321 self.queue
5322 .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
5323
5324 let binds = self.create_nv12_binds(&view_y, &view_uv, &yuv_buf, "p010 bind");
5325
5326 let bytes = checked_image_bytes(w, h, 2)?
5327 .checked_add(checked_image_bytes(uv_w, uv_h, 4)?)
5328 .and_then(|bytes| bytes.checked_add(std::mem::size_of::<YuvTransformRaw>() as u64))
5329 .ok_or_else(|| anyhow::anyhow!("P010 image byte size overflow"))?;
5330 self.image_bytes_total = self.image_bytes_total.saturating_add(bytes);
5331
5332 self.images.insert(
5333 handle,
5334 ImageTex::Nv12 {
5335 tex_y,
5336 tex_uv,
5337 binds,
5338 yuv_buf,
5339 w,
5340 h,
5341 pixel_format: PixelFormat::P010,
5342 fourcc: Some(P010_FOURCC),
5343 color_info,
5344 external: false,
5345 last_used_frame: self.frame_index,
5346 bytes,
5347 },
5348 );
5349 } else {
5350 if let Some(ImageTex::Nv12 {
5351 yuv_buf,
5352 color_info: stored_color,
5353 last_used_frame,
5354 ..
5355 }) = self.images.get_mut(&handle)
5356 {
5357 *stored_color = color_info;
5358 *last_used_frame = self.frame_index;
5359 self.queue
5360 .write_buffer(yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
5361 }
5362 }
5363
5364 let (tex_y, tex_uv, _binds) = match self.images.get(&handle) {
5365 Some(ImageTex::Nv12 {
5366 tex_y,
5367 tex_uv,
5368 binds,
5369 ..
5370 }) => (tex_y, tex_uv, binds),
5371 _ => return Err(anyhow::anyhow!("Handle is not P010/NV12")),
5372 };
5373
5374 self.queue.write_texture(
5375 wgpu::TexelCopyTextureInfo {
5376 texture: tex_y,
5377 mip_level: 0,
5378 origin: wgpu::Origin3d::ZERO,
5379 aspect: wgpu::TextureAspect::All,
5380 },
5381 &y[..y_expected],
5382 wgpu::TexelCopyBufferLayout {
5383 offset: 0,
5384 bytes_per_row: Some(
5385 w.checked_mul(2)
5386 .ok_or_else(|| anyhow::anyhow!("P010 row size overflow"))?,
5387 ),
5388 rows_per_image: Some(h),
5389 },
5390 wgpu::Extent3d {
5391 width: w,
5392 height: h,
5393 depth_or_array_layers: 1,
5394 },
5395 );
5396 self.queue.write_texture(
5397 wgpu::TexelCopyTextureInfo {
5398 texture: tex_uv,
5399 mip_level: 0,
5400 origin: wgpu::Origin3d::ZERO,
5401 aspect: wgpu::TextureAspect::All,
5402 },
5403 &uv[..uv_expected],
5404 wgpu::TexelCopyBufferLayout {
5405 offset: 0,
5406 bytes_per_row: Some(
5407 uv_w.checked_mul(4)
5408 .ok_or_else(|| anyhow::anyhow!("P010 UV row size overflow"))?,
5409 ),
5410 rows_per_image: Some(uv_h),
5411 },
5412 wgpu::Extent3d {
5413 width: uv_w,
5414 height: uv_h,
5415 depth_or_array_layers: 1,
5416 },
5417 );
5418
5419 self.evict_budget_excess();
5420 Ok(())
5421 }
5422
5423 #[cfg(target_os = "linux")]
5424 pub fn set_image_dmabuf(
5425 &mut self,
5426 handle: u64,
5427 w: u32,
5428 h: u32,
5429 fds: Vec<std::os::unix::io::OwnedFd>,
5430 modifier: u64,
5431 strides: Vec<u32>,
5432 offsets: Vec<u64>,
5433 color_info: ColorInfo,
5434 ) -> anyhow::Result<()> {
5435 self.set_image_dmabuf_fourcc(
5436 handle,
5437 w,
5438 h,
5439 fds,
5440 NV12_FOURCC,
5441 modifier,
5442 strides,
5443 offsets,
5444 color_info,
5445 )
5446 }
5447
5448 #[cfg(target_os = "linux")]
5449 pub fn set_image_dmabuf_fourcc(
5450 &mut self,
5451 handle: u64,
5452 w: u32,
5453 h: u32,
5454 fds: Vec<std::os::unix::io::OwnedFd>,
5455 fourcc: u32,
5456 modifier: u64,
5457 strides: Vec<u32>,
5458 offsets: Vec<u64>,
5459 color_info: ColorInfo,
5460 ) -> anyhow::Result<()> {
5461 validate_image_handle(handle)?;
5462 checked_image_bytes(w, h, 1)?;
5463 if w == 0
5464 || h == 0
5465 || w > self.device.limits().max_texture_dimension_2d
5466 || h > self.device.limits().max_texture_dimension_2d
5467 {
5468 anyhow::bail!("DMA-BUF dimensions are outside the device texture limit");
5469 }
5470 if modifier == u64::MAX {
5471 anyhow::bail!("DMA-BUF modifier is invalid");
5472 }
5473 if fds.len() != 2 || strides.len() != 2 || offsets.len() != 2 {
5474 anyhow::bail!(
5475 "DMA-BUF import requires two fds, strides, and offsets (got {}, {}, {})",
5476 fds.len(),
5477 strides.len(),
5478 offsets.len()
5479 );
5480 }
5481 let pixel_format = match fourcc {
5482 0x3231_564e | 0x4e56_3132 => PixelFormat::Nv12,
5483 0x3031_3050 | 0x5030_3130 => PixelFormat::P010,
5484 _ => anyhow::bail!("unsupported DMA-BUF fourcc 0x{fourcc:08x}"),
5485 };
5486 if !self
5487 .device
5488 .features()
5489 .contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF)
5490 {
5491 anyhow::bail!("DMA-BUF import requires VULKAN_EXTERNAL_MEMORY_DMA_BUF");
5492 }
5493 if pixel_format == PixelFormat::P010
5494 && !self
5495 .device
5496 .features()
5497 .contains(wgpu::Features::TEXTURE_FORMAT_16BIT_NORM)
5498 {
5499 anyhow::bail!("P010 DMA-BUF requires TEXTURE_FORMAT_16BIT_NORM");
5500 }
5501 let bytes_per_pixel = if pixel_format == PixelFormat::P010 {
5502 2
5503 } else {
5504 1
5505 };
5506 let uv_w = w.div_ceil(2);
5507 let uv_h = h.div_ceil(2);
5508 let y_file_size =
5509 validate_dmabuf_plane(&fds[0], offsets[0], strides[0], w, h, bytes_per_pixel)?;
5510 let uv_file_size = validate_dmabuf_plane(
5511 &fds[1],
5512 offsets[1],
5513 strides[1],
5514 uv_w,
5515 uv_h,
5516 bytes_per_pixel * 2,
5517 )?;
5518 let yuv_raw = make_yuv_transform_raw(color_info, pixel_format);
5519 let (y_format, uv_format) = if pixel_format == PixelFormat::P010 {
5520 (
5521 wgpu::TextureFormat::R16Unorm,
5522 wgpu::TextureFormat::Rg16Unorm,
5523 )
5524 } else {
5525 (wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::Rg8Unorm)
5526 };
5527 let hal_y_desc = wgpu::hal::TextureDescriptor {
5528 label: Some("dmabuf y"),
5529 size: wgpu::Extent3d {
5530 width: w,
5531 height: h,
5532 depth_or_array_layers: 1,
5533 },
5534 mip_level_count: 1,
5535 sample_count: 1,
5536 dimension: wgpu::TextureDimension::D2,
5537 format: y_format,
5538 usage: wgpu::wgt::TextureUses::RESOURCE,
5539 memory_flags: wgpu::hal::MemoryFlags::empty(),
5540 view_formats: vec![],
5541 };
5542 let hal_uv_desc = wgpu::hal::TextureDescriptor {
5543 label: Some("dmabuf uv"),
5544 size: wgpu::Extent3d {
5545 width: uv_w,
5546 height: uv_h,
5547 depth_or_array_layers: 1,
5548 },
5549 mip_level_count: 1,
5550 sample_count: 1,
5551 dimension: wgpu::TextureDimension::D2,
5552 format: uv_format,
5553 usage: wgpu::wgt::TextureUses::RESOURCE,
5554 memory_flags: wgpu::hal::MemoryFlags::empty(),
5555 view_formats: vec![],
5556 };
5557 let wgpu_y_desc = wgpu::TextureDescriptor {
5558 label: Some("dmabuf y"),
5559 size: hal_y_desc.size,
5560 mip_level_count: 1,
5561 sample_count: 1,
5562 dimension: wgpu::TextureDimension::D2,
5563 format: y_format,
5564 usage: wgpu::TextureUsages::TEXTURE_BINDING,
5565 view_formats: &[],
5566 };
5567 let wgpu_uv_desc = wgpu::TextureDescriptor {
5568 label: Some("dmabuf uv"),
5569 size: hal_uv_desc.size,
5570 mip_level_count: 1,
5571 sample_count: 1,
5572 dimension: wgpu::TextureDimension::D2,
5573 format: uv_format,
5574 usage: wgpu::TextureUsages::TEXTURE_BINDING,
5575 view_formats: &[],
5576 };
5577
5578 let (tex_y, view_y, tex_uv, view_uv) = unsafe {
5579 let hal_guard = self
5580 .device
5581 .as_hal::<wgpu::hal::vulkan::Api>()
5582 .ok_or_else(|| anyhow::anyhow!("device is not Vulkan"))?;
5583 let mut fds = fds.into_iter();
5584 let y_fd = fds.next().expect("validated fd count");
5585 let uv_fd = fds.next().expect("validated fd count");
5586 let y_texture = hal_guard.texture_from_dmabuf_fd(
5587 y_fd,
5588 &hal_y_desc,
5589 modifier,
5590 strides[0] as u64,
5591 offsets[0],
5592 );
5593 let y_texture =
5594 y_texture.map_err(|error| anyhow::anyhow!("import Y DMA-BUF: {error:?}"))?;
5595 let uv_texture = hal_guard.texture_from_dmabuf_fd(
5596 uv_fd,
5597 &hal_uv_desc,
5598 modifier,
5599 strides[1] as u64,
5600 offsets[1],
5601 );
5602 let uv_texture =
5603 uv_texture.map_err(|error| anyhow::anyhow!("import UV DMA-BUF: {error:?}"))?;
5604 drop(hal_guard);
5605 let tex_y = self
5606 .device
5607 .create_texture_from_hal::<wgpu::hal::vulkan::Api>(
5608 y_texture,
5609 &wgpu_y_desc,
5610 wgpu::wgt::TextureUses::UNINITIALIZED,
5611 );
5612 let tex_uv = self
5613 .device
5614 .create_texture_from_hal::<wgpu::hal::vulkan::Api>(
5615 uv_texture,
5616 &wgpu_uv_desc,
5617 wgpu::wgt::TextureUses::UNINITIALIZED,
5618 );
5619 let view_y = tex_y.create_view(&wgpu::TextureViewDescriptor::default());
5620 let view_uv = tex_uv.create_view(&wgpu::TextureViewDescriptor::default());
5621 (tex_y, view_y, tex_uv, view_uv)
5622 };
5623
5624 let yuv_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
5625 label: Some("dmabuf yuv transform"),
5626 size: std::mem::size_of::<YuvTransformRaw>() as u64,
5627 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
5628 mapped_at_creation: false,
5629 });
5630 self.queue
5631 .write_buffer(&yuv_buf, 0, bytemuck::bytes_of(&yuv_raw));
5632 let binds = self.create_nv12_binds(&view_y, &view_uv, &yuv_buf, "dmabuf yuv bind");
5633 let bytes = y_file_size
5634 .checked_add(uv_file_size)
5635 .and_then(|value| value.checked_add(std::mem::size_of::<YuvTransformRaw>() as u64))
5636 .ok_or_else(|| anyhow::anyhow!("DMA-BUF byte size overflow"))?;
5637 self.evict_budget_excess();
5638 let replaced_bytes = self
5639 .images
5640 .get(&handle)
5641 .map(|image| match image {
5642 ImageTex::Rgba { bytes, .. }
5643 | ImageTex::Nv12 { bytes, .. }
5644 | ImageTex::User { bytes, .. } => *bytes,
5645 })
5646 .unwrap_or(0);
5647 let projected = self
5648 .image_bytes_total
5649 .saturating_sub(replaced_bytes)
5650 .checked_add(bytes)
5651 .ok_or_else(|| anyhow::anyhow!("DMA-BUF image budget overflow"))?;
5652 if projected > self.image_budget_bytes {
5653 anyhow::bail!("DMA-BUF image budget exceeded");
5654 }
5655 self.remove_image(handle);
5656 self.image_bytes_total = self.image_bytes_total.saturating_add(bytes);
5657 self.images.insert(
5658 handle,
5659 ImageTex::Nv12 {
5660 tex_y,
5661 tex_uv,
5662 binds,
5663 yuv_buf,
5664 w,
5665 h,
5666 pixel_format,
5667 fourcc: Some(canonical_fourcc(pixel_format)),
5668 color_info,
5669 external: true,
5670 last_used_frame: self.frame_index,
5671 bytes,
5672 },
5673 );
5674 self.evict_budget_excess();
5675 Ok(())
5676 }
5677
5678 pub fn image_fourcc(&self, handle: u64) -> Option<u32> {
5679 match self.images.get(&handle) {
5680 Some(ImageTex::Nv12 { fourcc, .. }) => *fourcc,
5681 _ => None,
5682 }
5683 }
5684
5685 pub fn remove_image(&mut self, handle: u64) {
5686 if let Some(img) = self.images.remove(&handle) {
5687 let b = match &img {
5688 ImageTex::Rgba { bytes, .. } => *bytes,
5689 ImageTex::Nv12 { bytes, .. } => *bytes,
5690 ImageTex::User { bytes, .. } => *bytes,
5691 };
5692 self.image_bytes_total = self.image_bytes_total.saturating_sub(b);
5693 }
5694 if let Some(retained) = self.retained.remove(&handle) {
5695 self.retained_bytes_total = self
5696 .retained_bytes_total
5697 .saturating_sub(retained.rgba.len() as u64);
5698 }
5699 }
5700
5701 fn evict_image_gpu(&mut self, handle: u64) -> u64 {
5702 let Some(img) = self.images.remove(&handle) else {
5703 return 0;
5704 };
5705 let b = match &img {
5706 ImageTex::Rgba { bytes, .. } => *bytes,
5707 ImageTex::Nv12 { bytes, .. } => *bytes,
5708 ImageTex::User { bytes, .. } => *bytes,
5709 };
5710 self.image_bytes_total = self.image_bytes_total.saturating_sub(b);
5711 b
5712 }
5713
5714 fn revive_retained_image(&mut self, handle: u64) -> anyhow::Result<bool> {
5715 if self.images.contains_key(&handle) {
5716 return Ok(true);
5717 }
5718 let Some(r) = self.retained.get_mut(&handle) else {
5719 return Ok(false);
5720 };
5721 r.last_used_frame = self.frame_index;
5722 let r = r.clone();
5723 let (tex, binds) = self.create_rgba_tex(r.w, r.h, r.format);
5724
5725 self.queue.write_texture(
5726 wgpu::TexelCopyTextureInfo {
5727 texture: &tex,
5728 mip_level: 0,
5729 origin: wgpu::Origin3d::ZERO,
5730 aspect: wgpu::TextureAspect::All,
5731 },
5732 &r.rgba,
5733 wgpu::TexelCopyBufferLayout {
5734 offset: 0,
5735 bytes_per_row: Some(4 * r.w),
5736 rows_per_image: Some(r.h),
5737 },
5738 wgpu::Extent3d {
5739 width: r.w,
5740 height: r.h,
5741 depth_or_array_layers: 1,
5742 },
5743 );
5744
5745 let bytes = checked_image_bytes(r.w, r.h, 4)?;
5746 self.image_bytes_total = self.image_bytes_total.saturating_add(bytes);
5747 self.images.insert(
5748 handle,
5749 ImageTex::Rgba {
5750 tex,
5751 binds,
5752 w: r.w,
5753 h: r.h,
5754 format: r.format,
5755 last_used_frame: self.frame_index,
5756 bytes,
5757 },
5758 );
5759 Ok(true)
5760 }
5761
5762 fn resolve_image_for_draw(&mut self, handle: u64) -> Option<(u32, u32, bool)> {
5763 if let Some(retained) = self.retained.get_mut(&handle) {
5764 retained.last_used_frame = self.frame_index;
5765 }
5766 if let Some(t) = self.images.get_mut(&handle) {
5767 return match t {
5768 ImageTex::Rgba {
5769 w,
5770 h,
5771 last_used_frame,
5772 ..
5773 } => {
5774 *last_used_frame = self.frame_index;
5775 Some((*w, *h, false))
5776 }
5777 ImageTex::User {
5778 w,
5779 h,
5780 last_used_frame,
5781 ..
5782 } => {
5783 *last_used_frame = self.frame_index;
5784 Some((*w, *h, false))
5785 }
5786 ImageTex::Nv12 {
5787 w,
5788 h,
5789 last_used_frame,
5790 ..
5791 } => {
5792 *last_used_frame = self.frame_index;
5793 Some((*w, *h, true))
5794 }
5795 };
5796 }
5797 if self.revive_retained_image(handle).unwrap_or(false)
5798 && let Some(ImageTex::Rgba {
5799 w,
5800 h,
5801 last_used_frame,
5802 ..
5803 }) = self.images.get_mut(&handle)
5804 {
5805 *last_used_frame = self.frame_index;
5806 return Some((*w, *h, false));
5807 }
5808 None
5809 }
5810
5811 pub fn register_image_from_bytes(&mut self, data: &[u8], srgb: bool) -> u64 {
5813 let handle = self.next_image_handle;
5814 self.next_image_handle += 1;
5815 if let Err(e) = self.set_image_from_bytes(handle, data, srgb) {
5816 log::error!("Failed to register image: {e}");
5817 }
5818 handle
5819 }
5820
5821 pub fn register_image_rgba8(&mut self, w: u32, h: u32, rgba: &[u8], srgb: bool) -> u64 {
5826 let handle = self.next_image_handle;
5827 self.next_image_handle += 1;
5828 if let Err(e) = self.set_image_rgba8(handle, w, h, rgba, srgb) {
5829 log::error!("Failed to register image: {e}");
5830 }
5831 handle
5832 }
5833
5834 pub fn register_coverage_a8(&mut self, w: u32, h: u32, coverage: &[u8]) -> u64 {
5840 if validate_texture_dimensions(&self.device, w, h).is_err() {
5841 log::error!("Coverage dimensions are outside the device limit");
5842 return 0;
5843 }
5844 let Ok(expected_bytes) = checked_image_bytes(w, h, 1) else {
5845 log::error!("Coverage dimensions overflow");
5846 return 0;
5847 };
5848 let Ok(expected) = usize::try_from(expected_bytes) else {
5849 log::error!("Coverage dimensions exceed addressable memory");
5850 return 0;
5851 };
5852 if coverage.len() < expected {
5853 log::error!("Coverage buffer too small: {} < {expected}", coverage.len());
5854 return 0;
5855 }
5856 let handle = self.next_coverage_handle;
5857 self.next_coverage_handle += 1;
5858
5859 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
5860 label: Some("coverage tile a8"),
5861 size: wgpu::Extent3d {
5862 width: w,
5863 height: h,
5864 depth_or_array_layers: 1,
5865 },
5866 mip_level_count: 1,
5867 sample_count: 1,
5868 dimension: wgpu::TextureDimension::D2,
5869 format: wgpu::TextureFormat::R8Unorm,
5870 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
5871 view_formats: &[],
5872 });
5873 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
5874 let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
5875 label: Some("coverage bind a8"),
5876 layout: &self.image_bind_layout_rgba,
5877 entries: &[
5878 wgpu::BindGroupEntry {
5879 binding: 0,
5880 resource: wgpu::BindingResource::TextureView(&view),
5881 },
5882 wgpu::BindGroupEntry {
5883 binding: 1,
5884 resource: wgpu::BindingResource::Sampler(&self.image_sampler),
5885 },
5886 ],
5887 });
5888 self.queue.write_texture(
5889 wgpu::TexelCopyTextureInfo {
5890 texture: &tex,
5891 mip_level: 0,
5892 origin: wgpu::Origin3d::ZERO,
5893 aspect: wgpu::TextureAspect::All,
5894 },
5895 &coverage[..expected],
5896 wgpu::TexelCopyBufferLayout {
5897 offset: 0,
5898 bytes_per_row: Some(w),
5899 rows_per_image: Some(h),
5900 },
5901 wgpu::Extent3d {
5902 width: w,
5903 height: h,
5904 depth_or_array_layers: 1,
5905 },
5906 );
5907 let bytes = checked_image_bytes(w, h, 1).unwrap_or(u64::MAX);
5908 self.image_bytes_total = self.image_bytes_total.saturating_add(bytes);
5909 self.coverages.insert(
5910 handle,
5911 CoverageTex {
5912 tex,
5913 bind,
5914 w,
5915 h,
5916 last_used_frame: self.frame_index,
5917 bytes,
5918 },
5919 );
5920 self.evict_budget_excess();
5921 handle
5922 }
5923
5924 pub fn remove_coverage(&mut self, handle: u64) {
5926 if let Some(tile) = self.coverages.remove(&handle) {
5927 self.image_bytes_total = self.image_bytes_total.saturating_sub(tile.bytes);
5928 }
5929 }
5930
5931 pub fn coverage_dimensions(&mut self, handle: u64) -> Option<(u32, u32)> {
5934 if let Some(tile) = self.coverages.get_mut(&handle) {
5935 tile.last_used_frame = self.frame_index;
5936 return Some((tile.w, tile.h));
5937 }
5938 None
5939 }
5940
5941 fn evict_retained_excess(&mut self) {
5942 let mut candidates: Vec<(u64, u64, u64)> = self
5943 .retained
5944 .iter()
5945 .map(|(handle, image)| (*handle, image.last_used_frame, image.rgba.len() as u64))
5946 .collect();
5947 candidates.sort_by_key(|candidate| candidate.1);
5948 for (handle, _last_used, bytes) in candidates {
5949 if self.retained.len() <= MAX_RETAINED_IMAGES
5950 && self.retained_bytes_total <= MAX_RETAINED_IMAGE_BYTES
5951 {
5952 break;
5953 }
5954 if let Some(image) = self.retained.remove(&handle) {
5955 self.retained_bytes_total = self
5956 .retained_bytes_total
5957 .saturating_sub(bytes.min(image.rgba.len() as u64));
5958 }
5959 }
5960 }
5961
5962 fn evict_unused_images(&mut self) {
5963 let now = self.frame_index;
5964 let evict_after = self.image_evict_after_frames;
5965
5966 let mut to_evict = Vec::new();
5969 for (h, t) in self.images.iter() {
5970 if !t.evictable() {
5971 continue;
5972 }
5973 let last = match t {
5974 ImageTex::Rgba {
5975 last_used_frame, ..
5976 } => *last_used_frame,
5977 ImageTex::User {
5978 last_used_frame, ..
5979 } => *last_used_frame,
5980 ImageTex::Nv12 {
5981 last_used_frame, ..
5982 } => *last_used_frame,
5983 };
5984 if now.saturating_sub(last) > evict_after {
5985 to_evict.push(*h);
5986 }
5987 }
5988 for h in to_evict {
5989 if self.retained.contains_key(&h) {
5990 self.evict_image_gpu(h);
5991 } else {
5992 self.remove_image(h);
5993 }
5994 }
5995
5996 let mut stale = Vec::new();
5998 for (h, t) in self.coverages.iter() {
5999 if now.saturating_sub(t.last_used_frame) > evict_after {
6000 stale.push(*h);
6001 }
6002 }
6003 for h in stale {
6004 self.remove_coverage(h);
6005 }
6006
6007 self.evict_budget_excess();
6008 }
6009
6010 fn next_cache_touch(&mut self) -> u64 {
6011 let touch = self.cache_touch_clock;
6012 self.cache_touch_clock = self.cache_touch_clock.wrapping_add(1);
6013 touch
6014 }
6015
6016 fn gpu_bytes_total(&self) -> u64 {
6017 self.image_bytes_total
6018 .saturating_add(self.layer_bytes_total)
6019 .saturating_add(self.blend_snapshot_bytes_total)
6020 .saturating_add(self.mesh_cache_bytes_total)
6021 .saturating_add(self.working_space_bytes)
6022 .saturating_add(self.surface_resolve_bytes)
6023 .saturating_add(self.msaa_bytes)
6024 .saturating_add(self.ws_msaa_bytes)
6025 .saturating_add(self.depth_stencil_bytes)
6026 }
6027
6028 fn budget_exceeded(&self) -> bool {
6029 self.image_bytes_total > self.image_budget_bytes
6030 || self.gpu_bytes_total() > self.gpu_budget_bytes
6031 }
6032
6033 fn evict_budget_excess(&mut self) {
6034 let image_over_budget = self.image_bytes_total > self.image_budget_bytes;
6035 let gpu_over_budget = self.gpu_bytes_total() > self.gpu_budget_bytes;
6036 if !image_over_budget && !gpu_over_budget {
6037 return;
6038 }
6039 let mut coverage_candidates: Vec<(u64, u64)> = self
6040 .coverages
6041 .iter()
6042 .map(|(handle, tile)| (*handle, tile.last_used_frame))
6043 .collect();
6044 coverage_candidates.sort_by_key(|candidate| candidate.1);
6045 let now = self.frame_index;
6046 for (handle, last_used) in coverage_candidates {
6047 if !self.budget_exceeded() {
6048 break;
6049 }
6050 if last_used == now {
6051 continue;
6052 }
6053 self.remove_coverage(handle);
6054 }
6055 if !self.budget_exceeded() {
6056 return;
6057 }
6058 let mut candidates: Vec<(u64, u64, u64)> = self
6060 .images
6061 .iter()
6062 .filter_map(|(h, t)| {
6063 if !t.evictable() {
6064 return None;
6065 }
6066 let (last, bytes) = match t {
6067 ImageTex::Rgba {
6068 last_used_frame,
6069 bytes,
6070 ..
6071 } => (*last_used_frame, *bytes),
6072 ImageTex::User {
6073 last_used_frame,
6074 bytes,
6075 ..
6076 } => (*last_used_frame, *bytes),
6077 ImageTex::Nv12 {
6078 last_used_frame,
6079 bytes,
6080 ..
6081 } => (*last_used_frame, *bytes),
6082 };
6083 Some((*h, last, bytes))
6084 })
6085 .collect();
6086
6087 candidates.sort_by_key(|k| k.1);
6089
6090 for (h, last, _bytes) in candidates {
6091 if !self.budget_exceeded() {
6092 break;
6093 }
6094 if last == now {
6095 continue;
6096 }
6097 if self.retained.contains_key(&h) {
6098 self.evict_image_gpu(h);
6099 } else {
6100 self.remove_image(h);
6101 }
6102 }
6103 while self.gpu_bytes_total() > self.gpu_budget_bytes {
6104 if !self.evict_mesh_cache() {
6105 break;
6106 }
6107 }
6108 if self.gpu_bytes_total() > self.gpu_budget_bytes {
6109 log::warn!(
6110 "renderer GPU resource budget exceeded: {} > {}",
6111 self.gpu_bytes_total(),
6112 self.gpu_budget_bytes
6113 );
6114 }
6115 }
6116
6117 pub fn set_pixels_per_point(&mut self, ppp: f32) {
6119 if ppp.is_finite() {
6120 self.pixels_per_point = ppp.clamp(0.5, 8.0);
6121 }
6122 }
6123
6124 pub fn set_working_space(&mut self, enabled: bool) {
6128 if enabled == self.working_space {
6129 return;
6130 }
6131 self.working_space = enabled;
6132 if enabled {
6133 self.ensure_display_pipeline();
6134 self.recreate_msaa_and_depth_stencil();
6135 self.recreate_working_space_texture();
6136 } else {
6137 self.ws_tex = None;
6138 self.ws_view = None;
6139 self.ws_bind = None;
6140 self.ws_msaa_tex = None;
6141 self.ws_msaa_view = None;
6142 self.surface_resolve_tex = None;
6143 self.surface_resolve_view = None;
6144 self.surface_resolve_bytes = 0;
6145 self.working_space_bytes = 0;
6146 self.recreate_msaa_and_depth_stencil();
6147 }
6148 self.evict_budget_excess();
6149 }
6150
6151 fn ensure_display_pipeline(&mut self) {
6152 if self.display_pipeline.is_some() {
6153 return;
6154 }
6155
6156 let layout = self
6157 .device
6158 .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
6159 label: Some("display transform layout"),
6160 entries: &[
6161 wgpu::BindGroupLayoutEntry {
6162 binding: 0,
6163 visibility: wgpu::ShaderStages::FRAGMENT,
6164 ty: wgpu::BindingType::Texture {
6165 multisampled: false,
6166 view_dimension: wgpu::TextureViewDimension::D2,
6167 sample_type: wgpu::TextureSampleType::Float { filterable: true },
6168 },
6169 count: None,
6170 },
6171 wgpu::BindGroupLayoutEntry {
6172 binding: 1,
6173 visibility: wgpu::ShaderStages::FRAGMENT,
6174 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
6175 count: None,
6176 },
6177 ],
6178 });
6179 self.display_layout = Some(layout);
6180
6181 let display_source: Cow<'static, str> = if self.output_format.is_srgb() {
6182 Cow::Borrowed(include_str!("shaders/display_transform_passthrough.wgsl"))
6183 } else {
6184 Cow::Borrowed(include_str!("shaders/display_transform.wgsl"))
6185 };
6186 let shader = self
6187 .device
6188 .create_shader_module(wgpu::ShaderModuleDescriptor {
6189 label: Some("display transform"),
6190 source: wgpu::ShaderSource::Wgsl(display_source),
6191 });
6192
6193 let pipeline_layout = self
6194 .device
6195 .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
6196 label: Some("display transform pipeline layout"),
6197 bind_group_layouts: &[None, self.display_layout.as_ref()],
6198 immediate_size: 0,
6199 });
6200
6201 let pipeline = self
6202 .device
6203 .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
6204 label: Some("display transform pipeline"),
6205 layout: Some(&pipeline_layout),
6206 vertex: wgpu::VertexState {
6207 module: &shader,
6208 entry_point: Some("vs_main"),
6209 buffers: &[],
6210 compilation_options: wgpu::PipelineCompilationOptions::default(),
6211 },
6212 fragment: Some(wgpu::FragmentState {
6213 module: &shader,
6214 entry_point: Some("fs_main"),
6215 targets: &[Some(wgpu::ColorTargetState {
6216 format: self.output_format,
6217 blend: None,
6218 write_mask: wgpu::ColorWrites::ALL,
6219 })],
6220 compilation_options: wgpu::PipelineCompilationOptions::default(),
6221 }),
6222 primitive: wgpu::PrimitiveState::default(),
6223 depth_stencil: None,
6224 multisample: wgpu::MultisampleState::default(),
6225 multiview_mask: None,
6226 cache: None,
6227 });
6228 self.display_pipeline = Some(pipeline);
6229 }
6230
6231 pub fn resize(&mut self, width: u32, height: u32) {
6236 let (width, height) =
6237 clamp_output_size(width, height, self.device.limits().max_texture_dimension_2d);
6238 if self.output_width == width && self.output_height == height {
6239 return;
6240 }
6241 self.output_width = width;
6242 self.output_height = height;
6243 if width == 0 || height == 0 {
6244 self.msaa_tex = None;
6245 self.msaa_view = None;
6246 self.ws_msaa_tex = None;
6247 self.ws_msaa_view = None;
6248 self.surface_resolve_tex = None;
6249 self.surface_resolve_view = None;
6250 self.surface_resolve_bytes = 0;
6251 self.msaa_bytes = 0;
6252 self.ws_msaa_bytes = 0;
6253 self.depth_stencil_bytes = 0;
6254 self.working_space_bytes = 0;
6255 self.ws_tex = None;
6256 self.ws_view = None;
6257 self.ws_bind = None;
6258 self.evict_budget_excess();
6259 return;
6260 }
6261 self.recreate_msaa_and_depth_stencil();
6262 self.recreate_working_space_texture();
6263 self.evict_budget_excess();
6264 }
6265
6266 fn recreate_working_space_texture(&mut self) {
6267 if !self.working_space || self.output_width == 0 || self.output_height == 0 {
6268 return;
6269 }
6270 self.working_space_bytes = 0;
6271 let w = self
6272 .output_width
6273 .clamp(1, self.device.limits().max_texture_dimension_2d);
6274 let h = self
6275 .output_height
6276 .clamp(1, self.device.limits().max_texture_dimension_2d);
6277
6278 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6279 label: Some("working space"),
6280 size: wgpu::Extent3d {
6281 width: w,
6282 height: h,
6283 depth_or_array_layers: 1,
6284 },
6285 mip_level_count: 1,
6286 sample_count: 1,
6287 dimension: wgpu::TextureDimension::D2,
6288 format: wgpu::TextureFormat::Rgba16Float,
6289 usage: wgpu::TextureUsages::RENDER_ATTACHMENT
6290 | wgpu::TextureUsages::TEXTURE_BINDING
6291 | wgpu::TextureUsages::COPY_SRC
6292 | wgpu::TextureUsages::COPY_DST,
6293 view_formats: &[],
6294 });
6295 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
6296
6297 let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
6298 label: Some("working space bind"),
6299 layout: self.display_layout.as_ref().unwrap(),
6300 entries: &[
6301 wgpu::BindGroupEntry {
6302 binding: 0,
6303 resource: wgpu::BindingResource::TextureView(&view),
6304 },
6305 wgpu::BindGroupEntry {
6306 binding: 1,
6307 resource: wgpu::BindingResource::Sampler(&self.image_sampler),
6308 },
6309 ],
6310 });
6311
6312 self.working_space_bytes =
6313 texture_storage_bytes(wgpu::TextureFormat::Rgba16Float, w, h).unwrap_or(0);
6314 self.ws_tex = Some(tex);
6315 self.ws_view = Some(view);
6316 self.ws_bind = Some(bind);
6317 }
6318
6319 fn recreate_msaa_and_depth_stencil(&mut self) {
6320 if self.output_width == 0 || self.output_height == 0 {
6321 self.msaa_tex = None;
6322 self.msaa_view = None;
6323 self.ws_msaa_tex = None;
6324 self.ws_msaa_view = None;
6325 self.surface_resolve_tex = None;
6326 self.surface_resolve_view = None;
6327 self.surface_resolve_bytes = 0;
6328 self.msaa_bytes = 0;
6329 self.ws_msaa_bytes = 0;
6330 self.depth_stencil_bytes = 0;
6331 return;
6332 }
6333 self.msaa_bytes = 0;
6334 self.ws_msaa_bytes = 0;
6335 self.depth_stencil_bytes = 0;
6336 let aliased_surface = self.surface_format != self.output_format;
6337 let view_format_list = [self.output_format];
6338 let surface_view_formats: &[wgpu::TextureFormat] = if aliased_surface {
6339 &view_format_list
6340 } else {
6341 &[]
6342 };
6343 let surface_view = if aliased_surface {
6344 wgpu::TextureViewDescriptor {
6345 format: Some(self.output_format),
6346 ..Default::default()
6347 }
6348 } else {
6349 wgpu::TextureViewDescriptor::default()
6350 };
6351 if self.msaa_samples > 1 && !self.working_space {
6352 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6353 label: Some("msaa color"),
6354 size: wgpu::Extent3d {
6355 width: self.output_width.max(1),
6356 height: self.output_height.max(1),
6357 depth_or_array_layers: 1,
6358 },
6359 mip_level_count: 1,
6360 sample_count: self.msaa_samples,
6361 dimension: wgpu::TextureDimension::D2,
6362 format: self.surface_format,
6363 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
6364 view_formats: surface_view_formats,
6365 });
6366 let view = tex.create_view(&surface_view);
6367 self.msaa_bytes = texture_storage_bytes_with_samples(
6368 self.surface_format,
6369 self.output_width.max(1),
6370 self.output_height.max(1),
6371 self.msaa_samples,
6372 )
6373 .unwrap_or(0);
6374 self.msaa_tex = Some(tex);
6375 self.msaa_view = Some(view);
6376 } else {
6377 self.msaa_tex = None;
6378 self.msaa_view = None;
6379 }
6380 if self.working_space && self.working_space_msaa_samples > 1 {
6381 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6382 label: Some("working space msaa color"),
6383 size: wgpu::Extent3d {
6384 width: self.output_width.max(1),
6385 height: self.output_height.max(1),
6386 depth_or_array_layers: 1,
6387 },
6388 mip_level_count: 1,
6389 sample_count: self.working_space_msaa_samples,
6390 dimension: wgpu::TextureDimension::D2,
6391 format: wgpu::TextureFormat::Rgba16Float,
6392 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
6393 view_formats: &[],
6394 });
6395 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
6396 self.ws_msaa_bytes = texture_storage_bytes_with_samples(
6397 wgpu::TextureFormat::Rgba16Float,
6398 self.output_width.max(1),
6399 self.output_height.max(1),
6400 self.working_space_msaa_samples,
6401 )
6402 .unwrap_or(0);
6403 self.ws_msaa_tex = Some(tex);
6404 self.ws_msaa_view = Some(view);
6405 } else {
6406 self.ws_msaa_tex = None;
6407 self.ws_msaa_view = None;
6408 }
6409 self.surface_resolve_tex = None;
6410 self.surface_resolve_view = None;
6411 self.surface_resolve_bytes = 0;
6412 if self.msaa_samples > 1 && !self.working_space {
6413 let width = self.output_width.max(1);
6414 let height = self.output_height.max(1);
6415 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6416 label: Some("surface resolve"),
6417 size: wgpu::Extent3d {
6418 width,
6419 height,
6420 depth_or_array_layers: 1,
6421 },
6422 mip_level_count: 1,
6423 sample_count: 1,
6424 dimension: wgpu::TextureDimension::D2,
6425 format: self.surface_format,
6426 usage: wgpu::TextureUsages::RENDER_ATTACHMENT
6427 | wgpu::TextureUsages::TEXTURE_BINDING
6428 | wgpu::TextureUsages::COPY_SRC,
6429 view_formats: surface_view_formats,
6430 });
6431 let view = tex.create_view(&surface_view);
6432 self.surface_resolve_bytes =
6433 texture_storage_bytes(self.surface_format, width, height).unwrap_or(0);
6434 self.surface_resolve_tex = Some(tex);
6435 self.surface_resolve_view = Some(view);
6436 }
6437
6438 self.depth_stencil_bytes = texture_storage_bytes_with_samples(
6439 wgpu::TextureFormat::Depth24PlusStencil8,
6440 self.output_width.max(1),
6441 self.output_height.max(1),
6442 self.active_surface_msaa_samples(),
6443 )
6444 .unwrap_or(0);
6445 self.depth_stencil_tex = self.device.create_texture(&wgpu::TextureDescriptor {
6446 label: Some("depth-stencil (stencil clips)"),
6447 size: wgpu::Extent3d {
6448 width: self.output_width.max(1),
6449 height: self.output_height.max(1),
6450 depth_or_array_layers: 1,
6451 },
6452 mip_level_count: 1,
6453 sample_count: self.active_surface_msaa_samples(),
6454 dimension: wgpu::TextureDimension::D2,
6455 format: wgpu::TextureFormat::Depth24PlusStencil8,
6456 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
6457 view_formats: &[],
6458 });
6459 self.depth_stencil_view = self
6460 .depth_stencil_tex
6461 .create_view(&wgpu::TextureViewDescriptor::default());
6462 }
6463
6464 fn active_surface_msaa_samples(&self) -> u32 {
6465 if self.working_space {
6466 self.working_space_msaa_samples
6467 } else {
6468 self.msaa_samples
6469 }
6470 }
6471
6472 fn layer_target_format(&self) -> wgpu::TextureFormat {
6473 if self.working_space {
6474 wgpu::TextureFormat::Rgba16Float
6475 } else {
6476 self.output_format
6477 }
6478 }
6479
6480 fn get_or_create_layer(
6481 &mut self,
6482 layer_id: u32,
6483 width: u32,
6484 height: u32,
6485 rect: repose_core::Rect,
6486 transient: bool,
6487 ) -> bool {
6488 if width == 0
6489 || height == 0
6490 || width > self.device.limits().max_texture_dimension_2d
6491 || height > self.device.limits().max_texture_dimension_2d
6492 {
6493 return false;
6494 }
6495 let needs_alloc = match self.layer_pool.get(&layer_id) {
6496 Some(lt) => {
6497 lt.width != width || lt.height != height || lt.format != self.layer_target_format()
6498 }
6499 None => true,
6500 };
6501 if !needs_alloc {
6502 if let Some(lt) = self.layer_pool.get_mut(&layer_id) {
6503 lt.rect_px = (rect.x, rect.y, rect.w, rect.h);
6504 }
6505 return true;
6506 }
6507 let color_bytes =
6508 texture_storage_bytes(self.layer_target_format(), width.max(1), height.max(1))
6509 .unwrap_or(MAX_GRAPHICS_LAYER_BYTES + 1);
6510 let depth_bytes = checked_image_bytes(width.max(1), height.max(1), 4)
6511 .unwrap_or(MAX_GRAPHICS_LAYER_BYTES + 1);
6512 let bytes = color_bytes.saturating_add(depth_bytes);
6513 let old = self.layer_pool.get(&layer_id);
6514 let old_bytes = old.map_or(0, |layer| layer.bytes);
6515 let old_transient_bytes =
6516 old.map_or(0, |layer| if layer.transient { layer.bytes } else { 0 });
6517 let transient_count = self
6518 .layer_pool
6519 .values()
6520 .filter(|layer| layer.transient)
6521 .count();
6522 let transient_count = transient_count
6523 .saturating_sub(usize::from(old.is_some_and(|layer| layer.transient)))
6524 .saturating_add(usize::from(transient));
6525 let count = self.layer_pool.len() + usize::from(!self.layer_pool.contains_key(&layer_id));
6526 let total = self
6527 .layer_bytes_total
6528 .saturating_sub(old_bytes)
6529 .saturating_add(bytes);
6530 let projected_gpu = self
6531 .gpu_bytes_total()
6532 .saturating_sub(old_bytes)
6533 .saturating_add(bytes);
6534 let projected_transient = self
6535 .transient_layer_bytes_total
6536 .saturating_sub(old_transient_bytes)
6537 .saturating_add(if transient { bytes } else { 0 });
6538 if count > MAX_GRAPHICS_LAYERS
6539 || (transient
6540 && (transient_count > MAX_TRANSIENT_GRAPHICS_LAYERS
6541 || projected_transient > MAX_TRANSIENT_GRAPHICS_LAYER_BYTES))
6542 || bytes > MAX_GRAPHICS_LAYER_BYTES
6543 || total > MAX_GRAPHICS_LAYER_BYTES
6544 || projected_gpu > self.gpu_budget_bytes
6545 {
6546 log::warn!("graphics layer budget exhausted; layer {layer_id} skipped");
6547 if let Some(old) = self.layer_pool.remove(&layer_id) {
6548 self.layer_bytes_total = self.layer_bytes_total.saturating_sub(old.bytes);
6549 if old.transient {
6550 self.transient_layer_bytes_total =
6551 self.transient_layer_bytes_total.saturating_sub(old.bytes);
6552 }
6553 }
6554 return false;
6555 }
6556 if let Some(old) = self.layer_pool.remove(&layer_id) {
6557 self.layer_bytes_total = self.layer_bytes_total.saturating_sub(old.bytes);
6558 if old.transient {
6559 self.transient_layer_bytes_total =
6560 self.transient_layer_bytes_total.saturating_sub(old.bytes);
6561 }
6562 }
6563 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6564 label: Some("graphics layer"),
6565 size: wgpu::Extent3d {
6566 width: width.max(1),
6567 height: height.max(1),
6568 depth_or_array_layers: 1,
6569 },
6570 mip_level_count: 1,
6571 sample_count: 1,
6572 dimension: wgpu::TextureDimension::D2,
6573 format: self.layer_target_format(),
6574 usage: wgpu::TextureUsages::RENDER_ATTACHMENT
6575 | wgpu::TextureUsages::TEXTURE_BINDING
6576 | wgpu::TextureUsages::COPY_SRC,
6577 view_formats: &[],
6578 });
6579 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
6580 let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
6581 label: Some("layer bind"),
6582 layout: &self.image_bind_layout_rgba,
6583 entries: &[
6584 wgpu::BindGroupEntry {
6585 binding: 0,
6586 resource: wgpu::BindingResource::TextureView(&view),
6587 },
6588 wgpu::BindGroupEntry {
6589 binding: 1,
6590 resource: wgpu::BindingResource::Sampler(&self.layer_sampler),
6591 },
6592 ],
6593 });
6594 let bind_linear = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
6595 label: Some("layer bind linear"),
6596 layout: &self.image_bind_layout_rgba,
6597 entries: &[
6598 wgpu::BindGroupEntry {
6599 binding: 0,
6600 resource: wgpu::BindingResource::TextureView(&view),
6601 },
6602 wgpu::BindGroupEntry {
6603 binding: 1,
6604 resource: wgpu::BindingResource::Sampler(&self.layer_sampler_linear),
6605 },
6606 ],
6607 });
6608 let depth_stencil_view = self.create_layer_depth_stencil(width, height);
6609 self.layer_pool.insert(
6610 layer_id,
6611 LayerTarget {
6612 texture: tex,
6613 view,
6614 bind,
6615 bind_linear,
6616 depth_stencil_view,
6617 width,
6618 height,
6619 format: self.layer_target_format(),
6620 bytes,
6621 rect_px: (rect.x, rect.y, rect.w, rect.h),
6622 transient,
6623 },
6624 );
6625 self.layer_bytes_total = self.layer_bytes_total.saturating_add(bytes);
6626 if transient {
6627 self.transient_layer_bytes_total =
6628 self.transient_layer_bytes_total.saturating_add(bytes);
6629 }
6630 true
6631 }
6632
6633 fn acquire_blur_scratch(&mut self, layer_id: u32, slot: u32, pad: (f32, f32)) -> Option<u32> {
6643 let src = self.layer_pool.get(&layer_id)?;
6644 let width_f = (src.width as f32 + pad.0 * 2.0).ceil();
6645 let height_f = (src.height as f32 + pad.1 * 2.0).ceil();
6646 let max_dim = self.device.limits().max_texture_dimension_2d as f32;
6647 if !width_f.is_finite()
6648 || !height_f.is_finite()
6649 || width_f < 1.0
6650 || height_f < 1.0
6651 || width_f > max_dim
6652 || height_f > max_dim
6653 {
6654 log::warn!("blur scratch size {width_f}x{height_f} is invalid");
6655 return None;
6656 }
6657 let next = self.blur_scratch_next;
6658 let scratch_id = match self.blur_scratch_ids.get(&(layer_id, slot)) {
6659 Some(&id) => id,
6660 None => {
6661 let id = BLUR_SCRATCH_ID_BASE.wrapping_add(next);
6662 self.blur_scratch_next = next.wrapping_add(1);
6663 self.blur_scratch_ids.insert((layer_id, slot), id);
6664 id
6665 }
6666 };
6667 let allocated = self.get_or_create_layer(
6668 scratch_id,
6669 width_f as u32,
6670 height_f as u32,
6671 repose_core::Rect {
6672 x: 0.0,
6673 y: 0.0,
6674 w: width_f,
6675 h: height_f,
6676 },
6677 true,
6678 );
6679 allocated.then_some(scratch_id)
6680 }
6681
6682 #[allow(clippy::too_many_arguments)]
6701 fn emit_separable_blur(
6702 &mut self,
6703 source_layer: u32,
6704 slot: u32,
6705 sigma: [f32; 2],
6706 pad: (f32, f32),
6707 spread: (f32, f32),
6708 edge_mode: u32,
6709 alpha_only: bool,
6710 shape: [f32; 4],
6711 passes: &mut Vec<Pass>,
6712 current_pass: &mut Pass,
6713 next_pass_id: &mut u64,
6714 encoder: &mut wgpu::CommandEncoder,
6715 ) -> Option<u32> {
6716 let (source_w, source_h) = {
6717 let source = self.layer_pool.get(&source_layer)?;
6718 (source.width as f32, source.height as f32)
6719 };
6720 let spread_x = spread.0.max(-pad.0).max((1.0 - source_w) * 0.5);
6725 let spread_y = spread.1.max(-pad.1).max((1.0 - source_h) * 0.5);
6726 let expanded_w = (source_w + 2.0 * spread_x).max(1.0);
6727 let expanded_h = (source_h + 2.0 * spread_y).max(1.0);
6728 let alloc_pad = (pad.0 + spread_x, pad.1 + spread_y);
6729 let scratch_id = self.acquire_blur_scratch(source_layer, slot, alloc_pad)?;
6730 let (scratch_w, scratch_h) = {
6731 let scratch = self.layer_pool.get(&scratch_id)?;
6732 (scratch.width, scratch.height)
6733 };
6734 let uv = [
6738 -pad.0 / expanded_w,
6739 -pad.1 / expanded_h,
6740 1.0 + pad.0 / expanded_w,
6741 1.0 + pad.1 / expanded_h,
6742 ];
6743 let ndc = [-1.0, -1.0, 2.0, 2.0];
6744 let inst = BlurInstance {
6745 xywh: [ndc[0] + ndc[2] * 0.5, ndc[1] + ndc[3] * 0.5, ndc[2], ndc[3]],
6746 uv,
6747 color: [1.0, 1.0, 1.0, 1.0],
6748 sigma_px: [
6749 sigma[0] * source_w / expanded_w,
6750 sigma[1] * source_h / expanded_h,
6751 ],
6752 fwd_mat: [1.0, 0.0, 0.0, 1.0],
6753 axis: 0,
6754 edge_mode,
6755 shape,
6756 };
6757 let cmd = match self.upload_blur_instance(&inst, encoder) {
6758 Some(off) if alpha_only => Cmd::CompositeShadow {
6759 off,
6760 cnt: 1,
6761 layer_id: source_layer,
6762 spread_px: 0.0,
6763 inset: false,
6764 },
6765 Some(off) => Cmd::CompositeBlur {
6766 off,
6767 cnt: 1,
6768 layer_id: source_layer,
6769 blend: BlendMode::Alpha,
6770 },
6771 None => return None,
6772 };
6773 let target = current_pass.target;
6774 let scissor = current_pass.active_scissor;
6775 let resumed_pass_id = *next_pass_id;
6776 *next_pass_id += 1;
6777 let saved = std::mem::replace(
6778 current_pass,
6779 Pass {
6780 id: resumed_pass_id,
6781 target,
6782 initial_scissor: scissor.unwrap_or((0, 0, 1, 1)),
6783 active_scissor: scissor,
6784 clear_color: None,
6785 cmds: Vec::new(),
6786 },
6787 );
6788 passes.push(saved);
6789 let scratch_pass_id = *next_pass_id;
6790 *next_pass_id += 1;
6791 passes.push(Pass {
6792 id: scratch_pass_id,
6793 target: PassTarget::Layer(scratch_id),
6794 initial_scissor: (0, 0, scratch_w, scratch_h),
6795 active_scissor: Some((0, 0, scratch_w, scratch_h)),
6796 clear_color: Some([0.0, 0.0, 0.0, 0.0]),
6797 cmds: vec![cmd],
6798 });
6799 Some(scratch_id)
6800 }
6801
6802 fn upload_blur_instance(
6803 &mut self,
6804 inst: &BlurInstance,
6805 encoder: &mut wgpu::CommandEncoder,
6806 ) -> Option<u64> {
6807 self.blur_ring
6808 .grow_to_fit(
6809 &self.device,
6810 encoder,
6811 std::mem::size_of::<BlurInstance>() as u64,
6812 )
6813 .ok()?;
6814 self.blur_ring
6815 .alloc_write(&self.queue, bytemuck::bytes_of(inst))
6816 .ok()
6817 }
6818 fn create_layer_depth_stencil(&self, width: u32, height: u32) -> wgpu::TextureView {
6819 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6820 label: Some("layer depth-stencil"),
6821 size: wgpu::Extent3d {
6822 width: width.max(1),
6823 height: height.max(1),
6824 depth_or_array_layers: 1,
6825 },
6826 mip_level_count: 1,
6827 sample_count: 1,
6828 dimension: wgpu::TextureDimension::D2,
6829 format: wgpu::TextureFormat::Depth24PlusStencil8,
6830 usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
6831 view_formats: &[],
6832 });
6833 tex.create_view(&wgpu::TextureViewDescriptor::default())
6834 }
6835
6836 fn ensure_globals_staging(&mut self, pass_count: usize) -> bool {
6837 let size = std::mem::size_of::<Globals>() as u64;
6838 let needed = match (pass_count.max(1) as u64).checked_mul(size) {
6839 Some(needed) => needed,
6840 None => return false,
6841 };
6842 if needed <= self.globals_staging_cap {
6843 return true;
6844 }
6845 let cap = needed
6846 .next_power_of_two()
6847 .min(self.device.limits().max_buffer_size);
6848 if cap < needed {
6849 return false;
6850 }
6851 self.globals_staging = self.device.create_buffer(&wgpu::BufferDescriptor {
6852 label: Some("globals staging"),
6853 size: cap,
6854 usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
6855 mapped_at_creation: false,
6856 });
6857 self.globals_staging_cap = cap;
6858 true
6859 }
6860
6861 fn reset_atlas_storage(&mut self) {
6862 self.atlas_mask = init_atlas_mask(&self.device);
6863 self.atlas_color = init_atlas_color(&self.device);
6864 self.atlas_mask_bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
6865 label: Some("atlas mask bind"),
6866 layout: &self.text_bind_layout,
6867 entries: &[
6868 wgpu::BindGroupEntry {
6869 binding: 0,
6870 resource: wgpu::BindingResource::TextureView(&self.atlas_mask.view),
6871 },
6872 wgpu::BindGroupEntry {
6873 binding: 1,
6874 resource: wgpu::BindingResource::Sampler(&self.atlas_mask.sampler),
6875 },
6876 ],
6877 });
6878 self.atlas_color_bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
6879 label: Some("atlas color bind"),
6880 layout: &self.text_bind_layout,
6881 entries: &[
6882 wgpu::BindGroupEntry {
6883 binding: 0,
6884 resource: wgpu::BindingResource::TextureView(&self.atlas_color.view),
6885 },
6886 wgpu::BindGroupEntry {
6887 binding: 1,
6888 resource: wgpu::BindingResource::Sampler(&self.atlas_color.sampler),
6889 },
6890 ],
6891 });
6892 self.atlas_mask_pending = AtlasPending::default();
6893 self.atlas_color_pending = AtlasPending::default();
6894 self.atlas_mask_deferred.clear();
6895 self.atlas_color_deferred.clear();
6896 }
6897
6898 fn apply_atlas_pending(&mut self) {
6903 if self.atlas_mask_pending.grow {
6904 self.atlas_mask_pending.grow = false;
6905 let size = (self.atlas_mask.size * 2).min(MAX_GLYPH_ATLAS_SIZE);
6906 self.repack_mask(size);
6907 }
6908 if self.atlas_color_pending.grow {
6909 self.atlas_color_pending.grow = false;
6910 let size = (self.atlas_color.size * 2).min(MAX_GLYPH_ATLAS_SIZE);
6911 self.repack_color(size);
6912 }
6913 if self.frame_index.wrapping_sub(self.atlas_last_compact_frame)
6914 < ATLAS_COMPACT_MIN_FRAME_INTERVAL
6915 {
6916 return;
6917 }
6918 if self.atlas_mask_pending.compact && self.compact_atlas_mask() {
6921 self.atlas_mask_pending.compact = false;
6922 }
6923 if self.atlas_color_pending.compact && self.compact_atlas_color() {
6924 self.atlas_color_pending.compact = false;
6925 }
6926 }
6927
6928 fn compact_atlas_mask(&mut self) -> bool {
6933 let target = self.atlas_mask.used_area / ATLAS_COMPACT_KEEP_DEN * ATLAS_COMPACT_KEEP_NUM;
6934 if !evict_atlas_lru(
6935 &mut self.atlas_mask.map,
6936 &mut self.atlas_mask.used_area,
6937 self.frame_index,
6938 target,
6939 ) {
6940 return false;
6941 }
6942 let size = self.atlas_mask.size;
6943 self.repack_mask(size);
6944 self.atlas_last_compact_frame = self.frame_index;
6945 true
6946 }
6947
6948 fn compact_atlas_color(&mut self) -> bool {
6949 let target = self.atlas_color.used_area / ATLAS_COMPACT_KEEP_DEN * ATLAS_COMPACT_KEEP_NUM;
6950 if !evict_atlas_lru(
6951 &mut self.atlas_color.map,
6952 &mut self.atlas_color.used_area,
6953 self.frame_index,
6954 target,
6955 ) {
6956 return false;
6957 }
6958 let size = self.atlas_color.size;
6959 self.repack_color(size);
6960 self.atlas_last_compact_frame = self.frame_index;
6961 true
6962 }
6963
6964 fn repack_mask(&mut self, new_size: u32) {
6968 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
6969 label: Some("glyph atlas A8 (repacked)"),
6970 size: wgpu::Extent3d {
6971 width: new_size,
6972 height: new_size,
6973 depth_or_array_layers: 1,
6974 },
6975 mip_level_count: 1,
6976 sample_count: 1,
6977 dimension: wgpu::TextureDimension::D2,
6978 format: wgpu::TextureFormat::R8Unorm,
6979 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
6980 view_formats: &[],
6981 });
6982 self.atlas_mask.tex = tex;
6983 self.atlas_mask.view = self
6984 .atlas_mask
6985 .tex
6986 .create_view(&wgpu::TextureViewDescriptor::default());
6987 self.atlas_mask.size = new_size;
6988 self.atlas_mask.next_x = 1;
6989 self.atlas_mask.next_y = 1;
6990 self.atlas_mask.row_h = 0;
6991 self.atlas_mask.used_area = 0;
6992 self.atlas_mask_bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
6993 label: Some("atlas mask bind"),
6994 layout: &self.text_bind_layout,
6995 entries: &[
6996 wgpu::BindGroupEntry {
6997 binding: 0,
6998 resource: wgpu::BindingResource::TextureView(&self.atlas_mask.view),
6999 },
7000 wgpu::BindGroupEntry {
7001 binding: 1,
7002 resource: wgpu::BindingResource::Sampler(&self.atlas_mask.sampler),
7003 },
7004 ],
7005 });
7006 let survivors: Vec<_> = self.atlas_mask.map.drain().collect();
7007 self.atlas_mask_deferred.clear();
7008 for (key, previous) in survivors {
7009 let _ = self.upload_glyph_mask(key.clone(), f32::from_bits(key.font_size_bits));
7010 if let Some(info) = self.atlas_mask.map.get_mut(&key) {
7011 info.last_touch = previous.last_touch;
7012 info.last_used_frame = previous.last_used_frame;
7013 }
7014 }
7015 }
7016
7017 fn repack_color(&mut self, new_size: u32) {
7019 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
7020 label: Some("glyph atlas RGBA (repacked)"),
7021 size: wgpu::Extent3d {
7022 width: new_size,
7023 height: new_size,
7024 depth_or_array_layers: 1,
7025 },
7026 mip_level_count: 1,
7027 sample_count: 1,
7028 dimension: wgpu::TextureDimension::D2,
7029 format: wgpu::TextureFormat::Rgba8UnormSrgb,
7030 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
7031 view_formats: &[],
7032 });
7033 self.atlas_color.tex = tex;
7034 self.atlas_color.view = self
7035 .atlas_color
7036 .tex
7037 .create_view(&wgpu::TextureViewDescriptor::default());
7038 self.atlas_color.size = new_size;
7039 self.atlas_color.next_x = 1;
7040 self.atlas_color.next_y = 1;
7041 self.atlas_color.row_h = 0;
7042 self.atlas_color.used_area = 0;
7043 self.atlas_color_bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
7044 label: Some("atlas color bind"),
7045 layout: &self.text_bind_layout,
7046 entries: &[
7047 wgpu::BindGroupEntry {
7048 binding: 0,
7049 resource: wgpu::BindingResource::TextureView(&self.atlas_color.view),
7050 },
7051 wgpu::BindGroupEntry {
7052 binding: 1,
7053 resource: wgpu::BindingResource::Sampler(&self.atlas_color.sampler),
7054 },
7055 ],
7056 });
7057 let survivors: Vec<_> = self.atlas_color.map.drain().collect();
7058 self.atlas_color_deferred.clear();
7059 for (key, previous) in survivors {
7060 let _ = self.upload_glyph_color(key.clone(), f32::from_bits(key.font_size_bits));
7061 if let Some(info) = self.atlas_color.map.get_mut(&key) {
7062 info.last_touch = previous.last_touch;
7063 info.last_used_frame = previous.last_used_frame;
7064 }
7065 }
7066 }
7067
7068 fn sync_text_caches(&mut self) {
7069 let generation = repose_text::font_generation();
7070 if generation == self.atlas_generation {
7071 return;
7072 }
7073 self.atlas_generation = generation;
7074 self.reset_atlas_storage();
7075 self.atlas_mask_failures.clear();
7076 self.atlas_color_failures.clear();
7077 self.glyph_outline_cache.clear();
7078 self.legacy_shaped_text_cache.clear();
7079 self.slug_draw_cache.clear();
7080 self.slug_draw_cache_bytes_total = 0;
7081 self.slug_cache = slug::GlyphSlugCache::new();
7082 }
7083
7084 fn shape_text_cached(
7085 &mut self,
7086 text: &Arc<str>,
7087 px: f32,
7088 line_height_ratio: f32,
7089 font_family: Option<&'static str>,
7090 font_weight: u16,
7091 font_style: u8,
7092 letter_spacing: f32,
7093 variation: Option<&Arc<str>>,
7094 ) -> Arc<repose_text::SharedShapedText> {
7095 repose_text::shape_line_cached(
7096 text.as_ref(),
7097 px,
7098 line_height_ratio,
7099 font_family,
7100 font_weight,
7101 font_style,
7102 letter_spacing,
7103 variation.map(AsRef::as_ref),
7104 )
7105 }
7106
7107 fn legacy_shape_text_cached(
7108 &mut self,
7109 text: &Arc<str>,
7110 px: f32,
7111 line_height_ratio: f32,
7112 font_family: Option<&'static str>,
7113 font_weight: u16,
7114 font_style: u8,
7115 letter_spacing: f32,
7116 variation: Option<&Arc<str>>,
7117 ) -> Arc<[repose_text::ShapedGlyph]> {
7118 let key = TextShapeKey {
7119 text: text.clone(),
7120 px_bits: px.to_bits(),
7121 line_height_bits: line_height_ratio.to_bits(),
7122 font_family,
7123 font_weight,
7124 font_style,
7125 letter_spacing_bits: letter_spacing.to_bits(),
7126 variation: variation.cloned(),
7127 font_generation: self.atlas_generation,
7128 };
7129 if let Some(entry) = self.legacy_shaped_text_cache.get_mut(&key) {
7130 entry.last_used_frame = self.frame_index;
7131 return entry.glyphs.clone();
7132 }
7133 let glyphs: Arc<[repose_text::ShapedGlyph]> = Arc::from(repose_text::shape_line(
7134 text.as_ref(),
7135 px,
7136 line_height_ratio,
7137 font_family,
7138 font_weight,
7139 font_style,
7140 letter_spacing,
7141 variation.map(AsRef::as_ref),
7142 ));
7143 self.legacy_shaped_text_cache.insert(
7144 key,
7145 TextShapeCacheEntry {
7146 glyphs: glyphs.clone(),
7147 last_used_frame: self.frame_index,
7148 },
7149 );
7150 while self.legacy_shaped_text_cache.len() > MAX_LEGACY_SHAPED_TEXT_CACHE_ENTRIES {
7151 let Some(victim) = self
7152 .legacy_shaped_text_cache
7153 .iter()
7154 .min_by_key(|(_, entry)| entry.last_used_frame)
7155 .map(|(key, _)| key.clone())
7156 else {
7157 break;
7158 };
7159 self.legacy_shaped_text_cache.remove(&victim);
7160 }
7161 glyphs
7162 }
7163
7164 fn slug_draw_key(
7165 cache_key: &repose_text::CacheKey,
7166 fill: bool,
7167 stroke_key: Option<&slug::StrokeTessKey>,
7168 transform: &Transform,
7169 origin: (f32, f32),
7170 px: f32,
7171 target: (f32, f32),
7172 color: [f32; 4],
7173 ) -> SlugDrawKey {
7174 let linear = transform.linear();
7175 SlugDrawKey {
7176 cache_key: cache_key.clone(),
7177 fill,
7178 stroke: stroke_key.cloned(),
7179 transform: [
7180 linear[0].to_bits(),
7181 linear[1].to_bits(),
7182 linear[2].to_bits(),
7183 linear[3].to_bits(),
7184 transform.scale_x.to_bits(),
7185 transform.scale_y.to_bits(),
7186 transform.translate_x.to_bits(),
7187 transform.translate_y.to_bits(),
7188 transform.rotate.to_bits(),
7189 transform.shear_x.to_bits(),
7190 transform.shear_y.to_bits(),
7191 ],
7192 origin: [origin.0.to_bits(), origin.1.to_bits()],
7193 px_bits: px.to_bits(),
7194 target: [target.0.to_bits(), target.1.to_bits()],
7195 color: color.map(f32::to_bits),
7196 }
7197 }
7198
7199 fn evict_slug_draw_cache(&mut self) -> bool {
7200 let victim = self
7201 .slug_draw_cache
7202 .iter()
7203 .filter(|(_, entry)| entry.last_used_frame != self.frame_index)
7204 .min_by_key(|(_, entry)| entry.last_touch_frame)
7205 .map(|(key, _)| key.clone());
7206 let Some(victim) = victim else {
7207 return false;
7208 };
7209 let Some(entry) = self.slug_draw_cache.remove(&victim) else {
7210 return false;
7211 };
7212 self.slug_draw_cache_bytes_total =
7213 self.slug_draw_cache_bytes_total.saturating_sub(entry.bytes);
7214 true
7215 }
7216
7217 fn reserve_slug_draw_cache(&mut self, bytes: u64) -> bool {
7218 while self.slug_draw_cache.len() >= MAX_SLUG_DRAW_CACHE_ENTRIES
7219 || self.slug_draw_cache_bytes_total.saturating_add(bytes) > MAX_SLUG_DRAW_CACHE_BYTES
7220 {
7221 if !self.evict_slug_draw_cache() {
7222 return false;
7223 }
7224 }
7225 true
7226 }
7227
7228 fn get_cached_slug_vertices(&mut self, key: &SlugDrawKey) -> Option<Arc<[slug::TessVertex]>> {
7229 let touch = self.next_cache_touch();
7230 self.slug_draw_cache.get_mut(key).map(|entry| {
7231 entry.last_used_frame = self.frame_index;
7232 entry.last_touch_frame = touch;
7233 entry.vertices.clone()
7234 })
7235 }
7236
7237 fn cached_slug_vertices(
7238 &mut self,
7239 key: SlugDrawKey,
7240 vertices: Vec<slug::TessVertex>,
7241 ) -> Arc<[slug::TessVertex]> {
7242 let touch = self.next_cache_touch();
7243 if let Some(entry) = self.slug_draw_cache.get_mut(&key) {
7244 entry.last_used_frame = self.frame_index;
7245 entry.last_touch_frame = touch;
7246 return entry.vertices.clone();
7247 }
7248 let bytes = slug_draw_cache_entry_bytes(vertices.len());
7249 if bytes > MAX_SLUG_DRAW_CACHE_BYTES || !self.reserve_slug_draw_cache(bytes) {
7250 return Arc::from(vertices);
7251 }
7252 let touch = self.next_cache_touch();
7253 let vertices: Arc<[slug::TessVertex]> = Arc::from(vertices);
7254 self.slug_draw_cache.insert(
7255 key,
7256 SlugDrawCacheEntry {
7257 vertices: vertices.clone(),
7258 bytes,
7259 last_used_frame: self.frame_index,
7260 last_touch_frame: touch,
7261 },
7262 );
7263 self.slug_draw_cache_bytes_total = self.slug_draw_cache_bytes_total.saturating_add(bytes);
7264 vertices
7265 }
7266
7267 fn cached_glyph_outline(
7268 &mut self,
7269 cache_key: &repose_text::CacheKey,
7270 ) -> Option<Arc<[repose_text::Command]>> {
7271 let touch = self.next_cache_touch();
7272 if let Some(entry) = self.glyph_outline_cache.get_mut(cache_key) {
7273 entry.last_touch = touch;
7274 return entry.commands.clone();
7275 }
7276 let commands = repose_text::extract_outline_commands(cache_key).map(Arc::from);
7277 if self.glyph_outline_cache.len() >= MAX_GLYPH_OUTLINE_CACHE_ENTRIES {
7278 self.trim_glyph_outline_cache();
7279 }
7280 self.glyph_outline_cache.insert(
7281 cache_key.clone(),
7282 GlyphOutlineEntry {
7283 commands: commands.clone(),
7284 last_touch: touch,
7285 },
7286 );
7287 commands
7288 }
7289
7290 fn trim_glyph_outline_cache(&mut self) {
7293 let target = (MAX_GLYPH_OUTLINE_CACHE_ENTRIES / ATLAS_COMPACT_KEEP_DEN as usize)
7294 * ATLAS_COMPACT_KEEP_NUM as usize;
7295 let mut victims: Vec<(u64, repose_text::CacheKey)> = self
7296 .glyph_outline_cache
7297 .iter()
7298 .map(|(key, entry)| (entry.last_touch, key.clone()))
7299 .collect();
7300 victims.sort_unstable_by_key(|victim| victim.0);
7301 for (_, key) in victims {
7302 if self.glyph_outline_cache.len() <= target {
7303 break;
7304 }
7305 self.glyph_outline_cache.remove(&key);
7306 }
7307 }
7308
7309 fn atlas_bind_group_mask(&self) -> wgpu::BindGroup {
7310 self.atlas_mask_bind.clone()
7311 }
7312
7313 fn atlas_bind_group_color(&self) -> wgpu::BindGroup {
7314 self.atlas_color_bind.clone()
7315 }
7316
7317 fn mark_atlas_mask_failure(&mut self, key: repose_text::CacheKey) {
7318 if self.atlas_mask_failures.len() >= MAX_GLYPH_ATLAS_ENTRIES {
7319 self.atlas_mask_failures.clear();
7320 }
7321 self.atlas_mask_failures.insert(key);
7322 }
7323
7324 fn mark_atlas_color_failure(&mut self, key: repose_text::CacheKey) {
7325 if self.atlas_color_failures.len() >= MAX_GLYPH_ATLAS_ENTRIES {
7326 self.atlas_color_failures.clear();
7327 }
7328 self.atlas_color_failures.insert(key);
7329 }
7330
7331 fn upload_glyph_mask(
7332 &mut self,
7333 cache_key: repose_text::CacheKey,
7334 px: f32,
7335 ) -> Option<GlyphInfo> {
7336 let px = quantize_glyph_px(px);
7337 let keyp = repose_text::CacheKey {
7338 font_size_bits: px.to_bits(),
7339 ..cache_key
7340 };
7341 let touch = self.next_cache_touch();
7342 if let Some(info) = self.atlas_mask.map.get_mut(&keyp) {
7343 info.last_touch = touch;
7344 info.last_used_frame = self.frame_index;
7345 return Some(*info);
7346 }
7347 if self.atlas_mask_failures.contains(&keyp) || self.atlas_mask_deferred.contains(&keyp) {
7348 return None;
7349 }
7350
7351 let Some(gb) = repose_text::rasterize_cache_key(&keyp) else {
7352 self.mark_atlas_mask_failure(keyp);
7353 return None;
7354 };
7355 if gb.w == 0 || gb.h == 0 || gb.data.is_empty() {
7356 self.mark_atlas_mask_failure(keyp);
7357 return None;
7358 }
7359 let Some(coverage) = swash_to_a8_coverage(gb.content, &gb.data) else {
7360 self.mark_atlas_mask_failure(keyp);
7361 return None;
7362 };
7363
7364 let w = gb.w.max(1);
7365 let h = gb.h.max(1);
7366 let expected = checked_image_bytes_usize(w, h, 1).ok()?;
7367 if coverage.len() < expected {
7368 self.mark_atlas_mask_failure(keyp);
7369 return None;
7370 }
7371 if w >= MAX_GLYPH_ATLAS_SIZE || h >= MAX_GLYPH_ATLAS_SIZE {
7372 self.mark_atlas_mask_failure(keyp);
7373 return None;
7374 }
7375 if !self.alloc_or_schedule_mask(w, h) {
7376 defer_atlas_glyph(&mut self.atlas_mask_deferred, keyp);
7377 return None;
7378 }
7379 let x = self.atlas_mask.next_x;
7380 let y = self.atlas_mask.next_y;
7381 self.atlas_mask.next_x += w + 1;
7382 self.atlas_mask.row_h = self.atlas_mask.row_h.max(h + 1);
7383
7384 let layout = wgpu::TexelCopyBufferLayout {
7385 offset: 0,
7386 bytes_per_row: Some(w),
7387 rows_per_image: Some(h),
7388 };
7389 let size = wgpu::Extent3d {
7390 width: w,
7391 height: h,
7392 depth_or_array_layers: 1,
7393 };
7394 self.queue.write_texture(
7395 wgpu::TexelCopyTextureInfoBase {
7396 texture: &self.atlas_mask.tex,
7397 mip_level: 0,
7398 origin: wgpu::Origin3d { x, y, z: 0 },
7399 aspect: wgpu::TextureAspect::All,
7400 },
7401 &coverage,
7402 layout,
7403 size,
7404 );
7405
7406 let info = GlyphInfo {
7407 u0: x as f32 / self.atlas_mask.size as f32,
7408 v0: y as f32 / self.atlas_mask.size as f32,
7409 u1: (x + w) as f32 / self.atlas_mask.size as f32,
7410 v1: (y + h) as f32 / self.atlas_mask.size as f32,
7411 w: w as f32,
7412 h: h as f32,
7413 last_touch: touch,
7414 last_used_frame: self.frame_index,
7415 };
7416 self.atlas_mask.used_area = self
7417 .atlas_mask
7418 .used_area
7419 .saturating_add(u64::from(w).saturating_mul(u64::from(h)));
7420 self.atlas_mask.map.insert(keyp, info);
7421 Some(info)
7422 }
7423
7424 fn upload_glyph_color(
7425 &mut self,
7426 cache_key: repose_text::CacheKey,
7427 px: f32,
7428 ) -> Option<GlyphInfo> {
7429 let px = quantize_glyph_px(px);
7430 let keyp = repose_text::CacheKey {
7431 font_size_bits: px.to_bits(),
7432 ..cache_key
7433 };
7434 let touch = self.next_cache_touch();
7435 if let Some(info) = self.atlas_color.map.get_mut(&keyp) {
7436 info.last_touch = touch;
7437 info.last_used_frame = self.frame_index;
7438 return Some(*info);
7439 }
7440 if self.atlas_color_failures.contains(&keyp) || self.atlas_color_deferred.contains(&keyp) {
7441 return None;
7442 }
7443 let Some(gb) = repose_text::rasterize_cache_key(&keyp) else {
7444 self.mark_atlas_color_failure(keyp);
7445 return None;
7446 };
7447 if !matches!(gb.content, repose_text::SwashContent::Color) {
7448 self.mark_atlas_color_failure(keyp);
7449 return None;
7450 }
7451 let w = gb.w.max(1);
7452 let h = gb.h.max(1);
7453 let expected = checked_image_bytes_usize(w, h, 4).ok()?;
7454 if gb.data.len() < expected {
7455 self.mark_atlas_color_failure(keyp);
7456 return None;
7457 }
7458 if w >= MAX_GLYPH_ATLAS_SIZE || h >= MAX_GLYPH_ATLAS_SIZE {
7459 self.mark_atlas_color_failure(keyp);
7460 return None;
7461 }
7462 if !self.alloc_or_schedule_color(w, h) {
7463 defer_atlas_glyph(&mut self.atlas_color_deferred, keyp);
7464 return None;
7465 }
7466 let x = self.atlas_color.next_x;
7467 let y = self.atlas_color.next_y;
7468 self.atlas_color.next_x += w + 1;
7469 self.atlas_color.row_h = self.atlas_color.row_h.max(h + 1);
7470
7471 let layout = wgpu::TexelCopyBufferLayout {
7472 offset: 0,
7473 bytes_per_row: Some(w * 4),
7474 rows_per_image: Some(h),
7475 };
7476 let size = wgpu::Extent3d {
7477 width: w,
7478 height: h,
7479 depth_or_array_layers: 1,
7480 };
7481 self.queue.write_texture(
7482 wgpu::TexelCopyTextureInfoBase {
7483 texture: &self.atlas_color.tex,
7484 mip_level: 0,
7485 origin: wgpu::Origin3d { x, y, z: 0 },
7486 aspect: wgpu::TextureAspect::All,
7487 },
7488 &gb.data,
7489 layout,
7490 size,
7491 );
7492 let info = GlyphInfo {
7493 u0: x as f32 / self.atlas_color.size as f32,
7494 v0: y as f32 / self.atlas_color.size as f32,
7495 u1: (x + w) as f32 / self.atlas_color.size as f32,
7496 v1: (y + h) as f32 / self.atlas_color.size as f32,
7497 w: w as f32,
7498 h: h as f32,
7499 last_touch: touch,
7500 last_used_frame: self.frame_index,
7501 };
7502 self.atlas_color.used_area = self
7503 .atlas_color
7504 .used_area
7505 .saturating_add(u64::from(w).saturating_mul(u64::from(h)));
7506 self.atlas_color.map.insert(keyp, info);
7507 Some(info)
7508 }
7509
7510 fn alloc_space_mask(&mut self, w: u32, h: u32) -> bool {
7511 let Some(x_end) = self
7512 .atlas_mask
7513 .next_x
7514 .checked_add(w)
7515 .and_then(|v| v.checked_add(1))
7516 else {
7517 return false;
7518 };
7519 if x_end >= self.atlas_mask.size {
7520 self.atlas_mask.next_x = 1;
7521 let Some(next_y) = self
7522 .atlas_mask
7523 .next_y
7524 .checked_add(self.atlas_mask.row_h)
7525 .and_then(|v| v.checked_add(1))
7526 else {
7527 return false;
7528 };
7529 self.atlas_mask.next_y = next_y;
7530 self.atlas_mask.row_h = 0;
7531 }
7532 let Some(y_end) = self
7533 .atlas_mask
7534 .next_y
7535 .checked_add(h)
7536 .and_then(|v| v.checked_add(1))
7537 else {
7538 return false;
7539 };
7540 y_end < self.atlas_mask.size
7541 }
7542
7543 fn alloc_space_color(&mut self, w: u32, h: u32) -> bool {
7544 let Some(x_end) = self
7545 .atlas_color
7546 .next_x
7547 .checked_add(w)
7548 .and_then(|v| v.checked_add(1))
7549 else {
7550 return false;
7551 };
7552 if x_end >= self.atlas_color.size {
7553 self.atlas_color.next_x = 1;
7554 let Some(next_y) = self
7555 .atlas_color
7556 .next_y
7557 .checked_add(self.atlas_color.row_h)
7558 .and_then(|v| v.checked_add(1))
7559 else {
7560 return false;
7561 };
7562 self.atlas_color.next_y = next_y;
7563 self.atlas_color.row_h = 0;
7564 }
7565 let Some(y_end) = self
7566 .atlas_color
7567 .next_y
7568 .checked_add(h)
7569 .and_then(|v| v.checked_add(1))
7570 else {
7571 return false;
7572 };
7573 y_end < self.atlas_color.size
7574 }
7575
7576 fn alloc_or_schedule_mask(&mut self, w: u32, h: u32) -> bool {
7581 if self.atlas_mask.map.len() >= MAX_GLYPH_ATLAS_ENTRIES
7582 || self
7583 .atlas_mask
7584 .used_area
7585 .saturating_add(u64::from(w) * u64::from(h))
7586 >= self.atlas_mask.size as u64 * self.atlas_mask.size as u64
7587 {
7588 self.atlas_mask_pending.compact = true;
7589 return false;
7590 }
7591 if self.alloc_space_mask(w, h) {
7592 return true;
7593 }
7594 if self.atlas_mask.size < MAX_GLYPH_ATLAS_SIZE {
7595 self.atlas_mask_pending.grow = true;
7596 } else {
7597 self.atlas_mask_pending.compact = true;
7598 }
7599 false
7600 }
7601
7602 fn alloc_or_schedule_color(&mut self, w: u32, h: u32) -> bool {
7604 if self.atlas_color.map.len() >= MAX_GLYPH_ATLAS_ENTRIES
7605 || self
7606 .atlas_color
7607 .used_area
7608 .saturating_add(u64::from(w) * u64::from(h))
7609 >= self.atlas_color.size as u64 * self.atlas_color.size as u64
7610 {
7611 self.atlas_color_pending.compact = true;
7612 return false;
7613 }
7614 if self.alloc_space_color(w, h) {
7615 return true;
7616 }
7617 if self.atlas_color.size < MAX_GLYPH_ATLAS_SIZE {
7618 self.atlas_color_pending.grow = true;
7619 } else {
7620 self.atlas_color_pending.compact = true;
7621 }
7622 false
7623 }
7624}
7625
7626fn pack_shape_bits(brush_type: u32, grad_kind: u32, tile_mode: u32, cap: u32) -> u32 {
7629 debug_assert!(brush_type < 4 && grad_kind < 4 && tile_mode < 4 && cap < 4);
7630 (brush_type & 3) | ((grad_kind & 3) << 2) | ((tile_mode & 3) << 4) | ((cap & 3) << 6)
7631}
7632
7633fn tile_mode_bits(mode: TileMode) -> u32 {
7634 match mode {
7635 TileMode::Clamp => 0,
7636 TileMode::Repeated => 1,
7637 TileMode::Mirror => 2,
7638 }
7639}
7640
7641fn pack_shape_bits_with_stops(
7642 brush_type: u32,
7643 grad_kind: u32,
7644 tile_mode: u32,
7645 cap: u32,
7646 stop_table: u32,
7647) -> u32 {
7648 pack_shape_bits(brush_type, grad_kind, tile_mode, cap) | ((stop_table & 0xFFF) << 8)
7649}
7650
7651fn push_shape_stops(tables: &mut Vec<ShapeGradientStopsGpu>, stops: &GradientStops) -> u32 {
7652 let id = tables.len() as u32;
7653 if id < MAX_SHAPE_GRADIENT_TABLES {
7654 tables.push(ShapeGradientStopsGpu::from_stops(stops));
7655 id
7656 } else {
7657 0
7658 }
7659}
7660
7661fn stop_endpoints(stops: &GradientStops) -> ([f32; 4], [f32; 4]) {
7662 let slice = stops.as_slice();
7663 match slice.first() {
7664 Some(first) => (
7665 first.color.to_linear(),
7666 slice
7667 .last()
7668 .map(|s| s.color.to_linear())
7669 .unwrap_or(first.color.to_linear()),
7670 ),
7671 None => ([0.0; 4], [0.0; 4]),
7672 }
7673}
7674
7675fn brush_to_shape_fields(
7689 brush: &Brush,
7690 rect: &repose_core::Rect,
7691 transform: &Transform,
7692 stop_tables: &mut Vec<ShapeGradientStopsGpu>,
7693) -> (u32, u32, [f32; 4], [f32; 4], [f32; 2], [f32; 2], u32, u32) {
7694 let to_local = |p: Vec2| {
7695 let m = transform.linear();
7696 let det = m[0] * m[3] - m[1] * m[2];
7697 if det.abs() < 1e-12 {
7698 return [p.x, p.y];
7699 }
7700 [
7701 (m[3] * p.x - m[1] * p.y) / det,
7702 (-m[2] * p.x + m[0] * p.y) / det,
7703 ]
7704 };
7705 match brush {
7706 Brush::Solid(c) => (
7707 0u32,
7708 0u32,
7709 c.to_linear(),
7710 [0.0; 4],
7711 [0.0; 2],
7712 [0.0; 2],
7713 0u32,
7714 0u32,
7715 ),
7716 Brush::Linear {
7717 start,
7718 end,
7719 start_color,
7720 end_color,
7721 } => (
7722 1u32,
7723 0u32,
7724 start_color.to_linear(),
7725 end_color.to_linear(),
7726 to_local(*start),
7727 to_local(*end),
7728 0u32,
7729 0u32,
7730 ),
7731 Brush::LinearNormalized {
7732 start,
7733 end,
7734 start_color,
7735 end_color,
7736 } => (
7737 1u32,
7738 0u32,
7739 start_color.to_linear(),
7740 end_color.to_linear(),
7741 to_local(Vec2 {
7742 x: start.x * rect.w,
7743 y: start.y * rect.h,
7744 }),
7745 to_local(Vec2 {
7746 x: end.x * rect.w,
7747 y: end.y * rect.h,
7748 }),
7749 0u32,
7750 0u32,
7751 ),
7752 Brush::Radial {
7753 center,
7754 radius,
7755 start_color,
7756 end_color,
7757 } => (
7758 1u32,
7759 1u32,
7760 start_color.to_linear(),
7761 end_color.to_linear(),
7762 to_local(*center),
7763 [radius.max(0.0), 0.0],
7764 0u32,
7765 0u32,
7766 ),
7767 Brush::Sweep {
7768 center,
7769 start_color,
7770 end_color,
7771 } => (
7772 1u32,
7773 2u32,
7774 start_color.to_linear(),
7775 end_color.to_linear(),
7776 to_local(*center),
7777 [0.0, 0.0],
7778 0u32,
7779 0u32,
7780 ),
7781 Brush::LinearStops {
7782 start,
7783 end,
7784 stops,
7785 tile_mode,
7786 } => {
7787 let id = push_shape_stops(stop_tables, stops);
7788 let (color0, color1) = stop_endpoints(stops);
7789 (
7790 2u32,
7791 0u32,
7792 color0,
7793 color1,
7794 to_local(*start),
7795 to_local(*end),
7796 tile_mode_bits(*tile_mode),
7797 id,
7798 )
7799 }
7800 Brush::LinearNormalizedStops {
7801 start,
7802 end,
7803 stops,
7804 tile_mode,
7805 } => {
7806 let id = push_shape_stops(stop_tables, stops);
7807 let (color0, color1) = stop_endpoints(stops);
7808 (
7809 2u32,
7810 0u32,
7811 color0,
7812 color1,
7813 to_local(Vec2 {
7814 x: start.x * rect.w,
7815 y: start.y * rect.h,
7816 }),
7817 to_local(Vec2 {
7818 x: end.x * rect.w,
7819 y: end.y * rect.h,
7820 }),
7821 tile_mode_bits(*tile_mode),
7822 id,
7823 )
7824 }
7825 Brush::RadialStops {
7826 center,
7827 radius,
7828 stops,
7829 tile_mode,
7830 } => {
7831 let id = push_shape_stops(stop_tables, stops);
7832 let (color0, color1) = stop_endpoints(stops);
7833 (
7834 2u32,
7835 1u32,
7836 color0,
7837 color1,
7838 to_local(*center),
7839 [radius.max(0.0), 0.0],
7840 tile_mode_bits(*tile_mode),
7841 id,
7842 )
7843 }
7844 Brush::SweepStops {
7845 center,
7846 stops,
7847 tile_mode,
7848 } => {
7849 let id = push_shape_stops(stop_tables, stops);
7850 let (color0, color1) = stop_endpoints(stops);
7851 (
7852 2u32,
7853 2u32,
7854 color0,
7855 color1,
7856 to_local(*center),
7857 [0.0, 0.0],
7858 tile_mode_bits(*tile_mode),
7859 id,
7860 )
7861 }
7862 _ => (
7863 0u32, 0u32, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2], 0u32, 0u32,
7864 ),
7865 }
7866}
7867
7868fn shape_path_to_lyon(path: &ShapePath, ppp: f32) -> Option<lyon_path::Path> {
7870 use lyon_path::math::Point;
7871
7872 let point = |x: Dp, y: Dp| Point::new(x.0 * ppp, y.0 * ppp);
7873 let finite = |p: Point| p.x.is_finite() && p.y.is_finite();
7874 let mut builder = lyon_path::Path::builder();
7875 let mut open = false;
7876 for command in &path.commands {
7877 match *command {
7878 PathCommand::MoveTo(x, y) => {
7879 let p = point(x, y);
7880 if !finite(p) {
7881 return None;
7882 }
7883 if open {
7884 builder.end(false);
7885 }
7886 builder.begin(p);
7887 open = true;
7888 }
7889 PathCommand::LineTo(x, y) => {
7890 if !open {
7891 continue;
7892 }
7893 let p = point(x, y);
7894 if !finite(p) {
7895 return None;
7896 }
7897 builder.line_to(p);
7898 }
7899 PathCommand::CubicTo { c1, c2, end } => {
7900 if !open {
7901 continue;
7902 }
7903 let c1 = point(c1.0, c1.1);
7904 let c2 = point(c2.0, c2.1);
7905 let end = point(end.0, end.1);
7906 if !finite(c1) || !finite(c2) || !finite(end) {
7907 return None;
7908 }
7909 builder.cubic_bezier_to(c1, c2, end);
7910 }
7911 PathCommand::Close => {
7912 if open {
7913 builder.close();
7914 open = false;
7915 }
7916 }
7917 }
7918 }
7919 if open {
7920 builder.end(false);
7921 }
7922 Some(builder.build())
7923}
7924
7925fn shape_mesh_from_buffers(
7926 buffers: lyon_tessellation::VertexBuffers<lyon_path::math::Point, u16>,
7927) -> Option<repose_core::VectorMeshData> {
7928 if buffers.indices.is_empty() {
7929 return None;
7930 }
7931 let vertices: Arc<[repose_core::VectorVertex]> = buffers
7932 .vertices
7933 .iter()
7934 .map(|v| repose_core::VectorVertex {
7935 pos: [v.x, v.y],
7936 color: [1.0; 4],
7937 uv: [0.0, 0.0],
7938 })
7939 .collect();
7940 let indices: Arc<[u32]> = buffers.indices.iter().map(|&i| i as u32).collect();
7941 Some(repose_core::VectorMeshData { vertices, indices })
7942}
7943
7944fn tessellate_shape_path(
7949 path: &ShapePath,
7950 ppp: f32,
7951 stroke: Option<Px>,
7952) -> Option<repose_core::VectorMeshData> {
7953 use lyon_tessellation::{
7954 FillTessellator, StrokeTessellator, VertexBuffers, geometry_builder::simple_builder,
7955 };
7956
7957 let lyon_path = shape_path_to_lyon(path, ppp)?;
7958 let mut buffers: VertexBuffers<lyon_path::math::Point, u16> = VertexBuffers::new();
7959 if let Some(width) = stroke {
7960 if !width.0.is_finite() || width.0 <= 0.0 {
7961 return None;
7962 }
7963 StrokeTessellator::new()
7964 .tessellate_path(
7965 &lyon_path,
7966 &lyon_tessellation::StrokeOptions::default()
7967 .with_tolerance(0.25)
7968 .with_line_width(width.0),
7969 &mut simple_builder(&mut buffers),
7970 )
7971 .ok()?;
7972 } else {
7973 FillTessellator::new()
7974 .tessellate_path(
7975 &lyon_path,
7976 &lyon_tessellation::FillOptions::default().with_tolerance(0.25),
7977 &mut simple_builder(&mut buffers),
7978 )
7979 .ok()?;
7980 }
7981 shape_mesh_from_buffers(buffers)
7982}
7983
7984fn tessellate_shape_ellipse(rect: repose_core::Rect) -> Option<repose_core::VectorMeshData> {
7987 use lyon_tessellation::{FillTessellator, VertexBuffers, geometry_builder::simple_builder};
7988
7989 let rx = (rect.w * 0.5).max(0.0);
7990 let ry = (rect.h * 0.5).max(0.0);
7991 if !rx.is_finite() || !ry.is_finite() || rx <= 0.0 || ry <= 0.0 {
7992 return None;
7993 }
7994 let mut builder = lyon_path::Path::builder();
7995 builder.add_ellipse(
7996 lyon_path::math::Point::new(rect.w * 0.5, rect.h * 0.5),
7997 lyon_path::math::Vector::new(rx, ry),
7998 lyon_path::math::Angle::radians(0.0),
7999 lyon_path::Winding::Positive,
8000 );
8001 let path = builder.build();
8002 let mut buffers: VertexBuffers<lyon_path::math::Point, u16> = VertexBuffers::new();
8003 FillTessellator::new()
8004 .tessellate_path(
8005 &path,
8006 &lyon_tessellation::FillOptions::default().with_tolerance(0.25),
8007 &mut simple_builder(&mut buffers),
8008 )
8009 .ok()?;
8010 shape_mesh_from_buffers(buffers)
8011}
8012
8013fn shape_path_aabb(
8016 path: &ShapePath,
8017 ppp: f32,
8018 offset: (f32, f32),
8019 stroke: Option<Px>,
8020) -> repose_core::Rect {
8021 let mut min_x = f32::INFINITY;
8022 let mut min_y = f32::INFINITY;
8023 let mut max_x = f32::NEG_INFINITY;
8024 let mut max_y = f32::NEG_INFINITY;
8025 let mut include = |x: f32, y: f32| {
8026 min_x = min_x.min(x);
8027 min_y = min_y.min(y);
8028 max_x = max_x.max(x);
8029 max_y = max_y.max(y);
8030 };
8031 let point = |x: Dp, y: Dp| (x.0 * ppp + offset.0, y.0 * ppp + offset.1);
8032 for command in &path.commands {
8033 match *command {
8034 PathCommand::MoveTo(x, y) | PathCommand::LineTo(x, y) => {
8035 let (x, y) = point(x, y);
8036 include(x, y);
8037 }
8038 PathCommand::CubicTo { c1, c2, end } => {
8039 for (x, y) in [c1, c2, end] {
8040 let (x, y) = point(x, y);
8041 include(x, y);
8042 }
8043 }
8044 PathCommand::Close => {}
8045 }
8046 }
8047 let pad = stroke.map_or(0.0, |w| w.0.max(0.0) * 0.5);
8048 if !min_x.is_finite() || !min_y.is_finite() {
8049 return repose_core::Rect {
8050 x: 0.0,
8051 y: 0.0,
8052 w: 0.0,
8053 h: 0.0,
8054 };
8055 }
8056 repose_core::Rect {
8057 x: min_x - pad,
8058 y: min_y - pad,
8059 w: (max_x - min_x).max(0.0) + pad * 2.0,
8060 h: (max_y - min_y).max(0.0) + pad * 2.0,
8061 }
8062}
8063
8064fn brush_to_paint_desc(brush: &Brush, rect: repose_core::Rect) -> repose_core::PaintDesc {
8070 use repose_core::PaintDesc as P;
8071 let scaled = |p: Vec2| Vec2 {
8072 x: p.x * rect.w,
8073 y: p.y * rect.h,
8074 };
8075 let stop_colors = |stops: &GradientStops| {
8076 let slice = stops.as_slice();
8077 let transparent = repose_core::Color::TRANSPARENT;
8078 (
8079 slice.first().map_or(transparent, |s| s.color),
8080 slice.last().map_or(transparent, |s| s.color),
8081 )
8082 };
8083 match *brush {
8084 Brush::Solid(c) => P::Linear {
8085 start: Vec2::ZERO,
8086 end: Vec2::ZERO,
8087 start_color: c,
8088 end_color: c,
8089 },
8090 Brush::Linear {
8091 start,
8092 end,
8093 start_color,
8094 end_color,
8095 } => P::Linear {
8096 start,
8097 end,
8098 start_color,
8099 end_color,
8100 },
8101 Brush::LinearNormalized {
8102 start,
8103 end,
8104 start_color,
8105 end_color,
8106 } => P::Linear {
8107 start: scaled(start),
8108 end: scaled(end),
8109 start_color,
8110 end_color,
8111 },
8112 Brush::Radial {
8113 center,
8114 radius,
8115 start_color,
8116 end_color,
8117 } => P::Radial {
8118 center,
8119 radius,
8120 start_color,
8121 end_color,
8122 },
8123 Brush::Sweep {
8124 center,
8125 start_color,
8126 end_color,
8127 } => P::Sweep {
8128 center,
8129 start_color,
8130 end_color,
8131 },
8132 Brush::LinearStops {
8133 start, end, stops, ..
8134 } => P::LinearStops { start, end, stops },
8135 Brush::LinearNormalizedStops {
8136 start, end, stops, ..
8137 } => P::LinearStops {
8138 start: scaled(start),
8139 end: scaled(end),
8140 stops,
8141 },
8142 Brush::RadialStops {
8143 center,
8144 radius,
8145 stops,
8146 ..
8147 } => P::RadialStops {
8148 center,
8149 radius,
8150 stops,
8151 },
8152 Brush::SweepStops { center, stops, .. } => {
8153 let (start_color, end_color) = stop_colors(&stops);
8154 P::Sweep {
8155 center,
8156 start_color,
8157 end_color,
8158 }
8159 }
8160 _ => P::Linear {
8161 start: Vec2::ZERO,
8162 end: Vec2::ZERO,
8163 start_color: repose_core::Color::TRANSPARENT,
8164 end_color: repose_core::Color::TRANSPARENT,
8165 },
8166 }
8167}
8168
8169fn brush_to_instance_fields(brush: &Brush) -> (u32, [f32; 4], [f32; 4], [f32; 2], [f32; 2]) {
8170 match brush {
8171 Brush::Solid(c) => (
8172 0u32,
8173 c.to_linear(),
8174 [0.0, 0.0, 0.0, 0.0],
8175 [0.0, 0.0],
8176 [0.0, 1.0],
8177 ),
8178 Brush::Linear {
8179 start,
8180 end,
8181 start_color,
8182 end_color,
8183 } => (
8184 1u32,
8185 start_color.to_linear(),
8186 end_color.to_linear(),
8187 [start.x, start.y],
8188 [end.x, end.y],
8189 ),
8190 Brush::LinearNormalized {
8191 start,
8192 end,
8193 start_color,
8194 end_color,
8195 } => (
8196 1u32,
8197 start_color.to_linear(),
8198 end_color.to_linear(),
8199 [start.x, start.y],
8200 [end.x, end.y],
8201 ),
8202 Brush::Radial { start_color, .. } => (
8203 0u32,
8204 start_color.to_linear(),
8205 [0.0, 0.0, 0.0, 0.0],
8206 [0.0, 0.0],
8207 [0.0, 1.0],
8208 ),
8209 Brush::Sweep { start_color, .. } => (
8210 0u32,
8211 start_color.to_linear(),
8212 [0.0, 0.0, 0.0, 0.0],
8213 [0.0, 0.0],
8214 [0.0, 1.0],
8215 ),
8216 Brush::LinearStops {
8217 start, end, stops, ..
8218 }
8219 | Brush::LinearNormalizedStops {
8220 start, end, stops, ..
8221 } => {
8222 let (color0, color1) = stop_endpoints(stops);
8223 (1u32, color0, color1, [start.x, start.y], [end.x, end.y])
8224 }
8225 Brush::RadialStops { stops, .. } | Brush::SweepStops { stops, .. } => {
8226 let (color0, _) = stop_endpoints(stops);
8227 (0u32, color0, [0.0; 4], [0.0, 0.0], [0.0, 1.0])
8228 }
8229 _ => (0u32, [0.0; 4], [0.0; 4], [0.0; 2], [0.0; 2]),
8230 }
8231}
8232
8233#[allow(dead_code)]
8236fn brush_to_solid_color(brush: &Brush) -> [f32; 4] {
8237 match brush {
8238 Brush::Solid(c) => c.to_linear(),
8239 Brush::Linear { start_color, .. } => start_color.to_linear(),
8240 Brush::LinearNormalized { start_color, .. } => start_color.to_linear(),
8241 Brush::Radial { start_color, .. } => start_color.to_linear(),
8242 Brush::Sweep { start_color, .. } => start_color.to_linear(),
8243 Brush::LinearStops { stops, .. }
8244 | Brush::LinearNormalizedStops { stops, .. }
8245 | Brush::RadialStops { stops, .. }
8246 | Brush::SweepStops { stops, .. } => stop_endpoints(stops).0,
8247 _ => [0.0; 4],
8248 }
8249}
8250
8251fn init_atlas_mask(device: &wgpu::Device) -> AtlasA8 {
8252 let size = 1024u32;
8253 let tex = device.create_texture(&wgpu::TextureDescriptor {
8254 label: Some("glyph atlas A8"),
8255 size: wgpu::Extent3d {
8256 width: size,
8257 height: size,
8258 depth_or_array_layers: 1,
8259 },
8260 mip_level_count: 1,
8261 sample_count: 1,
8262 dimension: wgpu::TextureDimension::D2,
8263 format: wgpu::TextureFormat::R8Unorm,
8264 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
8265 view_formats: &[],
8266 });
8267 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
8268 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
8269 label: Some("glyph atlas sampler A8"),
8270 address_mode_u: wgpu::AddressMode::ClampToEdge,
8271 address_mode_v: wgpu::AddressMode::ClampToEdge,
8272 address_mode_w: wgpu::AddressMode::ClampToEdge,
8273 mag_filter: wgpu::FilterMode::Linear,
8274 min_filter: wgpu::FilterMode::Linear,
8275 mipmap_filter: wgpu::MipmapFilterMode::Linear,
8276 ..Default::default()
8277 });
8278
8279 AtlasA8 {
8280 tex,
8281 view,
8282 sampler,
8283 size,
8284 next_x: 1,
8285 next_y: 1,
8286 row_h: 0,
8287 map: HashMap::new(),
8288 used_area: 0,
8289 }
8290}
8291
8292fn init_atlas_color(device: &wgpu::Device) -> AtlasRGBA {
8293 let size = 1024u32;
8294 let tex = device.create_texture(&wgpu::TextureDescriptor {
8295 label: Some("glyph atlas RGBA"),
8296 size: wgpu::Extent3d {
8297 width: size,
8298 height: size,
8299 depth_or_array_layers: 1,
8300 },
8301 mip_level_count: 1,
8302 sample_count: 1,
8303 dimension: wgpu::TextureDimension::D2,
8304 format: wgpu::TextureFormat::Rgba8UnormSrgb,
8305 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
8306 view_formats: &[],
8307 });
8308 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
8309 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
8310 label: Some("glyph atlas sampler RGBA"),
8311 address_mode_u: wgpu::AddressMode::ClampToEdge,
8312 address_mode_v: wgpu::AddressMode::ClampToEdge,
8313 address_mode_w: wgpu::AddressMode::ClampToEdge,
8314 mag_filter: wgpu::FilterMode::Linear,
8315 min_filter: wgpu::FilterMode::Linear,
8316 mipmap_filter: wgpu::MipmapFilterMode::Linear,
8317 ..Default::default()
8318 });
8319 AtlasRGBA {
8320 tex,
8321 view,
8322 sampler,
8323 size,
8324 next_x: 1,
8325 next_y: 1,
8326 row_h: 0,
8327 map: HashMap::new(),
8328 used_area: 0,
8329 }
8330}
8331
8332#[cfg(feature = "winit-surface")]
8333impl WgpuSurfaceBackend {
8334 pub fn take_surface(&mut self) -> Option<wgpu::Surface<'static>> {
8337 self.surface.take()
8338 }
8339
8340 pub fn recreate_surface(&mut self, window: &Arc<winit::window::Window>) -> anyhow::Result<()> {
8344 self.window = Some(window.clone());
8345 let size = window.inner_size();
8346 if size.width == 0 || size.height == 0 {
8347 self.surface = None;
8348 self.pending_reconfigure = false;
8349 self.renderer.resize(0, 0);
8350 anyhow::bail!("window has zero size; surface recreation deferred");
8351 }
8352 let Some(instance) = self.instance.as_ref() else {
8353 anyhow::bail!("no wgpu instance retained; cannot recreate surface")
8354 };
8355 let Some(config) = self.surface_config.as_mut() else {
8356 anyhow::bail!("no surface config retained; cannot recreate surface")
8357 };
8358 let (width, height) = clamp_output_size(
8359 size.width,
8360 size.height,
8361 self.renderer.device.limits().max_texture_dimension_2d,
8362 );
8363 config.width = width;
8364 config.height = height;
8365 let surface = instance.create_surface(window.clone())?;
8366 surface.configure(&self.renderer.device, config);
8367 self.surface = Some(surface);
8368 self.pending_reconfigure = false;
8369 self.renderer.resize(width, height);
8370 Ok(())
8371 }
8372}
8373
8374#[cfg(feature = "winit-surface")]
8375impl RenderBackend for WgpuSurfaceBackend {
8376 fn configure_surface(&mut self, width: u32, height: u32) -> (u32, u32) {
8377 if width == 0 || height == 0 {
8378 self.renderer.resize(0, 0);
8379 self.pending_reconfigure = true;
8380 return (0, 0);
8381 }
8382 let (width, height) = clamp_output_size(
8383 width,
8384 height,
8385 self.renderer.device.limits().max_texture_dimension_2d,
8386 );
8387 if self.renderer.output_width == width && self.renderer.output_height == height {
8388 if let Some(ref mut config) = self.surface_config {
8389 config.width = width;
8390 config.height = height;
8391 }
8392 return (width, height);
8393 }
8394 if let Some(ref mut config) = self.surface_config {
8395 config.width = width;
8396 config.height = height;
8397 }
8398 self.renderer.resize(width, height);
8399 if let (Some(surface), Some(config)) = (self.surface.as_ref(), self.surface_config.as_ref())
8400 {
8401 surface.configure(&self.renderer.device, config);
8402 }
8403 (width, height)
8404 }
8405
8406 fn frame(&mut self, scene: &Scene, _glyph_cfg: GlyphRasterConfig) -> bool {
8407 if self.pending_reconfigure {
8408 if let (Some(surface), Some(config)) =
8409 (self.surface.as_ref(), self.surface_config.as_ref())
8410 {
8411 surface.configure(&self.renderer.device, config);
8412 }
8413 self.pending_reconfigure = false;
8414 }
8415
8416 if self.renderer.output_width == 0 || self.renderer.output_height == 0 {
8417 request_frame();
8418 return false;
8419 }
8420 if let Err(error) = self.renderer.begin_frame() {
8421 log::warn!("begin renderer frame: {error:#}");
8422 request_frame();
8423 return false;
8424 }
8425
8426 let Some(surface) = self.surface.as_ref() else {
8427 self.renderer.end_frame();
8428 request_frame();
8429 return false;
8430 };
8431 let frame = match surface.get_current_texture() {
8432 wgpu::CurrentSurfaceTexture::Success(f) => f,
8433 wgpu::CurrentSurfaceTexture::Suboptimal(f) => {
8434 self.pending_reconfigure = true;
8435 f
8436 }
8437 other @ (wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost) => {
8438 self.surface = None;
8439 let result = self
8440 .window
8441 .clone()
8442 .ok_or_else(|| anyhow::anyhow!("no window retained for surface recreation"))
8443 .and_then(|window| self.recreate_surface(&window));
8444 if let Err(error) = result {
8445 log::warn!("surface {other:?}; recreation deferred: {error:#}");
8446 }
8447 self.renderer.end_frame();
8448 request_frame();
8449 return false;
8450 }
8451 other => {
8452 match other {
8453 wgpu::CurrentSurfaceTexture::Validation => {
8454 log::warn!("surface {other:?}; reconfiguring next frame");
8455 self.pending_reconfigure = true;
8456 }
8457 wgpu::CurrentSurfaceTexture::Timeout
8458 | wgpu::CurrentSurfaceTexture::Occluded => {
8459 log::debug!("surface {other:?}; retrying next frame");
8460 }
8461 _ => {}
8462 }
8463 self.renderer.end_frame();
8464 request_frame();
8465 return false;
8466 }
8467 };
8468
8469 let (swap_w, swap_h) = (frame.texture.width(), frame.texture.height());
8478 if swap_w != self.renderer.output_width || swap_h != self.renderer.output_height {
8479 log::debug!(
8480 "swapchain {swap_w}x{swap_h} != renderer {}x{}; resyncing",
8481 self.renderer.output_width,
8482 self.renderer.output_height
8483 );
8484 drop(frame);
8485 if let Some(config) = self.surface_config.as_mut() {
8486 config.width = swap_w;
8487 config.height = swap_h;
8488 }
8489 self.renderer.resize(swap_w, swap_h);
8490 self.pending_reconfigure = true;
8491 self.renderer.end_frame();
8492 request_frame();
8493 return false;
8494 }
8495
8496 let swap_view = if let Some(view_format) = self
8497 .surface_config
8498 .as_ref()
8499 .and_then(|c| c.view_formats.iter().find(|f| f.is_srgb()).copied())
8500 {
8501 frame.texture.create_view(&wgpu::TextureViewDescriptor {
8502 format: Some(view_format),
8503 ..Default::default()
8504 })
8505 } else {
8506 frame
8507 .texture
8508 .create_view(&wgpu::TextureViewDescriptor::default())
8509 };
8510 let mut encoder =
8511 self.renderer
8512 .device
8513 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
8514 label: Some("frame encoder"),
8515 });
8516
8517 self.renderer.render_scene_to_encoder_with_texture(
8518 scene,
8519 &mut encoder,
8520 &swap_view,
8521 Some(&frame.texture),
8522 None,
8523 );
8524
8525 {
8528 let _reset = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
8529 label: Some("webgl color_mask reset before present"),
8530 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
8531 view: &swap_view,
8532 resolve_target: None,
8533 ops: wgpu::Operations {
8534 load: wgpu::LoadOp::Load,
8535 store: wgpu::StoreOp::Store,
8536 },
8537 depth_slice: None,
8538 })],
8539 depth_stencil_attachment: None,
8540 timestamp_writes: None,
8541 occlusion_query_set: None,
8542 multiview_mask: None,
8543 });
8544 }
8545
8546 self.renderer
8547 .queue
8548 .submit(std::iter::once(encoder.finish()));
8549 if let Err(e) = catch_unwind(AssertUnwindSafe(|| self.renderer.queue.present(frame))) {
8550 log::warn!("queue.present panicked: {:?}", e);
8551 self.renderer.end_frame();
8552 request_frame();
8553 return false;
8554 }
8555 self.renderer.end_frame();
8556 true
8557 }
8558}
8559
8560impl WgpuSceneRenderer {
8561 #[allow(clippy::too_many_arguments)]
8573 fn replay_active_clips(
8574 &mut self,
8575 clips: &[ActiveClip],
8576 parent_transform: &Transform,
8577 origin: (f32, f32),
8578 target_size: (f32, f32),
8579 pass: &mut Pass,
8580 encoder: &mut wgpu::CommandEncoder,
8581 ) -> Vec<ActiveClip> {
8582 let mut current = repose_core::Rect {
8583 x: 0.0,
8584 y: 0.0,
8585 w: target_size.0,
8586 h: target_size.1,
8587 };
8588 let mut replayed = Vec::with_capacity(clips.len());
8589 for (index, clip) in clips.iter().enumerate() {
8590 let has_inverse = clips[..index].iter().any(ActiveClip::difference);
8591 let mut blocked = clip.blocked();
8592 if has_inverse && !blocked {
8593 log::error!(
8594 "unsupported clip nesting: a Difference clip cannot contain another clip"
8595 );
8596 blocked = true;
8597 }
8598 let difference = clip.difference();
8599 let mut command = None;
8600 match clip {
8601 ActiveClip::Rect {
8602 off: _,
8603 cnt: _,
8604 rect,
8605 radii,
8606 ..
8607 } => {
8608 let local_rect = parent_rect_to_layer_rect(*rect, parent_transform, origin)
8609 .unwrap_or(repose_core::Rect {
8610 x: 0.0,
8611 y: 0.0,
8612 w: 0.0,
8613 h: 0.0,
8614 });
8615 let local_radii =
8616 parent_radii_to_layer_radii(*radii, parent_transform).unwrap_or([0.0; 4]);
8617 let next = if difference {
8618 current
8619 } else {
8620 intersect(current, local_rect)
8621 };
8622 let scissor = rect_to_scissor(
8623 next,
8624 target_size.0.max(1.0) as u32,
8625 target_size.1.max(1.0) as u32,
8626 );
8627 let has_area = local_rect.x.is_finite()
8628 && local_rect.y.is_finite()
8629 && local_rect.w.is_finite()
8630 && local_rect.h.is_finite()
8631 && local_rect.w > 0.0
8632 && local_rect.h > 0.0;
8633 if blocked || !has_area || (!difference && scissor.2 == 0) {
8634 blocked = blocked || !difference;
8635 } else {
8636 let ndc = rect_to_ndc(local_rect, target_size.0, target_size.1);
8637 let instance = ClipInstance {
8638 xywh: [ndc[0] + ndc[2] * 0.5, ndc[1] + ndc[3] * 0.5, ndc[2], ndc[3]],
8639 radii: local_radii,
8640 fwd_mat: [1.0, 0.0, 0.0, 1.0],
8641 };
8642 let bytes = bytemuck::bytes_of(&instance);
8643 if self
8644 .clip_ring
8645 .grow_to_fit(
8646 &self.device,
8647 encoder,
8648 u64::try_from(bytes.len()).unwrap_or(u64::MAX),
8649 )
8650 .is_ok()
8651 && let Ok(new_off) = self.clip_ring.alloc_write(&self.queue, bytes)
8652 {
8653 command = Some(Cmd::ClipPush {
8654 off: new_off,
8655 cnt: 1,
8656 scissor,
8657 difference,
8658 applied: true,
8659 });
8660 replayed.push(ActiveClip::Rect {
8661 off: new_off,
8662 cnt: 1,
8663 rect: local_rect,
8664 radii: local_radii,
8665 scissor,
8666 difference,
8667 applied: true,
8668 blocked: false,
8669 });
8670 } else {
8671 blocked = blocked || !difference;
8672 }
8673 }
8674 current = next;
8675 }
8676 ActiveClip::Vector {
8677 mesh,
8678 source,
8679 affine,
8680 ..
8681 } => {
8682 let local_affine =
8683 parent_affine_to_layer_affine(*affine, parent_transform, origin)
8684 .unwrap_or([0.0; 6]);
8685 let aabb = mesh_aabb(source, local_affine);
8686 let next = if difference {
8687 current
8688 } else {
8689 intersect(current, aabb)
8690 };
8691 let scissor = rect_to_scissor(
8692 next,
8693 target_size.0.max(1.0) as u32,
8694 target_size.1.max(1.0) as u32,
8695 );
8696 let has_area = aabb.x.is_finite()
8697 && aabb.y.is_finite()
8698 && aabb.w.is_finite()
8699 && aabb.h.is_finite()
8700 && aabb.w > 0.0
8701 && aabb.h > 0.0
8702 && mesh
8703 .as_ref()
8704 .is_some_and(|mesh| mesh.vertex_count > 0 && mesh.index_count > 0);
8705 if blocked || !has_area || (!difference && scissor.2 == 0) {
8706 blocked = blocked || !difference;
8707 } else if let Some(mesh_gpu) = mesh.clone()
8708 && let Some(uoff) = self.alloc_mesh_uniform(mesh_uniform_from_paint(
8709 &repose_core::PaintDesc::Solid,
8710 ))
8711 && let Some((ioff, icnt)) = self.alloc_mesh_instances(&[local_affine])
8712 {
8713 command = Some(Cmd::VectorClipPush {
8714 mesh: mesh_gpu.clone(),
8715 uoff,
8716 ioff,
8717 icnt,
8718 scissor,
8719 difference,
8720 applied: true,
8721 });
8722 replayed.push(ActiveClip::Vector {
8723 mesh: Some(mesh_gpu),
8724 source: source.clone(),
8725 uoff,
8726 ioff,
8727 icnt,
8728 affine: local_affine,
8729 scissor,
8730 difference,
8731 applied: true,
8732 blocked: false,
8733 });
8734 } else {
8735 blocked = blocked || !difference;
8736 }
8737 current = next;
8738 }
8739 }
8740 if blocked {
8741 current = repose_core::Rect {
8742 x: 0.0,
8743 y: 0.0,
8744 w: 0.0,
8745 h: 0.0,
8746 };
8747 }
8748 if command.is_none() {
8749 replayed.push(match clip {
8750 ActiveClip::Rect {
8751 rect,
8752 radii,
8753 scissor,
8754 difference,
8755 ..
8756 } => ActiveClip::Rect {
8757 off: 0,
8758 cnt: 0,
8759 rect: *rect,
8760 radii: *radii,
8761 scissor: *scissor,
8762 difference: *difference,
8763 applied: false,
8764 blocked,
8765 },
8766 ActiveClip::Vector {
8767 mesh,
8768 source,
8769 affine,
8770 scissor,
8771 difference,
8772 ..
8773 } => ActiveClip::Vector {
8774 mesh: mesh.clone(),
8775 source: source.clone(),
8776 uoff: 0,
8777 ioff: 0,
8778 icnt: 0,
8779 affine: parent_affine_to_layer_affine(*affine, parent_transform, origin)
8780 .unwrap_or([0.0; 6]),
8781 scissor: *scissor,
8782 difference: *difference,
8783 applied: false,
8784 blocked,
8785 },
8786 });
8787 }
8788 if let Some(command) = command {
8789 pass.cmds.push(command);
8790 }
8791 pass.active_scissor = if blocked {
8792 None
8793 } else {
8794 let scissor = rect_to_scissor(
8795 current,
8796 target_size.0.max(1.0) as u32,
8797 target_size.1.max(1.0) as u32,
8798 );
8799 (scissor.2 > 0 && scissor.3 > 0).then_some(scissor)
8800 };
8801 }
8802 replayed
8803 }
8804
8805 #[allow(clippy::too_many_arguments)]
8806 fn push_perspective_layer(
8807 &mut self,
8808 node: Transform,
8809 top: Transform,
8810 transform_stack: &mut Vec<Transform>,
8811 scissor_stack: &mut Vec<repose_core::Rect>,
8812 root_clip_rect: &mut repose_core::Rect,
8813 current_target_size: &mut (f32, f32),
8814 current_pass: &mut Pass,
8815 active_clips: &mut Vec<ActiveClip>,
8816 passes: &mut Vec<Pass>,
8817 target_stack: &mut Vec<PassTarget>,
8818 flatten_stack: &mut Vec<FlattenRecord>,
8819 id_head: &mut u32,
8820 pass_id_head: &mut u64,
8821 ids_used: &mut Vec<u32>,
8822 encoder: &mut wgpu::CommandEncoder,
8823 ) {
8824 let map =
8828 Transform::compose_projective(&top.projective_matrix(), &node.projective_matrix());
8829 let scr = scissor_stack.last().copied().unwrap_or(*root_clip_rect);
8830 let max_dimension = self.device.limits().max_texture_dimension_2d as f32;
8831 if !scr.w.is_finite()
8832 || !scr.h.is_finite()
8833 || scr.w < 1.0
8834 || scr.h < 1.0
8835 || scr.w > max_dimension
8836 || scr.h > max_dimension
8837 {
8838 return;
8839 }
8840 let w = scr.w.ceil();
8841 let h = scr.h.ceil();
8842 let layer_rect = repose_core::Rect {
8843 x: scr.x,
8844 y: scr.y,
8845 w,
8846 h,
8847 };
8848 if ids_used.len() >= MAX_TRANSIENT_GRAPHICS_LAYERS {
8849 return;
8850 }
8851 let layer_id = *id_head;
8852 *id_head = id_head.wrapping_add(1);
8853 ids_used.push(layer_id);
8854
8855 let stack_len = transform_stack.len();
8856 transform_stack.push(top);
8860 transform_stack.push(Transform::translate(-layer_rect.x, -layer_rect.y));
8861
8862 let saved_scissor_stack = std::mem::replace(
8863 scissor_stack,
8864 vec![repose_core::Rect {
8865 x: 0.0,
8866 y: 0.0,
8867 w,
8868 h,
8869 }],
8870 );
8871 let saved_root = std::mem::replace(
8872 root_clip_rect,
8873 repose_core::Rect {
8874 x: 0.0,
8875 y: 0.0,
8876 w,
8877 h,
8878 },
8879 );
8880 let saved_size = std::mem::replace(current_target_size, (w, h));
8881 let prev_target = current_pass.target;
8882 let saved_active_scissor = current_pass.active_scissor;
8883 let saved_clips = std::mem::take(active_clips);
8884 let layer_pass_id = *pass_id_head;
8885 *pass_id_head += 1;
8886 let mut layer_pass = Pass {
8887 id: layer_pass_id,
8888 target: PassTarget::Layer(layer_id),
8889 initial_scissor: (0, 0, w as u32, h as u32),
8890 active_scissor: Some((0, 0, w as u32, h as u32)),
8891 clear_color: Some([0.0, 0.0, 0.0, 0.0]),
8892 cmds: Vec::new(),
8893 };
8894 let layer_clips = self.replay_active_clips(
8895 &saved_clips,
8896 &top,
8897 (layer_rect.x, layer_rect.y),
8898 (w, h),
8899 &mut layer_pass,
8900 encoder,
8901 );
8902 *active_clips = layer_clips;
8903 let saved = std::mem::replace(current_pass, layer_pass);
8904 passes.push(saved);
8905 target_stack.push(prev_target);
8906 self.get_or_create_layer(layer_id, w as u32, h as u32, layer_rect, true);
8907 *current_target_size = (w, h);
8908 flatten_stack.push(FlattenRecord {
8909 stack_len,
8910 layer_id,
8911 map,
8912 layer_rect,
8913 saved_scissor_stack,
8914 saved_root,
8915 saved_size,
8916 saved_active_scissor,
8917 saved_clips,
8918 });
8919 }
8920
8921 #[allow(clippy::too_many_arguments)]
8924 fn pop_perspective_layer(
8925 &mut self,
8926 rec: FlattenRecord,
8927 scissor_stack: &mut Vec<repose_core::Rect>,
8928 root_clip_rect: &mut repose_core::Rect,
8929 current_target_size: &mut (f32, f32),
8930 current_pass: &mut Pass,
8931 active_clips: &mut Vec<ActiveClip>,
8932 passes: &mut Vec<Pass>,
8933 target_stack: &mut Vec<PassTarget>,
8934 pass_id_head: &mut u64,
8935 encoder: &mut wgpu::CommandEncoder,
8936 ) {
8937 *scissor_stack = rec.saved_scissor_stack;
8938 *root_clip_rect = rec.saved_root;
8939 *current_target_size = rec.saved_size;
8940 *active_clips = rec.saved_clips;
8941 let resumed_pass_id = *pass_id_head;
8942 *pass_id_head += 1;
8943 let saved = std::mem::replace(
8944 current_pass,
8945 Pass {
8946 id: resumed_pass_id,
8947 target: target_stack.pop().unwrap_or(PassTarget::Surface),
8948 initial_scissor: rec.saved_active_scissor.unwrap_or((0, 0, 1, 1)),
8949 active_scissor: rec.saved_active_scissor,
8950 clear_color: None,
8951 cmds: Vec::new(),
8952 },
8953 );
8954 passes.push(saved);
8955
8956 let Some(layer) = self.layer_pool.get(&rec.layer_id) else {
8957 return;
8958 };
8959 let uv_u1 = layer.rect_px.2 / layer.width.max(1) as f32;
8960 let uv_v1 = layer.rect_px.3 / layer.height.max(1) as f32;
8961 let (tw, th) = rec.saved_size;
8962 let Some(inst) = make_projective_instance(
8963 &rec.map,
8964 rec.layer_rect,
8965 tw,
8966 th,
8967 [0.0, 0.0, uv_u1, uv_v1],
8968 1.0,
8969 [1.0, 1.0, 1.0],
8970 ) else {
8971 return;
8974 };
8975 debug_assert_eq!(std::mem::size_of::<ProjectiveInstance>(), 80);
8976 if self
8977 .projective_ring
8978 .grow_to_fit(
8979 &self.device,
8980 encoder,
8981 std::mem::size_of::<ProjectiveInstance>() as u64,
8982 )
8983 .is_err()
8984 {
8985 return;
8986 }
8987 let bytes = bytemuck::bytes_of(&inst);
8988 let Ok(off) = self.projective_ring.alloc_write(&self.queue, bytes) else {
8989 return;
8990 };
8991 current_pass.cmds.push(Cmd::CompositeProjective {
8992 off,
8993 cnt: 1,
8994 layer_id: rec.layer_id,
8995 blend: BlendMode::Alpha,
8996 });
8997 }
8998
8999 fn mesh_cache_key(mesh: &Arc<repose_core::VectorMeshData>) -> MeshCacheKey {
9000 MeshCacheKey {
9001 source: Arc::as_ptr(mesh) as usize,
9002 index: 0,
9003 kind: 1,
9004 vertex_len: mesh.vertices.len(),
9005 index_len: mesh.indices.len(),
9006 }
9007 }
9008
9009 fn overlay_mesh_cache_key(
9010 meshes: &Arc<[repose_core::VectorMeshData]>,
9011 index: usize,
9012 ) -> MeshCacheKey {
9013 let mesh = &meshes[index];
9014 MeshCacheKey {
9015 source: meshes.as_ptr() as usize,
9016 index,
9017 kind: 2,
9018 vertex_len: mesh.vertices.len(),
9019 index_len: mesh.indices.len(),
9020 }
9021 }
9022
9023 fn mesh_owner_matches(owner: &MeshOwner, other: &MeshOwner) -> bool {
9024 match (owner, other) {
9025 (MeshOwner::Object(a), MeshOwner::Object(b)) => Arc::ptr_eq(a, b),
9026 (MeshOwner::Overlay(a), MeshOwner::Overlay(b)) => Arc::ptr_eq(a, b),
9027 (MeshOwner::Shape(a, ap, aw), MeshOwner::Shape(b, bp, bw)) => {
9028 ap == bp && aw == bw && Arc::ptr_eq(a, b)
9029 }
9030 _ => false,
9031 }
9032 }
9033
9034 fn evict_mesh_cache(&mut self) -> bool {
9035 let victim = self
9036 .mesh_cache
9037 .iter()
9038 .filter(|(_, entry)| entry.last_used_frame != self.frame_index)
9039 .min_by_key(|(_, entry)| entry.last_touch_frame)
9040 .map(|(key, _)| *key);
9041 let Some(victim) = victim else {
9042 return false;
9043 };
9044 let Some(entry) = self.mesh_cache.remove(&victim) else {
9045 return false;
9046 };
9047 self.mesh_cache_bytes_total = self.mesh_cache_bytes_total.saturating_sub(entry.gpu.bytes);
9048 true
9049 }
9050
9051 fn reserve_mesh_cache(&mut self, bytes: u64) -> bool {
9052 while self.mesh_cache.len() >= MAX_MESH_CACHE_ENTRIES
9053 || self.mesh_cache_bytes_total.saturating_add(bytes) > MAX_MESH_CACHE_BYTES
9054 {
9055 if !self.evict_mesh_cache() {
9056 return false;
9057 }
9058 }
9059 true
9060 }
9061
9062 fn reserve_mesh_gpu_budget(&mut self, bytes: u64) -> bool {
9063 while self.gpu_bytes_total().saturating_add(bytes) > self.gpu_budget_bytes {
9064 if !self.evict_mesh_cache() {
9065 return false;
9066 }
9067 }
9068 true
9069 }
9070
9071 fn upload_mesh_geometry_with_owner(
9072 &mut self,
9073 mesh: &repose_core::VectorMeshData,
9074 key: MeshCacheKey,
9075 owner: MeshOwner,
9076 ) -> Option<MeshGpu> {
9077 let touch = self.next_cache_touch();
9078 let cached = self
9079 .mesh_cache
9080 .get(&key)
9081 .filter(|entry| Self::mesh_owner_matches(&entry.owner, &owner))
9082 .map(|entry| entry.gpu.clone());
9083 if let Some(gpu) = cached {
9084 if let Some(entry) = self.mesh_cache.get_mut(&key) {
9085 entry.last_used_frame = self.frame_index;
9086 entry.last_touch_frame = touch;
9087 }
9088 return Some(gpu);
9089 }
9090 if let Some(entry) = self.mesh_cache.remove(&key) {
9091 self.mesh_cache_bytes_total =
9092 self.mesh_cache_bytes_total.saturating_sub(entry.gpu.bytes);
9093 }
9094 if mesh.vertices.is_empty() || mesh.indices.is_empty() {
9095 log::warn!("vector mesh has no geometry");
9096 return None;
9097 }
9098 if !mesh.indices.len().is_multiple_of(3) {
9099 log::warn!("vector mesh index count is not a triangle list");
9100 return None;
9101 }
9102 let vertex_count = u32::try_from(mesh.vertices.len()).ok()?;
9103 let index_count = u32::try_from(mesh.indices.len()).ok()?;
9104 if mesh.indices.iter().any(|&index| index >= vertex_count) {
9105 log::warn!("vector mesh index is outside its vertex buffer");
9106 return None;
9107 }
9108 if mesh.vertices.iter().any(|vertex| {
9109 vertex.pos.iter().any(|value| !value.is_finite())
9110 || vertex.color.iter().any(|value| !value.is_finite())
9111 || vertex.uv.iter().any(|value| !value.is_finite())
9112 }) {
9113 log::warn!("vector mesh contains non-finite vertex data");
9114 return None;
9115 }
9116 let verts: Vec<MeshVertex> = mesh
9117 .vertices
9118 .iter()
9119 .map(|v| MeshVertex {
9120 pos: v.pos,
9121 color: v.color,
9122 uv: v.uv,
9123 })
9124 .collect();
9125 let vbytes = bytemuck::cast_slice(&verts);
9126 let ibytes = bytemuck::cast_slice(&mesh.indices[..]);
9127 let bytes = u64::try_from(vbytes.len())
9128 .ok()?
9129 .checked_add(u64::try_from(ibytes.len()).ok()?)?;
9130 let max_buffer_size = self.device.limits().max_buffer_size;
9131 if vbytes.len() as u64 > max_buffer_size || ibytes.len() as u64 > max_buffer_size {
9132 return None;
9133 }
9134 let cacheable = bytes <= MAX_MESH_CACHE_BYTES
9135 && self.reserve_mesh_cache(bytes)
9136 && self.reserve_mesh_gpu_budget(bytes);
9137 let vertices = self.device.create_buffer(&wgpu::BufferDescriptor {
9138 label: Some("vector mesh vertices"),
9139 size: vbytes.len().max(4) as u64,
9140 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
9141 mapped_at_creation: false,
9142 });
9143 let indices = self.device.create_buffer(&wgpu::BufferDescriptor {
9144 label: Some("vector mesh indices"),
9145 size: ibytes.len().max(4) as u64,
9146 usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
9147 mapped_at_creation: false,
9148 });
9149 self.queue.write_buffer(&vertices, 0, vbytes);
9150 self.queue.write_buffer(&indices, 0, ibytes);
9151 let gpu = MeshGpu {
9152 vertices,
9153 indices,
9154 vertex_count,
9155 index_count,
9156 bytes,
9157 };
9158 if cacheable {
9159 let touch = self.next_cache_touch();
9160 self.mesh_cache.insert(
9161 key,
9162 MeshCacheEntry {
9163 owner,
9164 gpu: gpu.clone(),
9165 last_used_frame: self.frame_index,
9166 last_touch_frame: touch,
9167 },
9168 );
9169 self.mesh_cache_bytes_total = self.mesh_cache_bytes_total.saturating_add(bytes);
9170 }
9171 Some(gpu)
9172 }
9173
9174 fn upload_mesh_geometry(&mut self, mesh: &Arc<repose_core::VectorMeshData>) -> Option<MeshGpu> {
9175 self.upload_mesh_geometry_with_owner(
9176 mesh,
9177 Self::mesh_cache_key(mesh),
9178 MeshOwner::Object(mesh.clone()),
9179 )
9180 }
9181
9182 fn upload_shape_mesh(
9186 &mut self,
9187 path: &Arc<ShapePath>,
9188 ppp: f32,
9189 stroke: Option<Px>,
9190 ) -> Option<MeshGpu> {
9191 let width_bits = stroke.map(|w| w.0.to_bits());
9192 let ppp_bits = ppp.to_bits();
9193 let source = Arc::as_ptr(path) as usize;
9194 let mut hasher = std::collections::hash_map::DefaultHasher::new();
9195 ppp_bits.hash(&mut hasher);
9196 width_bits.hash(&mut hasher);
9197 let index = hasher.finish() as usize;
9198 let kind = if stroke.is_some() { 4 } else { 3 };
9199 let owner = MeshOwner::Shape(path.clone(), ppp_bits, width_bits);
9200 if let Some((key, cached)) = self
9201 .mesh_cache
9202 .iter()
9203 .find(|(key, entry)| {
9204 key.source == source
9205 && key.index == index
9206 && key.kind == kind
9207 && Self::mesh_owner_matches(&entry.owner, &owner)
9208 })
9209 .map(|(key, entry)| (*key, entry.gpu.clone()))
9210 {
9211 let touch = self.next_cache_touch();
9212 if let Some(entry) = self.mesh_cache.get_mut(&key) {
9213 entry.last_used_frame = self.frame_index;
9214 entry.last_touch_frame = touch;
9215 }
9216 return Some(cached);
9217 }
9218 let mesh = Arc::new(tessellate_shape_path(path, ppp, stroke)?);
9219 let key = MeshCacheKey {
9220 source,
9221 index,
9222 kind,
9223 vertex_len: mesh.vertices.len(),
9224 index_len: mesh.indices.len(),
9225 };
9226 self.upload_mesh_geometry_with_owner(&mesh, key, owner)
9227 }
9228
9229 fn upload_overlay_mesh(
9230 &mut self,
9231 meshes: &Arc<[repose_core::VectorMeshData]>,
9232 index: usize,
9233 ) -> Option<MeshGpu> {
9234 self.upload_mesh_geometry_with_owner(
9235 &meshes[index],
9236 Self::overlay_mesh_cache_key(meshes, index),
9237 MeshOwner::Overlay(meshes.clone()),
9238 )
9239 }
9240
9241 fn alloc_mesh_uniform(&mut self, u: MeshUniform) -> Option<u64> {
9242 let size = std::mem::size_of::<MeshUniform>() as u64;
9243 let next = self
9244 .mesh_uniform_head
9245 .checked_add(self.mesh_uniform_alignment)?;
9246 if next > self.mesh_uniform_cap || next > u64::from(u32::MAX) {
9247 log::warn!("mesh uniform buffer exhausted; remaining meshes skipped");
9248 return None;
9249 }
9250 let slot = self.mesh_uniform_head;
9251 if slot.checked_add(size)? > self.mesh_uniform_cap {
9252 return None;
9253 }
9254 self.queue
9255 .write_buffer(&self.mesh_uniform_buf, slot, bytemuck::bytes_of(&u));
9256 self.mesh_uniform_head = next;
9257 Some(slot)
9258 }
9259
9260 fn alloc_mesh_instances(&mut self, affines: &[[f32; 6]]) -> Option<(u64, u32)> {
9265 let count = u32::try_from(affines.len()).ok()?;
9266 if count == 0 {
9267 return None;
9268 }
9269 let stride = std::mem::size_of::<MeshInstance>() as u64;
9270 let bytes = u64::from(count) * stride;
9271 let slot = self.mesh_instance_head;
9272 let next = slot.checked_add(bytes)?;
9273 if next > self.mesh_instance_cap {
9274 log::warn!("mesh instance buffer exhausted; remaining meshes skipped");
9275 return None;
9276 }
9277 let mut staging = Vec::with_capacity(affines.len());
9278 for affine in affines {
9279 staging.push(MeshInstance::new(*affine));
9280 }
9281 self.queue.write_buffer(
9282 &self.mesh_instance_buf,
9283 slot,
9284 bytemuck::cast_slice(&staging),
9285 );
9286 self.mesh_instance_head = next;
9287 Some((slot, count))
9288 }
9289
9290 #[allow(clippy::too_many_arguments)]
9307 fn emit_isolated_blend_source(
9308 &mut self,
9309 bounds: repose_core::Rect,
9310 blend: repose_core::BlendMode,
9311 color: [f32; 4],
9312 color_filter: ColorFilter,
9313 current_transform: &repose_core::Transform,
9314 current_pass: &mut Pass,
9315 active_clips: &[ActiveClip],
9316 passes: &mut Vec<Pass>,
9317 id_head: &mut u32,
9318 pass_id_head: &mut u64,
9319 ids_used: &mut Vec<u32>,
9320 scissor: (u32, u32, u32, u32),
9321 encoder: &mut wgpu::CommandEncoder,
9322 fb_w: f32,
9323 fb_h: f32,
9324 emit_source: impl FnOnce(
9325 &mut Self,
9326 &mut Pass,
9327 &repose_core::Transform,
9328 f32,
9329 f32,
9330 &mut wgpu::CommandEncoder,
9331 ),
9332 ) -> Option<Cmd> {
9333 if scissor.2 == 0 || scissor.3 == 0 || active_clips.iter().any(ActiveClip::blocked) {
9334 return None;
9335 }
9336 let parent_target = current_pass.target;
9337 let (parent_w, parent_h) = match parent_target {
9338 PassTarget::Surface => (fb_w, fb_h),
9339 PassTarget::Layer(id) => match self.layer_pool.get(&id) {
9340 Some(layer) => (layer.width as f32, layer.height as f32),
9341 None => return None,
9342 },
9343 };
9344 let local_rect = intersect(
9345 bounds,
9346 repose_core::Rect {
9347 x: 0.0,
9348 y: 0.0,
9349 w: parent_w,
9350 h: parent_h,
9351 },
9352 );
9353 if !local_rect.x.is_finite()
9354 || !local_rect.y.is_finite()
9355 || !local_rect.w.is_finite()
9356 || !local_rect.h.is_finite()
9357 || local_rect.w <= 0.0
9358 || local_rect.h <= 0.0
9359 || local_rect.w > self.device.limits().max_texture_dimension_2d as f32
9360 || local_rect.h > self.device.limits().max_texture_dimension_2d as f32
9361 {
9362 return None;
9363 }
9364 let layer_rect = repose_core::Rect {
9365 x: local_rect.x.floor(),
9366 y: local_rect.y.floor(),
9367 w: (local_rect.x + local_rect.w).ceil() - local_rect.x.floor(),
9368 h: (local_rect.y + local_rect.h).ceil() - local_rect.y.floor(),
9369 };
9370 let w = layer_rect.w;
9371 let h = layer_rect.h;
9372 let local_rect = layer_rect;
9373 if ids_used.len() >= MAX_TRANSIENT_GRAPHICS_LAYERS {
9374 return None;
9375 }
9376 let layer_id = *id_head;
9377 *id_head = id_head.wrapping_add(1);
9378 ids_used.push(layer_id);
9379
9380 let snapshot_format = match parent_target {
9384 PassTarget::Surface if self.working_space => wgpu::TextureFormat::Rgba16Float,
9385 PassTarget::Surface => self.output_format,
9386 PassTarget::Layer(_) => self.layer_target_format(),
9387 };
9388 if !self.alloc_blend_snapshot(layer_id, w as u32, h as u32, snapshot_format) {
9389 log::warn!("blend snapshot budget exhausted; blend skipped");
9390 return None;
9391 }
9392 let source_pass_id = *pass_id_head;
9393 *pass_id_head += 1;
9394 let resumed_pass_id = *pass_id_head;
9395 *pass_id_head += 1;
9396 self.blend_copies.push(BlendCopy {
9397 pass_id: resumed_pass_id,
9398 blend_id: layer_id,
9399 target: parent_target,
9400 region: layer_rect,
9401 });
9402
9403 let mut layer_pass = Pass {
9407 id: source_pass_id,
9408 target: PassTarget::Layer(layer_id),
9409 initial_scissor: (0, 0, w as u32, h as u32),
9410 active_scissor: Some((0, 0, w as u32, h as u32)),
9411 clear_color: Some([0.0, 0.0, 0.0, 0.0]),
9412 cmds: Vec::new(),
9413 };
9414 self.replay_active_clips(
9415 active_clips,
9416 current_transform,
9417 (local_rect.x, local_rect.y),
9418 (w, h),
9419 &mut layer_pass,
9420 encoder,
9421 );
9422 self.get_or_create_layer(layer_id, w as u32, h as u32, layer_rect, true);
9423 let shift = repose_core::Transform::translate(-local_rect.x, -local_rect.y);
9424 let local = current_transform.combine(&shift);
9425 emit_source(self, &mut layer_pass, &local, w, h, encoder);
9426 let saved = std::mem::replace(
9427 current_pass,
9428 Pass {
9429 id: resumed_pass_id,
9430 target: parent_target,
9431 initial_scissor: scissor,
9432 active_scissor: Some(scissor),
9433 clear_color: None,
9434 cmds: Vec::new(),
9435 },
9436 );
9437 passes.push(layer_pass);
9438 passes.push(saved);
9439
9440 let ndc = {
9444 let cx = local_rect.x + local_rect.w * 0.5;
9445 let cy = local_rect.y + local_rect.h * 0.5;
9446 let ndc_cx = (cx / parent_w) * 2.0 - 1.0;
9447 let ndc_cy = 1.0 - (cy / parent_h) * 2.0;
9448 let ndc_w = (local_rect.w / parent_w) * 2.0;
9449 let ndc_h = (local_rect.h / parent_h) * 2.0;
9450 [ndc_cx, ndc_cy, ndc_w, ndc_h]
9451 };
9452 let (filter_color, filter_mode) = color_filter_fields(color_filter);
9453 let inst = BlendInstance {
9454 xywh: ndc,
9455 uv: [0.0, 0.0, 1.0, 1.0],
9456 color,
9457 fwd_mat: [1.0, 0.0, 0.0, 1.0],
9458 filter_color,
9459 mode: blend.shader_mode(),
9460 filter_mode,
9461 };
9462 if self
9463 .blend_ring
9464 .grow_to_fit(
9465 &self.device,
9466 encoder,
9467 std::mem::size_of::<BlendInstance>() as u64,
9468 )
9469 .is_err()
9470 {
9471 return None;
9472 }
9473 let bytes = bytemuck::bytes_of(&inst);
9474 let Ok(off) = self.blend_ring.alloc_write(&self.queue, bytes) else {
9475 return None;
9476 };
9477 Some(Cmd::BlendLayer {
9478 off,
9479 cnt: 1,
9480 src_layer: layer_id,
9481 dst_layer: Some(layer_id),
9482 parent: parent_target,
9483 scissor,
9484 })
9485 }
9486
9487 #[allow(clippy::too_many_arguments)]
9491 fn emit_isolated_blend(
9492 &mut self,
9493 mesh: std::sync::Arc<repose_core::VectorMeshData>,
9494 transform: [f32; 6],
9495 paint: repose_core::PaintDesc,
9496 blend: repose_core::BlendMode,
9497 color: [f32; 4],
9498 color_filter: ColorFilter,
9499 current_transform: &repose_core::Transform,
9500 current_pass: &mut Pass,
9501 active_clips: &[ActiveClip],
9502 passes: &mut Vec<Pass>,
9503 id_head: &mut u32,
9504 pass_id_head: &mut u64,
9505 ids_used: &mut Vec<u32>,
9506 scissor: (u32, u32, u32, u32),
9507 encoder: &mut wgpu::CommandEncoder,
9508 fb_w: f32,
9509 fb_h: f32,
9510 ) {
9511 let affine = combine_mesh_affine(current_transform, transform);
9512 let bounds = mesh_aabb(&mesh, affine);
9513 let cmd = self.emit_isolated_blend_source(
9514 bounds,
9515 blend,
9516 color,
9517 color_filter,
9518 current_transform,
9519 current_pass,
9520 active_clips,
9521 passes,
9522 id_head,
9523 pass_id_head,
9524 ids_used,
9525 scissor,
9526 encoder,
9527 fb_w,
9528 fb_h,
9529 |slf, pass, local, _w, _h, _encoder| {
9530 slf.emit_vector_mesh(
9531 local,
9532 &mesh,
9533 transform,
9534 &paint,
9535 repose_core::BlendMode::Alpha,
9536 &mut pass.cmds,
9537 );
9538 },
9539 );
9540 if let Some(cmd) = cmd {
9541 current_pass.cmds.push(cmd);
9542 }
9543 }
9544
9545 #[allow(clippy::too_many_arguments)]
9551 fn emit_isolated_image(
9552 &mut self,
9553 draw_rect: repose_core::Rect,
9554 handle: u64,
9555 uv_rect: [f32; 4],
9556 tint: repose_core::Color,
9557 tile: bool,
9558 filter: ImageFilter,
9559 blend: repose_core::BlendMode,
9560 color: [f32; 4],
9561 color_filter: ColorFilter,
9562 current_transform: &repose_core::Transform,
9563 current_pass: &mut Pass,
9564 active_clips: &[ActiveClip],
9565 passes: &mut Vec<Pass>,
9566 id_head: &mut u32,
9567 pass_id_head: &mut u64,
9568 ids_used: &mut Vec<u32>,
9569 scissor: (u32, u32, u32, u32),
9570 encoder: &mut wgpu::CommandEncoder,
9571 fb_w: f32,
9572 fb_h: f32,
9573 ) {
9574 let bounds = affine_aabb(current_transform, &draw_rect);
9575 let cmd = self.emit_isolated_blend_source(
9576 bounds,
9577 blend,
9578 color,
9579 color_filter,
9580 current_transform,
9581 current_pass,
9582 active_clips,
9583 passes,
9584 id_head,
9585 pass_id_head,
9586 ids_used,
9587 scissor,
9588 encoder,
9589 fb_w,
9590 fb_h,
9591 |slf, pass, local, w, h, encoder| {
9592 let (ndc_center, fwd_mat) = rect_to_instance_ndc(draw_rect, local, w, h);
9593 let inst = GlyphInstance {
9594 xywh: ndc_center,
9595 uv: uv_rect,
9596 color: tint.to_linear(),
9597 fwd_mat,
9598 };
9599 if let Some((off, _)) =
9600 slf.glyph_color
9601 .upload(&slf.device, &slf.queue, encoder, &[inst])
9602 {
9603 pass.cmds.push(Cmd::ImageRgba {
9604 off,
9605 cnt: 1,
9606 handle,
9607 filter,
9608 tile,
9609 blend: repose_core::BlendMode::Alpha,
9610 });
9611 }
9612 },
9613 );
9614 if let Some(cmd) = cmd {
9615 current_pass.cmds.push(cmd);
9616 }
9617 }
9618
9619 fn recycle_blend_snapshot(&mut self, snapshot: BlendSnapshot) {
9620 let key = snapshot.key;
9621 if let Some(old) = self.blend_snapshot_pool.insert(key, snapshot) {
9622 self.blend_snapshot_bytes_total =
9623 self.blend_snapshot_bytes_total.saturating_sub(old.bytes);
9624 }
9625 while self.blend_snapshot_bytes_total > MAX_BLEND_SNAPSHOT_BYTES
9626 || self.blend_snapshot_pool.len() > MAX_BLEND_SNAPSHOT_POOL_ENTRIES
9627 {
9628 let Some(victim) = self.blend_snapshot_pool.keys().next().copied() else {
9629 break;
9630 };
9631 if let Some(snapshot) = self.blend_snapshot_pool.remove(&victim) {
9632 self.blend_snapshot_bytes_total = self
9633 .blend_snapshot_bytes_total
9634 .saturating_sub(snapshot.bytes);
9635 }
9636 }
9637 }
9638
9639 fn recycle_blend_snapshots(&mut self) {
9640 for (_, snapshot) in std::mem::take(&mut self.blend_snapshots) {
9641 self.recycle_blend_snapshot(snapshot);
9642 }
9643 }
9644
9645 fn alloc_blend_snapshot(
9646 &mut self,
9647 layer_id: u32,
9648 w: u32,
9649 h: u32,
9650 format: wgpu::TextureFormat,
9651 ) -> bool {
9652 let key = BlendSnapshotKey {
9653 format,
9654 width: w,
9655 height: h,
9656 };
9657 if self
9658 .blend_snapshots
9659 .get(&layer_id)
9660 .is_some_and(|snapshot| snapshot.key == key)
9661 {
9662 return true;
9663 }
9664 if w == 0 || h == 0 {
9665 return false;
9666 }
9667 if let Some(old) = self.blend_snapshots.remove(&layer_id) {
9668 self.recycle_blend_snapshot(old);
9669 }
9670 if let Some(snapshot) = self.blend_snapshot_pool.remove(&key) {
9671 self.blend_snapshots.insert(layer_id, snapshot);
9672 return true;
9673 }
9674 let Ok(bytes) = texture_storage_bytes(format, w, h) else {
9675 return false;
9676 };
9677 if bytes > MAX_BLEND_SNAPSHOT_BYTES {
9678 return false;
9679 }
9680 while self.blend_snapshot_bytes_total.saturating_add(bytes) > MAX_BLEND_SNAPSHOT_BYTES
9681 || self.gpu_bytes_total().saturating_add(bytes) > self.gpu_budget_bytes
9682 {
9683 let Some(victim) = self.blend_snapshot_pool.keys().next().copied() else {
9684 return false;
9685 };
9686 let Some(snapshot) = self.blend_snapshot_pool.remove(&victim) else {
9687 return false;
9688 };
9689 self.blend_snapshot_bytes_total = self
9690 .blend_snapshot_bytes_total
9691 .saturating_sub(snapshot.bytes);
9692 }
9693 let tex = self.device.create_texture(&wgpu::TextureDescriptor {
9694 label: Some("blend backdrop snapshot"),
9695 size: wgpu::Extent3d {
9696 width: w,
9697 height: h,
9698 depth_or_array_layers: 1,
9699 },
9700 mip_level_count: 1,
9701 sample_count: 1,
9702 dimension: wgpu::TextureDimension::D2,
9703 format,
9704 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
9705 view_formats: &[],
9706 });
9707 let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
9708 let bind = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
9709 label: Some("blend snapshot bind"),
9710 layout: &self.image_bind_layout_rgba,
9711 entries: &[
9712 wgpu::BindGroupEntry {
9713 binding: 0,
9714 resource: wgpu::BindingResource::TextureView(&view),
9715 },
9716 wgpu::BindGroupEntry {
9717 binding: 1,
9718 resource: wgpu::BindingResource::Sampler(&self.layer_sampler),
9719 },
9720 ],
9721 });
9722 self.blend_snapshot_bytes_total = self.blend_snapshot_bytes_total.saturating_add(bytes);
9723 self.blend_snapshots.insert(
9724 layer_id,
9725 BlendSnapshot {
9726 key,
9727 texture: tex,
9728 bind,
9729 bytes,
9730 },
9731 );
9732 true
9733 }
9734
9735 fn remove_blend_snapshot(&mut self, layer_id: u32) {
9736 if let Some(snapshot) = self.blend_snapshots.remove(&layer_id) {
9737 self.recycle_blend_snapshot(snapshot);
9738 }
9739 }
9740
9741 fn blend_snapshot_texture(&self, layer_id: u32) -> Option<wgpu::Texture> {
9742 self.blend_snapshots
9743 .get(&layer_id)
9744 .map(|s| s.texture.clone())
9745 }
9746
9747 #[allow(clippy::too_many_arguments)]
9748 fn emit_vector_mesh(
9749 &mut self,
9750 current_transform: &Transform,
9751 mesh: &Arc<repose_core::VectorMeshData>,
9752 transform: [f32; 6],
9753 paint: &repose_core::PaintDesc,
9754 blend: repose_core::BlendMode,
9755 cmds: &mut Vec<Cmd>,
9756 ) {
9757 self.emit_vector_mesh_affines(current_transform, mesh, &[transform], paint, blend, cmds);
9758 }
9759
9760 #[allow(clippy::too_many_arguments)]
9765 fn emit_vector_mesh_affines(
9766 &mut self,
9767 current_transform: &Transform,
9768 mesh: &Arc<repose_core::VectorMeshData>,
9769 transforms: &[[f32; 6]],
9770 paint: &repose_core::PaintDesc,
9771 blend: repose_core::BlendMode,
9772 cmds: &mut Vec<Cmd>,
9773 ) {
9774 let Some(mesh_gpu) = self.upload_mesh_geometry(mesh) else {
9775 return;
9776 };
9777 let Some(uoff) = self.alloc_mesh_uniform(mesh_uniform_from_paint(paint)) else {
9778 return;
9779 };
9780 let affines: Vec<[f32; 6]> = transforms
9781 .iter()
9782 .map(|transform| combine_mesh_affine(current_transform, *transform))
9783 .collect();
9784 let Some((ioff, icnt)) = self.alloc_mesh_instances(&affines) else {
9785 return;
9786 };
9787 cmds.push(Cmd::VectorMesh {
9788 mesh: mesh_gpu,
9789 uoff,
9790 ioff,
9791 icnt,
9792 blend,
9793 });
9794 }
9795
9796 fn emit_shape_mesh(
9800 &mut self,
9801 mesh: MeshGpu,
9802 current_transform: &Transform,
9803 offset: (f32, f32),
9804 paint: &repose_core::PaintDesc,
9805 cmds: &mut Vec<Cmd>,
9806 ) {
9807 let Some(uoff) = self.alloc_mesh_uniform(mesh_uniform_from_paint(paint)) else {
9808 return;
9809 };
9810 let affine =
9811 combine_mesh_affine(current_transform, [1.0, 0.0, 0.0, 1.0, offset.0, offset.1]);
9812 let Some((ioff, icnt)) = self.alloc_mesh_instances(&[affine]) else {
9813 return;
9814 };
9815 cmds.push(Cmd::VectorMesh {
9816 mesh,
9817 uoff,
9818 ioff,
9819 icnt,
9820 blend: repose_core::BlendMode::Alpha,
9821 });
9822 }
9823
9824 fn touch_callback_scope(&mut self, scope: CallbackScopeKey) {
9825 self.callback_scope_clock = self.callback_scope_clock.wrapping_add(1);
9826 let tick = self.callback_scope_clock;
9827 self.callback_scope_uses.insert(
9828 scope,
9829 CallbackScopeUse {
9830 tick,
9831 frame: self.frame_index,
9832 },
9833 );
9834 }
9835
9836 fn remove_callback_scope(&mut self, scope: &CallbackScopeKey) {
9837 self.callback_scoped_resources.remove(scope);
9838 self.callback_scope_uses.remove(scope);
9839 self.callback_scope_payloads.remove(scope);
9840 }
9841
9842 fn evict_callback_scope(&mut self, protected: &HashSet<CallbackScopeKey>) -> bool {
9843 let candidate = self
9844 .callback_scoped_resources
9845 .keys()
9846 .filter(|scope| !protected.contains(*scope))
9847 .min_by_key(|scope| {
9848 self.callback_scope_uses
9849 .get(scope)
9850 .map(|usage| usage.tick)
9851 .unwrap_or(0)
9852 })
9853 .cloned();
9854 let Some(scope) = candidate else {
9855 return false;
9856 };
9857 self.remove_callback_scope(&scope);
9858 true
9859 }
9860
9861 fn prune_callback_scopes(&mut self) {
9862 let current_frame = self.frame_index;
9863 let mut dead: Vec<(CallbackScopeKey, u64)> = self
9864 .callback_scope_uses
9865 .iter()
9866 .filter_map(|(scope, usage)| {
9867 let payload_dead = self
9868 .callback_scope_payloads
9869 .get(scope)
9870 .is_none_or(|weak| weak.upgrade().is_none());
9871 (payload_dead && !scope.callback.reusable).then(|| (scope.clone(), usage.tick))
9872 })
9873 .collect();
9874 dead.sort_by_key(|(_, tick)| *tick);
9875 for (scope, _) in dead {
9876 self.remove_callback_scope(&scope);
9877 }
9878
9879 if self.callback_scoped_resources.len() <= MAX_CALLBACK_SCOPES {
9880 return;
9881 }
9882 let mut inactive: Vec<(CallbackScopeKey, u64)> = self
9883 .callback_scope_uses
9884 .iter()
9885 .filter(|(_, usage)| usage.frame != current_frame)
9886 .map(|(scope, usage)| (scope.clone(), usage.tick))
9887 .collect();
9888 inactive.sort_by_key(|(_, tick)| *tick);
9889 for (scope, _) in inactive {
9890 if self.callback_scoped_resources.len() <= MAX_CALLBACK_SCOPES {
9891 break;
9892 }
9893 self.remove_callback_scope(&scope);
9894 }
9895 }
9896
9897 pub fn begin_frame(&mut self) -> anyhow::Result<()> {
9898 if self.frame_active {
9899 self.last_render_error = Some("renderer frame is already active".into());
9900 anyhow::bail!("renderer frame is already active");
9901 }
9902 self.last_render_error = None;
9903 self.frame_active = true;
9904 self.frame_index = self.frame_index.wrapping_add(1);
9905 self.apply_atlas_pending();
9906 self.slug_cache.next_frame();
9907 if let Some(composite) = self.callback_resources.get_mut::<DepthComposite>() {
9908 composite.begin_frame();
9909 }
9910 for resources in self.callback_scoped_resources.values_mut() {
9911 if let Some(composite) = resources.get_mut::<DepthComposite>() {
9912 composite.begin_frame();
9913 }
9914 }
9915 Ok(())
9916 }
9917
9918 pub fn end_frame(&mut self) {
9919 if !self.frame_active {
9920 return;
9921 }
9922 if let Some(composite) = self.callback_resources.get_mut::<DepthComposite>() {
9923 composite.end_frame();
9924 }
9925 for resources in self.callback_scoped_resources.values_mut() {
9926 if let Some(composite) = resources.get_mut::<DepthComposite>() {
9927 composite.end_frame();
9928 }
9929 }
9930 self.prune_callback_scopes();
9931 self.evict_unused_images();
9932 self.frame_active = false;
9933 }
9934
9935 pub fn last_render_error(&self) -> Option<&str> {
9936 self.last_render_error.as_deref()
9937 }
9938
9939 pub fn render_scene_to_encoder(
9940 &mut self,
9941 scene: &Scene,
9942 encoder: &mut wgpu::CommandEncoder,
9943 target_view: &wgpu::TextureView,
9944 clear_color_override: Option<[f64; 4]>,
9945 ) {
9946 self.render_scene_to_encoder_with_texture(
9947 scene,
9948 encoder,
9949 target_view,
9950 None,
9951 clear_color_override,
9952 )
9953 }
9954
9955 pub fn render_scene_to_encoder_with_texture(
9961 &mut self,
9962 scene: &Scene,
9963 encoder: &mut wgpu::CommandEncoder,
9964 target_view: &wgpu::TextureView,
9965 target_texture: Option<&wgpu::Texture>,
9966 clear_color_override: Option<[f64; 4]>,
9967 ) {
9968 if self.output_width == 0 || self.output_height == 0 {
9969 return;
9970 }
9971 self.sync_text_caches();
9972 fn visible(aabb: repose_core::Rect, clip: repose_core::Rect) -> bool {
9973 if !aabb.x.is_finite()
9974 || !aabb.y.is_finite()
9975 || !aabb.w.is_finite()
9976 || !aabb.h.is_finite()
9977 || aabb.w <= 0.0
9978 || aabb.h <= 0.0
9979 {
9980 return false;
9981 }
9982 let aabb = repose_core::Rect {
9983 x: aabb.x - 1.0,
9984 y: aabb.y - 1.0,
9985 w: aabb.w + 2.0,
9986 h: aabb.h + 2.0,
9987 };
9988 let clipped = intersect(aabb, clip);
9989 clipped.x.is_finite()
9990 && clipped.y.is_finite()
9991 && clipped.w.is_finite()
9992 && clipped.h.is_finite()
9993 && clipped.w > 0.0
9994 && clipped.h > 0.0
9995 }
9996
9997 fn to_ndc(x: f32, y: f32, w: f32, h: f32, fb_w: f32, fb_h: f32) -> [f32; 4] {
9998 let x0 = (x / fb_w) * 2.0 - 1.0;
9999 let y0 = 1.0 - (y / fb_h) * 2.0;
10000 let x1 = ((x + w) / fb_w) * 2.0 - 1.0;
10001 let y1 = 1.0 - ((y + h) / fb_h) * 2.0;
10002 let min_x = x0.min(x1);
10003 let min_y = y0.min(y1);
10004 let w_ndc = (x1 - x0).abs();
10005 let h_ndc = (y1 - y0).abs();
10006 [min_x, min_y, w_ndc, h_ndc]
10007 }
10008
10009 fn to_scissor(r: &repose_core::Rect, fb_w: u32, fb_h: u32) -> (u32, u32, u32, u32) {
10010 if fb_w == 0
10011 || fb_h == 0
10012 || !r.x.is_finite()
10013 || !r.y.is_finite()
10014 || !r.w.is_finite()
10015 || !r.h.is_finite()
10016 || r.w <= 0.0
10017 || r.h <= 0.0
10018 {
10019 return (0, 0, 0, 0);
10020 }
10021 let x0 = r.x.ceil().max(0.0).min(fb_w as f32);
10026 let y0 = r.y.ceil().max(0.0).min(fb_h as f32);
10027 let x1 = (r.x + r.w).floor().max(x0).min(fb_w as f32);
10028 let y1 = (r.y + r.h).floor().max(y0).min(fb_h as f32);
10029 if x1 <= x0 || y1 <= y0 {
10030 return (0, 0, 0, 0);
10031 }
10032 (x0 as u32, y0 as u32, (x1 - x0) as u32, (y1 - y0) as u32)
10033 }
10034
10035 let fb_w = self.output_width as f32;
10036 let fb_h = self.output_height as f32;
10037
10038 let mut passes: Vec<Pass> = Vec::with_capacity(1);
10039 let clear_color = clear_color_override
10040 .map(|color| {
10041 let alpha = color[3];
10042 [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha]
10043 })
10044 .unwrap_or_else(|| {
10045 let color = scene.clear_color.to_linear();
10046 let alpha = color[3] as f64;
10047 [
10048 color[0] as f64 * alpha,
10049 color[1] as f64 * alpha,
10050 color[2] as f64 * alpha,
10051 alpha,
10052 ]
10053 });
10054 let mut next_pass_id = 0u64;
10055 let mut current_pass: Pass = Pass {
10056 id: next_pass_id,
10057 target: PassTarget::Surface,
10058 initial_scissor: (0, 0, self.output_width, self.output_height),
10059 active_scissor: Some((0, 0, self.output_width, self.output_height)),
10060 clear_color: Some([
10061 clear_color[0] as f32,
10062 clear_color[1] as f32,
10063 clear_color[2] as f32,
10064 clear_color[3] as f32,
10065 ]),
10066 cmds: Vec::with_capacity(scene.nodes.len()),
10067 };
10068 next_pass_id += 1;
10069 let mut target_stack: Vec<PassTarget> = Vec::new();
10070 let mut layer_stack: Vec<LayerState> = Vec::new();
10071 let mut current_target_size: (f32, f32) = (fb_w, fb_h);
10072
10073 struct Batch {
10074 rects: Vec<RectInstance>,
10075 borders: Vec<BorderInstance>,
10076 ellipses: Vec<EllipseInstance>,
10077 e_borders: Vec<EllipseBorderInstance>,
10078 arcs: Vec<ArcInstance>,
10079 masks: Vec<GlyphInstance>,
10080 colors: Vec<GlyphInstance>,
10081 }
10082
10083 impl Batch {
10084 fn new() -> Self {
10085 Self {
10086 rects: vec![],
10087 borders: vec![],
10088 ellipses: vec![],
10089 e_borders: vec![],
10090 arcs: vec![],
10091 masks: vec![],
10092 colors: vec![],
10093 }
10094 }
10095
10096 fn is_empty(&self) -> bool {
10097 self.rects.is_empty()
10098 && self.borders.is_empty()
10099 && self.ellipses.is_empty()
10100 && self.e_borders.is_empty()
10101 && self.arcs.is_empty()
10102 && self.masks.is_empty()
10103 && self.colors.is_empty()
10104 }
10105
10106 fn flush(
10107 &mut self,
10108 pipes: (
10109 &mut InstancedPipe<RectInstance>,
10110 &mut InstancedPipe<BorderInstance>,
10111 &mut InstancedPipe<EllipseInstance>,
10112 &mut InstancedPipe<EllipseBorderInstance>,
10113 &mut InstancedPipe<ArcInstance>,
10114 ),
10115 glyph_pipes: (
10116 &mut InstancedPipe<GlyphInstance>,
10117 &mut InstancedPipe<GlyphInstance>,
10118 ),
10119 device: &wgpu::Device,
10120 queue: &wgpu::Queue,
10121 encoder: &mut wgpu::CommandEncoder,
10122 cmds: &mut Vec<Cmd>,
10123 ) {
10124 let (rects, borders, ellipses, e_borders, arcs) = pipes;
10125 let (masks, colors) = glyph_pipes;
10126
10127 macro_rules! flush_one {
10128 ($buf:ident, $pipe:expr, $variant:ident) => {
10129 if !self.$buf.is_empty() {
10130 if let Some((off, cnt)) =
10131 $pipe.upload(device, queue, encoder, &self.$buf)
10132 {
10133 cmds.push(Cmd::$variant { off, cnt });
10134 }
10135 self.$buf.clear();
10136 }
10137 };
10138 }
10139
10140 flush_one!(rects, rects, Rect);
10141 flush_one!(borders, borders, Border);
10142 flush_one!(ellipses, ellipses, Ellipse);
10143 flush_one!(e_borders, e_borders, EllipseBorder);
10144 flush_one!(arcs, arcs, Arc);
10145 flush_one!(masks, masks, GlyphsMask);
10146 flush_one!(colors, colors, GlyphsColor);
10147 }
10148 }
10149
10150 self.rects.reset();
10151 self.borders.reset();
10152 self.ellipses.reset();
10153 self.ellipse_borders.reset();
10154 self.arcs.reset();
10155 self.glyph_mask.reset();
10156 self.glyph_color.reset();
10157 self.clip_ring.reset();
10158 self.blur_ring.reset();
10159 self.nv12.reset();
10160
10161 self.slug_ring.reset();
10162 self.mesh_uniform_head = 0;
10163 self.mesh_instance_head = 0;
10164 self.projective_ring.reset();
10165 self.blend_ring.reset();
10166 for id in self.flatten_layer_ids.drain(..) {
10167 if let Some(layer) = self.layer_pool.remove(&id) {
10168 self.layer_bytes_total = self.layer_bytes_total.saturating_sub(layer.bytes);
10169 if layer.transient {
10170 self.transient_layer_bytes_total =
10171 self.transient_layer_bytes_total.saturating_sub(layer.bytes);
10172 }
10173 }
10174 }
10175 self.producer_layer_ids.clear();
10176 self.recycle_blend_snapshots();
10177 self.blend_copies.clear();
10178 let mut batch = Batch::new();
10179 let mut image_run: Option<(
10182 u64,
10183 ImageFilter,
10184 bool,
10185 repose_core::BlendMode,
10186 Vec<GlyphInstance>,
10187 )> = None;
10188 let mut nv12_run: Option<(u64, ImageFilter, repose_core::BlendMode, Vec<Nv12Instance>)> =
10189 None;
10190 let mut slug_verts_local: Vec<slug::TessVertex> = Vec::new();
10191 let mut transform_stack: Vec<Transform> = vec![Transform::identity()];
10192 let mut flatten_stack: Vec<FlattenRecord> = Vec::new();
10193 let mut flatten_id_head: u32 = FLATTEN_ID_BASE;
10194 let mut flatten_ids_used: Vec<u32> = Vec::new();
10195 let mut scissor_stack: Vec<repose_core::Rect> = Vec::with_capacity(8);
10196 let mut active_clips: Vec<ActiveClip> = Vec::with_capacity(8);
10197 let mut root_clip_rect = repose_core::Rect {
10198 x: 0.0,
10199 y: 0.0,
10200 w: fb_w,
10201 h: fb_h,
10202 };
10203
10204 let mut current_prim: Option<&'static str> = None;
10205 let mut shape_stops: Vec<ShapeGradientStopsGpu> = Vec::new();
10206
10207 macro_rules! flush_if_prim_changed {
10208 ($prim:literal, $pipe:expr) => {
10209 if current_prim != Some($prim) {
10210 flush_batch!();
10211 current_prim = Some($prim);
10212 }
10213 };
10214 }
10215
10216 macro_rules! flush_image_runs {
10217 () => {{
10218 if let Some((handle, filter, tile, blend, instances)) = image_run.take()
10219 && let Some((off, cnt)) =
10220 self.glyph_color
10221 .upload(&self.device, &self.queue, encoder, &instances)
10222 {
10223 current_pass.cmds.push(Cmd::ImageRgba {
10224 off,
10225 cnt,
10226 handle,
10227 filter,
10228 tile,
10229 blend,
10230 });
10231 }
10232 if let Some((handle, filter, blend, instances)) = nv12_run.take()
10233 && let Some((off, cnt)) =
10234 self.nv12
10235 .upload(&self.device, &self.queue, encoder, &instances)
10236 {
10237 current_pass.cmds.push(Cmd::ImageNv12 {
10238 off,
10239 cnt,
10240 handle,
10241 filter,
10242 blend,
10243 });
10244 }
10245 }};
10246 }
10247
10248 macro_rules! flush_primitives {
10249 () => {{
10250 if !batch.is_empty() {
10251 batch.flush(
10252 (
10253 &mut self.rects,
10254 &mut self.borders,
10255 &mut self.ellipses,
10256 &mut self.ellipse_borders,
10257 &mut self.arcs,
10258 ),
10259 (&mut self.glyph_mask, &mut self.glyph_color),
10260 &self.device,
10261 &self.queue,
10262 encoder,
10263 &mut current_pass.cmds,
10264 )
10265 }
10266 }};
10267 }
10268
10269 macro_rules! flush_batch {
10270 () => {{
10271 flush_image_runs!();
10272 flush_primitives!();
10273 }};
10274 }
10275 let mut pending_layer_composite: Option<Cmd> = None;
10276 let shadow_layer_ids: HashSet<u32> = scene
10277 .nodes
10278 .iter()
10279 .filter_map(|node| match node {
10280 SceneNode::CompositeShadow { layer_id, .. } => Some(*layer_id),
10281 _ => None,
10282 })
10283 .collect();
10284 macro_rules! flush_pending_layer {
10285 () => {
10286 if let Some(command) = pending_layer_composite.take() {
10287 current_pass.cmds.push(command);
10288 }
10289 };
10290 }
10291 for node in &scene.nodes {
10292 let t_identity = Transform::identity();
10293 let current_transform = transform_stack.last().unwrap_or(&t_identity);
10294
10295 let image_spec = match node {
10299 SceneNode::Image {
10300 rect,
10301 handle,
10302 tint,
10303 style,
10304 } => Some((*rect, *handle, *tint, *style, repose_core::BlendMode::Alpha)),
10305 SceneNode::ImageBlended {
10306 rect,
10307 handle,
10308 tint,
10309 style,
10310 blend,
10311 } => Some((*rect, *handle, *tint, *style, *blend)),
10312 _ => None,
10313 };
10314 if let Some((rect, handle, tint, style, blend)) = image_spec {
10315 let ImagePaintStyle {
10316 fit,
10317 filter,
10318 source_rect,
10319 alignment,
10320 } = style;
10321 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10322 if !visible(affine_aabb(current_transform, &rect), clip) {
10323 continue;
10324 }
10325 flush_batch!();
10326 let (img_w, img_h, is_nv12) = match self.resolve_image_for_draw(handle) {
10327 Some(wh) => wh,
10328 None => {
10329 log::warn!("Image handle {} not found", handle);
10330 continue;
10331 }
10332 };
10333 let Some(source) = resolve_image_source(source_rect, img_w, img_h) else {
10334 log::warn!(
10335 "Image handle {} has invalid source rect {:?}",
10336 handle,
10337 source_rect
10338 );
10339 continue;
10340 };
10341 let Some((draw_rect, uv_rect)) = image_fit_geometry(rect, fit, alignment, &source)
10342 else {
10343 continue;
10344 };
10345 let tile = matches!(fit, ImageFit::Tile);
10346 let translucent_fixed_blend = matches!(
10350 blend,
10351 repose_core::BlendMode::Add
10352 | repose_core::BlendMode::Multiply
10353 | repose_core::BlendMode::Screen
10354 | repose_core::BlendMode::Darken
10355 | repose_core::BlendMode::Lighten
10356 ) && tint.3 < 255;
10357 if blend.needs_isolation() || translucent_fixed_blend {
10358 if is_nv12 {
10359 log::warn!("blend on an NV12 image is not supported");
10362 } else {
10363 let blend_scissor = to_scissor(
10364 &scissor_stack.last().copied().unwrap_or(root_clip_rect),
10365 current_target_size.0 as u32,
10366 current_target_size.1 as u32,
10367 );
10368 self.emit_isolated_image(
10369 draw_rect,
10370 handle,
10371 uv_rect,
10372 tint,
10373 tile,
10374 filter,
10375 blend,
10376 [1.0, 1.0, 1.0, 1.0],
10377 ColorFilter::None,
10378 current_transform,
10379 &mut current_pass,
10380 &active_clips,
10381 &mut passes,
10382 &mut flatten_id_head,
10383 &mut next_pass_id,
10384 &mut flatten_ids_used,
10385 blend_scissor,
10386 encoder,
10387 fb_w,
10388 fb_h,
10389 );
10390 }
10391 continue;
10392 }
10393 let (ndc_center, fwd_mat) = rect_to_instance_ndc(
10394 draw_rect,
10395 current_transform,
10396 current_target_size.0,
10397 current_target_size.1,
10398 );
10399 if is_nv12 {
10400 if image_run.is_some() {
10401 flush_image_runs!();
10402 }
10403 let (uv_x_offset, uv_y_offset) =
10404 if let Some(ImageTex::Nv12 {
10405 w, h, color_info, ..
10406 }) = self.images.get(&handle)
10407 {
10408 let chroma_w = w.div_ceil(2).max(1) as f32;
10409 let chroma_h = h.div_ceil(2).max(1) as f32;
10410 match color_info.chroma_siting {
10411 ChromaSiting::Center => (0.0, 0.0),
10412 ChromaSiting::Left => (-0.5 / chroma_w, 0.0),
10413 ChromaSiting::TopLeft => (-0.5 / chroma_w, -0.5 / chroma_h),
10414 }
10415 } else {
10416 (0.0, 0.0)
10417 };
10418 let inst = Nv12Instance {
10419 xywh: ndc_center,
10420 uv: uv_rect,
10421 color: tint.to_linear(),
10422 uv_x_offset,
10423 uv_y_offset,
10424 fwd_mat,
10425 };
10426 if nv12_run
10427 .as_ref()
10428 .is_some_and(|(run_handle, run_filter, run_blend, _)| {
10429 *run_handle != handle || *run_filter != filter || *run_blend != blend
10430 })
10431 {
10432 flush_image_runs!();
10433 }
10434 match &mut nv12_run {
10435 Some((run_handle, run_filter, run_blend, instances))
10436 if *run_handle == handle
10437 && *run_filter == filter
10438 && *run_blend == blend =>
10439 {
10440 instances.push(inst)
10441 }
10442 _ => nv12_run = Some((handle, filter, blend, vec![inst])),
10443 }
10444 } else {
10445 if nv12_run.is_some() {
10446 flush_image_runs!();
10447 }
10448 let inst = GlyphInstance {
10449 xywh: ndc_center,
10450 uv: uv_rect,
10451 color: tint.to_linear(),
10452 fwd_mat,
10453 };
10454 if image_run.as_ref().is_some_and(
10455 |(run_handle, run_filter, run_tile, run_blend, _)| {
10456 *run_handle != handle
10457 || *run_filter != filter
10458 || *run_tile != tile
10459 || *run_blend != blend
10460 },
10461 ) {
10462 flush_image_runs!();
10463 }
10464 match &mut image_run {
10465 Some((run_handle, run_filter, run_tile, run_blend, instances))
10466 if *run_handle == handle
10467 && *run_filter == filter
10468 && *run_tile == tile
10469 && *run_blend == blend =>
10470 {
10471 instances.push(inst)
10472 }
10473 _ => image_run = Some((handle, filter, tile, blend, vec![inst])),
10474 }
10475 }
10476 continue;
10477 }
10478
10479 match node {
10480 SceneNode::Rect {
10481 rect,
10482 brush,
10483 radius,
10484 } => {
10485 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10486 if !visible(affine_aabb(current_transform, rect), clip) {
10487 continue;
10488 }
10489 flush_if_prim_changed!("rect", &self.rects);
10490 let (ndc, fwd_mat) = rect_to_instance_ndc(
10491 *rect,
10492 current_transform,
10493 current_target_size.0,
10494 current_target_size.1,
10495 );
10496 let (
10497 brush_type,
10498 grad_kind,
10499 color0,
10500 color1,
10501 grad_p0,
10502 grad_p1,
10503 tile_mode,
10504 stop_table,
10505 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10506 batch.rects.push(RectInstance {
10507 xywh: ndc,
10508 radii: radius.map(|r| r.0),
10509 color0,
10510 color1,
10511 fwd_mat,
10512 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10513 bits: pack_shape_bits_with_stops(
10514 brush_type, grad_kind, tile_mode, 0, stop_table,
10515 ),
10516 _pad: [0.0; 3],
10517 });
10518 }
10519 SceneNode::Border {
10520 rect,
10521 brush,
10522 width,
10523 radius,
10524 } => {
10525 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10526 if !visible(affine_aabb(current_transform, rect), clip) {
10527 continue;
10528 }
10529 flush_if_prim_changed!("border", &self.borders);
10530 let (ndc, fwd_mat) = rect_to_instance_ndc(
10531 *rect,
10532 current_transform,
10533 current_target_size.0,
10534 current_target_size.1,
10535 );
10536 let (
10537 brush_type,
10538 grad_kind,
10539 color0,
10540 color1,
10541 grad_p0,
10542 grad_p1,
10543 tile_mode,
10544 stop_table,
10545 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10546 batch.borders.push(BorderInstance {
10547 xywh: ndc,
10548 radii: radius.map(|r| r.0),
10549 color0,
10550 color1,
10551 fwd_mat,
10552 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10553 bits: pack_shape_bits_with_stops(
10554 brush_type, grad_kind, tile_mode, 0, stop_table,
10555 ),
10556 stroke: width.0,
10557 _pad: [0.0; 2],
10558 });
10559 }
10560 SceneNode::ShapeRect {
10561 rect,
10562 resolved,
10563 brush,
10564 } => match resolved {
10565 ResolvedShape::Rect(radii) => {
10566 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10567 if !visible(affine_aabb(current_transform, rect), clip) {
10568 continue;
10569 }
10570 flush_if_prim_changed!("rect", &self.rects);
10571 let (ndc, fwd_mat) = rect_to_instance_ndc(
10572 *rect,
10573 current_transform,
10574 current_target_size.0,
10575 current_target_size.1,
10576 );
10577 let (
10578 brush_type,
10579 grad_kind,
10580 color0,
10581 color1,
10582 grad_p0,
10583 grad_p1,
10584 tile_mode,
10585 stop_table,
10586 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10587 batch.rects.push(RectInstance {
10588 xywh: ndc,
10589 radii: radii.map(|r| r.0),
10590 color0,
10591 color1,
10592 fwd_mat,
10593 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10594 bits: pack_shape_bits_with_stops(
10595 brush_type, grad_kind, tile_mode, 0, stop_table,
10596 ),
10597 _pad: [0.0; 3],
10598 });
10599 }
10600 ResolvedShape::Ellipse => {
10601 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10602 if !visible(affine_aabb(current_transform, rect), clip) {
10603 continue;
10604 }
10605 flush_if_prim_changed!("ellipse", &self.ellipses);
10606 let (ndc, fwd_mat) = rect_to_instance_ndc(
10607 *rect,
10608 current_transform,
10609 current_target_size.0,
10610 current_target_size.1,
10611 );
10612 let (
10613 brush_type,
10614 grad_kind,
10615 color0,
10616 color1,
10617 grad_p0,
10618 grad_p1,
10619 tile_mode,
10620 stop_table,
10621 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10622 batch.ellipses.push(EllipseInstance {
10623 xywh: ndc,
10624 color0,
10625 color1,
10626 fwd_mat,
10627 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10628 bits: pack_shape_bits_with_stops(
10629 brush_type, grad_kind, tile_mode, 0, stop_table,
10630 ),
10631 _pad: [0.0; 1],
10632 });
10633 }
10634 ResolvedShape::Path { path, offset } => {
10635 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10636 let offset_px = (offset.0.0, offset.1.0);
10637 let aabb = shape_path_aabb(path, self.pixels_per_point, offset_px, None);
10638 if !visible(affine_aabb(current_transform, &aabb), clip) {
10639 continue;
10640 }
10641 let Some(mesh) = self.upload_shape_mesh(path, self.pixels_per_point, None)
10642 else {
10643 continue;
10644 };
10645 flush_batch!();
10646 let paint = brush_to_paint_desc(brush, *rect);
10647 self.emit_shape_mesh(
10648 mesh,
10649 current_transform,
10650 offset_px,
10651 &paint,
10652 &mut current_pass.cmds,
10653 );
10654 }
10655 },
10656 SceneNode::ShapeBorder {
10657 rect,
10658 resolved,
10659 brush,
10660 width,
10661 } => match resolved {
10662 ResolvedShape::Rect(radii) => {
10663 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10664 if !visible(affine_aabb(current_transform, rect), clip) {
10665 continue;
10666 }
10667 flush_if_prim_changed!("border", &self.borders);
10668 let (ndc, fwd_mat) = rect_to_instance_ndc(
10669 *rect,
10670 current_transform,
10671 current_target_size.0,
10672 current_target_size.1,
10673 );
10674 let (
10675 brush_type,
10676 grad_kind,
10677 color0,
10678 color1,
10679 grad_p0,
10680 grad_p1,
10681 tile_mode,
10682 stop_table,
10683 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10684 batch.borders.push(BorderInstance {
10685 xywh: ndc,
10686 radii: radii.map(|r| r.0),
10687 color0,
10688 color1,
10689 fwd_mat,
10690 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10691 bits: pack_shape_bits_with_stops(
10692 brush_type, grad_kind, tile_mode, 0, stop_table,
10693 ),
10694 stroke: width.0,
10695 _pad: [0.0; 2],
10696 });
10697 }
10698 ResolvedShape::Ellipse => {
10699 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10700 let cull_pad = width.0.abs() * 0.5 + 2.0;
10701 let cull_rect = repose_core::Rect {
10702 x: rect.x - cull_pad,
10703 y: rect.y - cull_pad,
10704 w: rect.w + cull_pad * 2.0,
10705 h: rect.h + cull_pad * 2.0,
10706 };
10707 if !visible(affine_aabb(current_transform, &cull_rect), clip) {
10708 continue;
10709 }
10710 flush_if_prim_changed!("ellipse_border", &self.ellipse_borders);
10711 let (ndc, fwd_mat) = rect_to_instance_ndc(
10712 *rect,
10713 current_transform,
10714 current_target_size.0,
10715 current_target_size.1,
10716 );
10717 let pad_px = width.0 * 0.5 + 2.0;
10718 let pad = (pad_px / current_target_size.0.max(1.0)) * 2.0;
10719 let (
10720 brush_type,
10721 grad_kind,
10722 color0,
10723 color1,
10724 grad_p0,
10725 grad_p1,
10726 tile_mode,
10727 stop_table,
10728 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10729 batch.e_borders.push(EllipseBorderInstance {
10730 xywh: ndc,
10731 color0,
10732 color1,
10733 fwd_mat,
10734 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10735 bits: pack_shape_bits_with_stops(
10736 brush_type, grad_kind, tile_mode, 0, stop_table,
10737 ),
10738 stroke: width.0,
10739 pad,
10740 _pad: 0.0,
10741 });
10742 }
10743 ResolvedShape::Path { path, offset } => {
10744 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10745 let offset_px = (offset.0.0, offset.1.0);
10746 let aabb =
10747 shape_path_aabb(path, self.pixels_per_point, offset_px, Some(*width));
10748 if !visible(affine_aabb(current_transform, &aabb), clip) {
10749 continue;
10750 }
10751 let Some(mesh) =
10752 self.upload_shape_mesh(path, self.pixels_per_point, Some(*width))
10753 else {
10754 continue;
10755 };
10756 flush_batch!();
10757 let paint = brush_to_paint_desc(brush, *rect);
10758 self.emit_shape_mesh(
10759 mesh,
10760 current_transform,
10761 offset_px,
10762 &paint,
10763 &mut current_pass.cmds,
10764 );
10765 }
10766 },
10767 SceneNode::Ellipse { rect, brush } => {
10768 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10769 if !visible(affine_aabb(current_transform, rect), clip) {
10770 continue;
10771 }
10772 flush_if_prim_changed!("ellipse", &self.ellipses);
10773 let (ndc, fwd_mat) = rect_to_instance_ndc(
10774 *rect,
10775 current_transform,
10776 current_target_size.0,
10777 current_target_size.1,
10778 );
10779 let (
10780 brush_type,
10781 grad_kind,
10782 color0,
10783 color1,
10784 grad_p0,
10785 grad_p1,
10786 tile_mode,
10787 stop_table,
10788 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10789 batch.ellipses.push(EllipseInstance {
10790 xywh: ndc,
10791 color0,
10792 color1,
10793 fwd_mat,
10794 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10795 bits: pack_shape_bits_with_stops(
10796 brush_type, grad_kind, tile_mode, 0, stop_table,
10797 ),
10798 _pad: [0.0; 1],
10799 });
10800 }
10801 SceneNode::EllipseBorder { rect, brush, width } => {
10802 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10803 let cull_pad = width.0.abs() * 0.5 + 2.0;
10804 let cull_rect = repose_core::Rect {
10805 x: rect.x - cull_pad,
10806 y: rect.y - cull_pad,
10807 w: rect.w + cull_pad * 2.0,
10808 h: rect.h + cull_pad * 2.0,
10809 };
10810 if !visible(affine_aabb(current_transform, &cull_rect), clip) {
10811 continue;
10812 }
10813 flush_if_prim_changed!("ellipse_border", &self.ellipse_borders);
10814 let (ndc, fwd_mat) = rect_to_instance_ndc(
10815 *rect,
10816 current_transform,
10817 current_target_size.0,
10818 current_target_size.1,
10819 );
10820 let pad_px = width.0 * 0.5 + 2.0;
10821 let pad = (pad_px / current_target_size.0.max(1.0)) * 2.0;
10822 let (
10823 brush_type,
10824 grad_kind,
10825 color0,
10826 color1,
10827 grad_p0,
10828 grad_p1,
10829 tile_mode,
10830 stop_table,
10831 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10832 batch.e_borders.push(EllipseBorderInstance {
10833 xywh: ndc,
10834 color0,
10835 color1,
10836 fwd_mat,
10837 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10838 bits: pack_shape_bits_with_stops(
10839 brush_type, grad_kind, tile_mode, 0, stop_table,
10840 ),
10841 stroke: width.0,
10842 pad,
10843 _pad: 0.0,
10844 });
10845 }
10846 SceneNode::Arc {
10847 rect,
10848 start_angle,
10849 sweep_angle,
10850 stroke_width,
10851 brush,
10852 cap,
10853 } => {
10854 if !start_angle.is_finite()
10855 || !sweep_angle.is_finite()
10856 || !stroke_width.0.is_finite()
10857 || !rect.x.is_finite()
10858 || !rect.y.is_finite()
10859 || !rect.w.is_finite()
10860 || !rect.h.is_finite()
10861 || rect.w <= 0.0
10862 || rect.h <= 0.0
10863 || stroke_width.0 <= 0.0
10864 || sweep_angle.abs() <= 1e-6
10865 {
10866 continue;
10867 }
10868 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10869 let cull_pad = stroke_width.0.abs() * 0.5 + 2.0;
10870 let cull_rect = repose_core::Rect {
10871 x: rect.x - cull_pad,
10872 y: rect.y - cull_pad,
10873 w: rect.w + cull_pad * 2.0,
10874 h: rect.h + cull_pad * 2.0,
10875 };
10876 if !visible(affine_aabb(current_transform, &cull_rect), clip) {
10877 continue;
10878 }
10879 flush_if_prim_changed!("arc", &self.arcs);
10880 let (ndc, fwd_mat) = rect_to_instance_ndc(
10881 *rect,
10882 current_transform,
10883 current_target_size.0.max(1.0),
10884 current_target_size.1.max(1.0),
10885 );
10886 let pad_px = stroke_width.0 * 0.5 + 2.0;
10887 let pad = (pad_px / current_target_size.0.max(1.0)) * 2.0;
10888 let cap_val = match cap {
10889 StrokeCap::Butt => 0.0,
10890 StrokeCap::Round => 1.0,
10891 StrokeCap::Square => 2.0,
10892 };
10893 let (
10894 brush_type,
10895 grad_kind,
10896 color0,
10897 color1,
10898 grad_p0,
10899 grad_p1,
10900 tile_mode,
10901 stop_table,
10902 ) = brush_to_shape_fields(brush, rect, current_transform, &mut shape_stops);
10903 let (start, sweep) = if *sweep_angle < 0.0 {
10904 (*start_angle + *sweep_angle, -*sweep_angle)
10905 } else {
10906 (*start_angle, *sweep_angle)
10907 };
10908 batch.arcs.push(ArcInstance {
10909 xywh: ndc,
10910 color0,
10911 color1,
10912 fwd_mat,
10913 grad: [grad_p0[0], grad_p0[1], grad_p1[0], grad_p1[1]],
10914 bits: pack_shape_bits_with_stops(
10915 brush_type,
10916 grad_kind,
10917 tile_mode,
10918 cap_val as u32,
10919 stop_table,
10920 ),
10921 start_angle: start,
10922 sweep_angle: sweep,
10923 stroke: stroke_width.0,
10924 pad,
10925 _pad: 0.0,
10926 });
10927 }
10928 SceneNode::Text {
10929 rect,
10930 text,
10931 color,
10932 size,
10933 style,
10934 } => {
10935 let TextPaintStyle {
10936 font_family,
10937 font_weight,
10938 font_style,
10939 text_decoration,
10940 letter_spacing,
10941 font_variation_settings,
10942 baseline_shift,
10943 draw_style,
10944 ..
10945 } = style;
10946 let px = size.0;
10947 if !px.is_finite()
10948 || px <= 0.0
10949 || !rect.x.is_finite()
10950 || !rect.y.is_finite()
10951 || !rect.w.is_finite()
10952 || !rect.h.is_finite()
10953 {
10954 continue;
10955 }
10956 let margin = px * 4.0 + letter_spacing.0.abs() * 2.0;
10957 let text_bounds = repose_core::Rect {
10958 x: rect.x - margin,
10959 y: rect.y - margin,
10960 w: rect.w + margin * 2.0,
10961 h: rect.h + margin * 2.0,
10962 };
10963 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
10964 if !visible(affine_aabb(current_transform, &text_bounds), clip) {
10965 continue;
10966 }
10967 flush_batch!(); let lh_ratio = rect.h / px;
10970 let fw = font_weight.0;
10971 let fs = if *font_style == FontStyle::Italic {
10972 1
10973 } else {
10974 0
10975 };
10976 let shaped = self.shape_text_cached(
10977 text,
10978 px,
10979 lh_ratio,
10980 *font_family,
10981 fw,
10982 fs,
10983 letter_spacing.0,
10984 font_variation_settings.as_ref(),
10985 );
10986 let baseline_y = shaped.glyphs.first().map(|g| rect.y + g.y);
10987
10988 let fwd = forward_rs_mat(current_transform);
10989 let has_linear = fwd != [1.0, 0.0, 0.0, 1.0];
10990
10991 let lin = current_transform.linear();
10992 let tr_x = current_transform.translate_x;
10993 let tr_y = current_transform.translate_y;
10994
10995 let make_glyph_instance =
10996 |gx: f32, gy: f32, gw: f32, gh: f32| -> ([f32; 4], [f32; 4]) {
10997 if has_linear {
10998 let gc_x = gx + gw * 0.5;
10999 let gc_y = gy + gh * 0.5;
11000 let wc_x = lin[0] * gc_x + lin[1] * gc_y + tr_x;
11001 let wc_y = lin[2] * gc_x + lin[3] * gc_y + tr_y;
11002 let ww = gw * current_transform.scale_x;
11003 let wh = gh * current_transform.scale_y;
11004 let ex = fwd[0].abs() * ww * 0.5 + fwd[1].abs() * wh * 0.5;
11005 let ey = fwd[2].abs() * ww * 0.5 + fwd[3].abs() * wh * 0.5;
11006 let ndc_tl = to_ndc(
11007 wc_x - ex,
11008 wc_y - ey,
11009 ex * 2.0,
11010 ey * 2.0,
11011 current_target_size.0,
11012 current_target_size.1,
11013 );
11014 let ndc = [
11015 ndc_tl[0] + ndc_tl[2] * 0.5,
11016 ndc_tl[1] + ndc_tl[3] * 0.5,
11017 ndc_tl[2],
11018 ndc_tl[3],
11019 ];
11020 (ndc, fwd)
11021 } else {
11022 let (sx, sy) = if current_transform.scale_x == 1.0
11023 && current_transform.scale_y == 1.0
11024 {
11025 (gx.round(), gy.round())
11026 } else {
11027 (gx, gy)
11028 };
11029 rect_to_instance_ndc(
11030 repose_core::Rect {
11031 x: sx,
11032 y: sy,
11033 w: gw,
11034 h: gh,
11035 },
11036 current_transform,
11037 current_target_size.0,
11038 current_target_size.1,
11039 )
11040 }
11041 };
11042
11043 let baseline_shift_y: f32 = px * baseline_shift.0;
11044
11045 let (
11046 draws_fill,
11047 is_stroke,
11048 stroke_width,
11049 stroke_cap,
11050 stroke_join,
11051 stroke_miter,
11052 stroke_path_effect,
11053 stroke_color,
11054 ) = match draw_style {
11055 repose_core::DrawStyle::Stroke {
11056 width,
11057 cap,
11058 join,
11059 miter,
11060 path_effect,
11061 } => (
11062 false,
11063 true,
11064 *width,
11065 *cap,
11066 *join,
11067 *miter,
11068 path_effect.clone(),
11069 None,
11070 ),
11071 repose_core::DrawStyle::FillAndStroke {
11072 width,
11073 cap,
11074 join,
11075 miter,
11076 path_effect,
11077 outline_color,
11078 } => (
11079 true,
11080 true,
11081 *width,
11082 *cap,
11083 *join,
11084 *miter,
11085 path_effect.clone(),
11086 outline_color.map(|c| {
11090 c.with_alpha_f32(
11091 f32::from(c.3) * f32::from(color.3) / (255.0 * 255.0),
11092 )
11093 }),
11094 ),
11095 _ => (
11096 true,
11097 false,
11098 0.0,
11099 repose_core::StrokeCap::Butt,
11100 repose_core::StrokeJoin::Miter,
11101 4.0,
11102 None,
11103 None,
11104 ),
11105 };
11106 let outline_under = stroke_color.is_some();
11110 let stroke_tess_key = if is_stroke {
11111 Some(slug::StrokeTessKey::new(
11112 stroke_width,
11113 stroke_cap,
11114 stroke_join,
11115 stroke_miter,
11116 &stroke_path_effect,
11117 ))
11118 } else {
11119 None
11120 };
11121
11122 let mut legacy_shaped = None;
11123 for (glyph_index, sg) in shaped.glyphs.iter().enumerate() {
11124 if self.slug_enabled {
11125 let ck = &sg.cache_key;
11126 let color_linear = color.to_linear();
11127 let stroke_color_linear = stroke_color.unwrap_or(*color).to_linear();
11128 let glyph_pos = (rect.x + sg.x, rect.y + sg.y + baseline_shift_y);
11129 let fill_key = draws_fill.then(|| {
11130 Self::slug_draw_key(
11131 ck,
11132 true,
11133 None,
11134 current_transform,
11135 glyph_pos,
11136 px,
11137 current_target_size,
11138 color_linear,
11139 )
11140 });
11141 let stroke_key = is_stroke.then(|| {
11142 Self::slug_draw_key(
11143 ck,
11144 false,
11145 stroke_tess_key.as_ref(),
11146 current_transform,
11147 glyph_pos,
11148 px,
11149 current_target_size,
11150 stroke_color_linear,
11151 )
11152 });
11153
11154 let fill_cache = fill_key
11157 .as_ref()
11158 .and_then(|k| self.get_cached_slug_vertices(k));
11159 let stroke_cache = stroke_key
11160 .as_ref()
11161 .and_then(|k| self.get_cached_slug_vertices(k));
11162 let fill_miss = fill_key.is_some() && fill_cache.is_none();
11163 let stroke_miss = stroke_key.is_some() && stroke_cache.is_none();
11164 if (fill_key.is_some() || stroke_key.is_some())
11165 && !fill_miss
11166 && !stroke_miss
11167 {
11168 let mut push = |cached: &Option<Arc<[slug::TessVertex]>>| {
11169 if let Some(vertices) = cached {
11170 slug_verts_local.extend_from_slice(vertices);
11171 }
11172 };
11173 if outline_under {
11174 push(&stroke_cache);
11175 push(&fill_cache);
11176 } else {
11177 push(&fill_cache);
11178 push(&stroke_cache);
11179 }
11180 continue;
11181 }
11182
11183 let outline = self.cached_glyph_outline(ck);
11184 if let Some(commands) = outline.as_ref() {
11185 let font_size_px = f32::from_bits(ck.font_size_bits);
11186 if draws_fill {
11187 self.slug_cache.get_or_insert(
11188 ck.clone(),
11189 font_size_px,
11190 commands.as_ref(),
11191 );
11192 }
11193 if is_stroke {
11194 self.slug_cache.get_or_insert_stroke(
11195 ck.clone(),
11196 font_size_px,
11197 commands.as_ref(),
11198 stroke_width,
11199 stroke_cap,
11200 stroke_join,
11201 stroke_miter,
11202 &stroke_path_effect,
11203 );
11204 }
11205 }
11206
11207 if let Some(entry) = self.slug_cache.get(ck) {
11208 let ox = rect.x + sg.x;
11209 let oy = rect.y + sg.y + baseline_shift_y;
11210 let tf = |x: f32, y: f32| -> (f32, f32) {
11211 if has_linear {
11212 (
11213 lin[0] * x + lin[1] * y + current_transform.translate_x,
11214 lin[2] * x + lin[3] * y + current_transform.translate_y,
11215 )
11216 } else {
11217 (
11218 x * current_transform.scale_x
11219 + current_transform.translate_x,
11220 y * current_transform.scale_y
11221 + current_transform.translate_y,
11222 )
11223 }
11224 };
11225 let tw = current_target_size.0;
11226 let th = current_target_size.1;
11227 let fill_vertices = if draws_fill && fill_cache.is_none() {
11228 entry.fill_vertices.clone().unwrap_or_default()
11229 } else {
11230 Vec::new()
11231 };
11232 let stroke_vertices = if stroke_cache.is_none() {
11233 stroke_tess_key
11234 .as_ref()
11235 .and_then(|key| entry.stroke_variants.get(key))
11236 .map(|variant| variant.vertices.clone())
11237 .unwrap_or_default()
11238 } else {
11239 Vec::new()
11240 };
11241 let mut emit =
11242 |verts: &Vec<[f32; 2]>,
11243 key: &Option<SlugDrawKey>,
11244 cached: &Option<Arc<[slug::TessVertex]>>,
11245 vertex_color: [f32; 4]| {
11246 if let Some(vertices) = cached {
11247 slug_verts_local.extend_from_slice(vertices);
11248 return;
11249 }
11250 let Some(key) = key.clone() else {
11251 return;
11252 };
11253 let transformed: Vec<slug::TessVertex> = verts
11254 .iter()
11255 .map(|v| {
11256 let (sx, sy) = tf(ox + v[0] * px, oy - v[1] * px);
11257 slug::TessVertex {
11258 ndc_pos: [
11259 sx / tw * 2.0 - 1.0,
11260 -(sy / th) * 2.0 + 1.0,
11261 ],
11262 color: vertex_color,
11263 }
11264 })
11265 .collect();
11266 let vertices = self.cached_slug_vertices(key, transformed);
11267 slug_verts_local.extend_from_slice(&vertices);
11268 };
11269 if outline_under {
11273 emit(
11274 &stroke_vertices,
11275 &stroke_key,
11276 &stroke_cache,
11277 stroke_color_linear,
11278 );
11279 emit(&fill_vertices, &fill_key, &fill_cache, color_linear);
11280 } else {
11281 emit(&fill_vertices, &fill_key, &fill_cache, color_linear);
11282 emit(
11283 &stroke_vertices,
11284 &stroke_key,
11285 &stroke_cache,
11286 stroke_color_linear,
11287 );
11288 }
11289 continue;
11290 }
11291 }
11292
11293 if !draws_fill {
11294 continue;
11295 }
11296 if legacy_shaped.is_none() {
11297 legacy_shaped = Some(self.legacy_shape_text_cached(
11298 text,
11299 px,
11300 lh_ratio,
11301 *font_family,
11302 fw,
11303 fs,
11304 letter_spacing.0,
11305 font_variation_settings.as_ref(),
11306 ));
11307 }
11308 let Some(legacy_glyph) = legacy_shaped
11309 .as_ref()
11310 .and_then(|glyphs| glyphs.get(glyph_index))
11311 else {
11312 continue;
11313 };
11314 let gx = rect.x + legacy_glyph.x + legacy_glyph.bearing_x;
11315 let gy =
11316 rect.y + legacy_glyph.y - legacy_glyph.bearing_y + baseline_shift_y;
11317 if let Some(info) =
11318 self.upload_glyph_color(legacy_glyph.cache_key.clone(), legacy_glyph.px)
11319 {
11320 let (ndc, fwd_mat) = make_glyph_instance(gx, gy, info.w, info.h);
11321 batch.colors.push(GlyphInstance {
11322 xywh: ndc,
11323 uv: [info.u0, info.v1, info.u1, info.v0],
11324 color: color.to_linear(),
11325 fwd_mat,
11326 });
11327 } else if let Some(info) =
11328 self.upload_glyph_mask(legacy_glyph.cache_key.clone(), legacy_glyph.px)
11329 {
11330 let (ndc, fwd_mat) = make_glyph_instance(gx, gy, info.w, info.h);
11331 batch.masks.push(GlyphInstance {
11332 xywh: ndc,
11333 uv: [info.u0, info.v1, info.u1, info.v0],
11334 color: color.to_linear(),
11335 fwd_mat,
11336 });
11337 }
11338 }
11339
11340 if !slug_verts_local.is_empty() {
11342 let bytes = bytemuck::cast_slice(&slug_verts_local);
11343 let byte_len = u64::try_from(bytes.len()).unwrap_or(u64::MAX);
11344 let Ok(count) = u32::try_from(slug_verts_local.len()) else {
11345 slug_verts_local.clear();
11346 continue;
11347 };
11348 if self
11349 .slug_ring
11350 .grow_to_fit(&self.device, encoder, byte_len)
11351 .is_ok()
11352 && let Ok(off) = self.slug_ring.alloc_write(&self.queue, bytes)
11353 {
11354 current_pass
11355 .cmds
11356 .push(Cmd::GlyphsVector { off, cnt: count });
11357 }
11358 slug_verts_local.clear();
11359 }
11360
11361 if (text_decoration.underline || text_decoration.strikethrough)
11363 && let Some(baseline_y) = baseline_y
11364 {
11365 flush_batch!();
11366 current_prim = Some("rect");
11367 let deco_color = text_decoration.color.unwrap_or(*color);
11368 let thickness = (px * 0.07).max(1.0);
11369
11370 if text_decoration.underline {
11371 let dy = baseline_y + px * 0.1;
11372 let (ndc, fwd_mat) = rect_to_instance_ndc(
11373 repose_core::Rect {
11374 x: rect.x,
11375 y: dy,
11376 w: rect.w,
11377 h: thickness,
11378 },
11379 current_transform,
11380 current_target_size.0,
11381 current_target_size.1,
11382 );
11383 batch.rects.push(RectInstance {
11384 xywh: ndc,
11385 radii: [0.0; 4],
11386 color0: deco_color.to_linear(),
11387 color1: [0.0; 4],
11388 fwd_mat,
11389 grad: [0.0; 4],
11390 bits: 0,
11391 _pad: [0.0; 3],
11392 });
11393 }
11394 if text_decoration.strikethrough {
11395 let sy = baseline_y - px * 0.3;
11396 let (ndc, fwd_mat) = rect_to_instance_ndc(
11397 repose_core::Rect {
11398 x: rect.x,
11399 y: sy,
11400 w: rect.w,
11401 h: thickness,
11402 },
11403 current_transform,
11404 current_target_size.0,
11405 current_target_size.1,
11406 );
11407 batch.rects.push(RectInstance {
11408 xywh: ndc,
11409 radii: [0.0; 4],
11410 color0: deco_color.to_linear(),
11411 color1: [0.0; 4],
11412 fwd_mat,
11413 grad: [0.0; 4],
11414 bits: 0,
11415 _pad: [0.0; 3],
11416 });
11417 }
11418 }
11419 }
11420 SceneNode::Coverage {
11421 rect,
11422 handle,
11423 color,
11424 } => {
11425 flush_batch!();
11426 let Some((tile_w, tile_h)) = self.coverage_dimensions(*handle) else {
11429 log::warn!("Coverage handle {handle} not found");
11430 continue;
11431 };
11432 let draw_rect = repose_core::Rect {
11435 x: rect.x,
11436 y: rect.y,
11437 w: tile_w as f32,
11438 h: tile_h as f32,
11439 };
11440 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
11441 if !visible(affine_aabb(current_transform, &draw_rect), clip) {
11442 continue;
11443 }
11444 let (ndc_center, fwd_mat) = rect_to_instance_ndc(
11445 draw_rect,
11446 current_transform,
11447 current_target_size.0,
11448 current_target_size.1,
11449 );
11450 let inst = GlyphInstance {
11451 xywh: ndc_center,
11452 uv: [0.0, 1.0, 1.0, 0.0],
11453 color: color.to_linear(),
11454 fwd_mat,
11455 };
11456 if let Some((off, _)) =
11457 self.glyph_color
11458 .upload(&self.device, &self.queue, encoder, &[inst])
11459 {
11460 current_pass.cmds.push(Cmd::Coverage {
11461 off,
11462 cnt: 1,
11463 handle: *handle,
11464 });
11465 }
11466 }
11467 SceneNode::PushClip { rect, radius, op } => {
11468 flush_batch!();
11469
11470 let is_diff = matches!(op, repose_core::ClipOp::Difference);
11471 let t_identity = Transform::identity();
11472 let current_transform = transform_stack.last().unwrap_or(&t_identity);
11473 let transformed = affine_aabb(current_transform, rect);
11474 let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
11475 let next_scissor = if is_diff {
11476 top
11477 } else {
11478 intersect(top, transformed)
11479 };
11480 scissor_stack.push(next_scissor);
11481 let scissor = to_scissor(
11482 &next_scissor,
11483 current_target_size.0 as u32,
11484 current_target_size.1 as u32,
11485 );
11486 let has_inverse = active_clips.iter().any(ActiveClip::difference);
11487 let mut blocked =
11488 current_pass.active_scissor.is_none() || (has_inverse && !is_diff);
11489 if has_inverse && is_diff {
11490 log::error!(
11491 "unsupported clip nesting: Difference cannot contain a Difference clip"
11492 );
11493 blocked = true;
11494 }
11495 let has_area = transformed.x.is_finite()
11496 && transformed.y.is_finite()
11497 && transformed.w.is_finite()
11498 && transformed.h.is_finite()
11499 && transformed.w > 0.0
11500 && transformed.h > 0.0;
11501 let mut applied = false;
11502 let mut off = 0;
11503 if !blocked && has_area && (is_diff || scissor.2 > 0 && scissor.3 > 0) {
11504 let clip_ndc_tl = to_ndc(
11505 transformed.x,
11506 transformed.y,
11507 transformed.w,
11508 transformed.h,
11509 current_target_size.0,
11510 current_target_size.1,
11511 );
11512 let inst = ClipInstance {
11513 xywh: [
11514 clip_ndc_tl[0] + clip_ndc_tl[2] * 0.5,
11515 clip_ndc_tl[1] + clip_ndc_tl[3] * 0.5,
11516 clip_ndc_tl[2],
11517 clip_ndc_tl[3],
11518 ],
11519 radii: radius.map(|r| r.0),
11520 fwd_mat: [1.0, 0.0, 0.0, 1.0],
11521 };
11522 let bytes = bytemuck::bytes_of(&inst);
11523 if self
11524 .clip_ring
11525 .grow_to_fit(
11526 &self.device,
11527 encoder,
11528 u64::try_from(bytes.len()).unwrap_or(u64::MAX),
11529 )
11530 .is_ok()
11531 && let Ok(new_off) = self.clip_ring.alloc_write(&self.queue, bytes)
11532 {
11533 off = new_off;
11534 applied = true;
11535 current_pass.cmds.push(Cmd::ClipPush {
11536 off,
11537 cnt: 1,
11538 scissor,
11539 difference: is_diff,
11540 applied,
11541 });
11542 } else {
11543 blocked = !is_diff;
11544 }
11545 } else if !is_diff {
11546 blocked = true;
11547 }
11548 current_pass.active_scissor = if blocked {
11549 None
11550 } else {
11551 (scissor.2 > 0 && scissor.3 > 0).then_some(scissor)
11552 };
11553 active_clips.push(ActiveClip::Rect {
11554 off,
11555 cnt: u32::from(applied),
11556 rect: transformed,
11557 radii: radius.map(|r| r.0),
11558 scissor,
11559 difference: is_diff,
11560 applied,
11561 blocked,
11562 });
11563 }
11564 SceneNode::PushShapeClip { rect, resolved, op } => {
11565 flush_batch!();
11566
11567 let is_diff = matches!(op, repose_core::ClipOp::Difference);
11568 let t_identity = Transform::identity();
11569 let current_transform = transform_stack.last().unwrap_or(&t_identity);
11570 let has_inverse = active_clips.iter().any(ActiveClip::difference);
11571 let mut blocked =
11572 current_pass.active_scissor.is_none() || (has_inverse && !is_diff);
11573 if has_inverse && is_diff {
11574 log::error!(
11575 "unsupported clip nesting: Difference cannot contain a Difference clip"
11576 );
11577 blocked = true;
11578 }
11579
11580 if let ResolvedShape::Rect(radii) = resolved {
11581 let transformed = affine_aabb(current_transform, rect);
11582 let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
11583 let next_scissor = if is_diff {
11584 top
11585 } else {
11586 intersect(top, transformed)
11587 };
11588 scissor_stack.push(next_scissor);
11589 let scissor = to_scissor(
11590 &next_scissor,
11591 current_target_size.0 as u32,
11592 current_target_size.1 as u32,
11593 );
11594 let has_area = transformed.x.is_finite()
11595 && transformed.y.is_finite()
11596 && transformed.w.is_finite()
11597 && transformed.h.is_finite()
11598 && transformed.w > 0.0
11599 && transformed.h > 0.0;
11600 let mut applied = false;
11601 let mut off = 0;
11602 if !blocked && has_area && (is_diff || scissor.2 > 0 && scissor.3 > 0) {
11603 let clip_ndc_tl = to_ndc(
11604 transformed.x,
11605 transformed.y,
11606 transformed.w,
11607 transformed.h,
11608 current_target_size.0,
11609 current_target_size.1,
11610 );
11611 let inst = ClipInstance {
11612 xywh: [
11613 clip_ndc_tl[0] + clip_ndc_tl[2] * 0.5,
11614 clip_ndc_tl[1] + clip_ndc_tl[3] * 0.5,
11615 clip_ndc_tl[2],
11616 clip_ndc_tl[3],
11617 ],
11618 radii: radii.map(|r| r.0),
11619 fwd_mat: [1.0, 0.0, 0.0, 1.0],
11620 };
11621 let bytes = bytemuck::bytes_of(&inst);
11622 if self
11623 .clip_ring
11624 .grow_to_fit(
11625 &self.device,
11626 encoder,
11627 u64::try_from(bytes.len()).unwrap_or(u64::MAX),
11628 )
11629 .is_ok()
11630 && let Ok(new_off) = self.clip_ring.alloc_write(&self.queue, bytes)
11631 {
11632 off = new_off;
11633 applied = true;
11634 current_pass.cmds.push(Cmd::ClipPush {
11635 off,
11636 cnt: 1,
11637 scissor,
11638 difference: is_diff,
11639 applied,
11640 });
11641 } else {
11642 blocked = !is_diff;
11643 }
11644 } else if !is_diff {
11645 blocked = true;
11646 }
11647 current_pass.active_scissor = if blocked {
11648 None
11649 } else {
11650 (scissor.2 > 0 && scissor.3 > 0).then_some(scissor)
11651 };
11652 active_clips.push(ActiveClip::Rect {
11653 off,
11654 cnt: u32::from(applied),
11655 rect: transformed,
11656 radii: radii.map(|r| r.0),
11657 scissor,
11658 difference: is_diff,
11659 applied,
11660 blocked,
11661 });
11662 } else {
11663 let (mesh, affine, aabb) = match resolved {
11664 ResolvedShape::Ellipse => {
11665 let mesh = tessellate_shape_ellipse(*rect).map(Arc::new);
11666 let affine = combine_mesh_affine(
11667 current_transform,
11668 [1.0, 0.0, 0.0, 1.0, rect.x, rect.y],
11669 );
11670 (mesh, affine, *rect)
11671 }
11672 ResolvedShape::Path { path, offset } => {
11673 let mesh = tessellate_shape_path(path, self.pixels_per_point, None)
11674 .map(Arc::new);
11675 let offset_px = (offset.0.0, offset.1.0);
11676 let affine = combine_mesh_affine(
11677 current_transform,
11678 [1.0, 0.0, 0.0, 1.0, offset_px.0, offset_px.1],
11679 );
11680 let aabb =
11681 shape_path_aabb(path, self.pixels_per_point, offset_px, None);
11682 (mesh, affine, aabb)
11683 }
11684 ResolvedShape::Rect(_) => unreachable!(),
11685 };
11686 let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
11687 let next = if is_diff { top } else { intersect(top, aabb) };
11688 scissor_stack.push(next);
11689 let scissor = to_scissor(
11690 &next,
11691 current_target_size.0 as u32,
11692 current_target_size.1 as u32,
11693 );
11694 let has_area = aabb.x.is_finite()
11695 && aabb.y.is_finite()
11696 && aabb.w.is_finite()
11697 && aabb.h.is_finite()
11698 && aabb.w > 0.0
11699 && aabb.h > 0.0
11700 && mesh.as_ref().is_some_and(|mesh| {
11701 !mesh.vertices.is_empty() && !mesh.indices.is_empty()
11702 });
11703 let mut uoff = 0;
11704 let mut ioff = 0;
11705 let mut icnt = 0;
11706 let mut pushed = false;
11707 if !blocked
11708 && has_area
11709 && (if is_diff {
11710 visible(aabb, top)
11711 } else {
11712 scissor.2 > 0 && scissor.3 > 0
11713 })
11714 {
11715 if let Some(mesh_arc) = mesh.as_ref()
11716 && let Some(mesh_gpu) = self.upload_mesh_geometry(mesh_arc)
11717 && let Some(slot) = self.alloc_mesh_uniform(
11718 mesh_uniform_from_paint(&repose_core::PaintDesc::Solid),
11719 )
11720 && let Some((run_off, run_cnt)) =
11721 self.alloc_mesh_instances(&[affine])
11722 {
11723 uoff = slot;
11724 ioff = run_off;
11725 icnt = run_cnt;
11726 pushed = true;
11727 current_pass.cmds.push(Cmd::VectorClipPush {
11728 mesh: mesh_gpu.clone(),
11729 uoff,
11730 ioff,
11731 icnt,
11732 scissor,
11733 difference: is_diff,
11734 applied: true,
11735 });
11736 active_clips.push(ActiveClip::Vector {
11737 mesh: Some(mesh_gpu),
11738 source: mesh_arc.clone(),
11739 uoff,
11740 ioff,
11741 icnt,
11742 affine,
11743 scissor,
11744 difference: is_diff,
11745 applied: true,
11746 blocked,
11747 });
11748 } else {
11749 blocked = !is_diff;
11750 }
11751 } else if !is_diff {
11752 blocked = true;
11753 }
11754 if !pushed {
11755 match mesh {
11756 Some(source) => active_clips.push(ActiveClip::Vector {
11757 mesh: None,
11758 source,
11759 uoff,
11760 ioff,
11761 icnt,
11762 affine,
11763 scissor,
11764 difference: is_diff,
11765 applied: false,
11766 blocked,
11767 }),
11768 None => active_clips.push(ActiveClip::Rect {
11769 off: 0,
11770 cnt: 0,
11771 rect: aabb,
11772 radii: [0.0; 4],
11773 scissor,
11774 difference: is_diff,
11775 applied: false,
11776 blocked: true,
11777 }),
11778 }
11779 }
11780 current_pass.active_scissor = if blocked {
11781 None
11782 } else {
11783 (scissor.2 > 0 && scissor.3 > 0).then_some(scissor)
11784 };
11785 }
11786 }
11787 SceneNode::PopClip => {
11788 flush_batch!();
11789
11790 if scissor_stack.is_empty() || active_clips.is_empty() {
11791 log::error!("PopClip does not match an active clip");
11792 } else {
11793 scissor_stack.pop();
11794 }
11795 let clip = active_clips.pop();
11796 let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
11797 let scissor = to_scissor(
11798 &top,
11799 current_target_size.0 as u32,
11800 current_target_size.1 as u32,
11801 );
11802 current_pass.active_scissor =
11803 (scissor.2 > 0 && scissor.3 > 0).then_some(scissor);
11804 match clip {
11805 Some(ActiveClip::Rect {
11806 off,
11807 cnt,
11808 scissor: stencil_scissor,
11809 difference,
11810 applied,
11811 ..
11812 }) if applied && cnt > 0 => {
11813 current_pass.cmds.push(Cmd::ClipPop {
11814 off,
11815 cnt,
11816 scissor,
11817 stencil_scissor,
11818 difference,
11819 applied: true,
11820 });
11821 }
11822 Some(ActiveClip::Vector {
11823 mesh: Some(mesh),
11824 uoff,
11825 ioff,
11826 icnt,
11827 scissor: stencil_scissor,
11828 difference,
11829 applied,
11830 ..
11831 }) if applied && mesh.vertex_count > 0 && mesh.index_count > 0 => {
11832 current_pass.cmds.push(Cmd::VectorClipPop {
11833 mesh,
11834 uoff,
11835 ioff,
11836 icnt,
11837 scissor,
11838 stencil_scissor,
11839 difference,
11840 applied: true,
11841 });
11842 }
11843 None => {}
11844 _ => {}
11845 }
11846 }
11847 SceneNode::Shadow {
11848 rect,
11849 radius,
11850 elevation: _,
11851 color,
11852 } => {
11853 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
11854 if !visible(affine_aabb(current_transform, rect), clip) {
11855 continue;
11856 }
11857 flush_if_prim_changed!("rect", &self.rects);
11858 let (ndc, fwd_mat) = rect_to_instance_ndc(
11859 *rect,
11860 current_transform,
11861 current_target_size.0,
11862 current_target_size.1,
11863 );
11864 let (_brush_type, color0, _color1, _grad_p0, _grad_p1) =
11865 brush_to_instance_fields(&Brush::Solid(*color));
11866 batch.rects.push(RectInstance {
11867 xywh: ndc,
11868 radii: radius.map(|r| r.0),
11869 color0,
11870 color1: [0.0; 4],
11871 fwd_mat,
11872 grad: [0.0; 4],
11873 bits: 0,
11874 _pad: [0.0; 3],
11875 });
11876 }
11877 SceneNode::PushTransform { transform } => {
11878 flush_batch!(); if transform_is_projective(transform) {
11880 let top = *transform_stack.last().unwrap_or(&t_identity);
11885 self.push_perspective_layer(
11886 *transform,
11887 top,
11888 &mut transform_stack,
11889 &mut scissor_stack,
11890 &mut root_clip_rect,
11891 &mut current_target_size,
11892 &mut current_pass,
11893 &mut active_clips,
11894 &mut passes,
11895 &mut target_stack,
11896 &mut flatten_stack,
11897 &mut flatten_id_head,
11898 &mut next_pass_id,
11899 &mut flatten_ids_used,
11900 encoder,
11901 );
11902 } else {
11903 let combined = current_transform.combine(transform);
11904 transform_stack.push(combined);
11905 }
11906 }
11907 SceneNode::PopTransform => {
11908 flush_batch!(); if let Some(rec) = flatten_stack.last() {
11910 if transform_stack.len() == rec.stack_len + 2 {
11914 let rec = flatten_stack.pop().expect("checked above");
11915 transform_stack.pop();
11916 transform_stack.pop();
11917 self.pop_perspective_layer(
11918 rec,
11919 &mut scissor_stack,
11920 &mut root_clip_rect,
11921 &mut current_target_size,
11922 &mut current_pass,
11923 &mut active_clips,
11924 &mut passes,
11925 &mut target_stack,
11926 &mut next_pass_id,
11927 encoder,
11928 );
11929 continue;
11930 }
11931 }
11932 transform_stack.pop();
11933 }
11934 SceneNode::BeginLayer {
11935 rect,
11936 layer_id,
11937 alpha,
11938 blur_radius_x,
11939 blur_radius_y,
11940 rectangle_edge,
11941 blend_mode,
11942 color_filter,
11943 compositing_strategy,
11944 } => {
11945 flush_batch!();
11946 let width_f = rect.w.round();
11947 let height_f = rect.h.round();
11948 let max_dimension = self.device.limits().max_texture_dimension_2d as f32;
11949 if !width_f.is_finite()
11950 || !height_f.is_finite()
11951 || width_f < 1.0
11952 || height_f < 1.0
11953 || width_f > max_dimension
11954 || height_f > max_dimension
11955 {
11956 log::warn!("BeginLayer dimensions are invalid");
11957 continue;
11958 }
11959 let width = width_f as u32;
11960 let height = height_f as u32;
11961 let parent_scissors =
11962 std::mem::replace(&mut scissor_stack, Vec::with_capacity(8));
11963 let parent_root_clip = std::mem::replace(
11964 &mut root_clip_rect,
11965 repose_core::Rect {
11966 x: 0.0,
11967 y: 0.0,
11968 w: width as f32,
11969 h: height as f32,
11970 },
11971 );
11972 scissor_stack.push(root_clip_rect);
11973 let layer_pass_id = next_pass_id;
11974 next_pass_id += 1;
11975 let parent_clips = std::mem::take(&mut active_clips);
11976 let mut layer_pass = Pass {
11977 id: layer_pass_id,
11978 target: PassTarget::Layer(*layer_id),
11979 initial_scissor: (0, 0, width, height),
11980 active_scissor: Some((0, 0, width, height)),
11981 clear_color: Some([0.0, 0.0, 0.0, 0.0]),
11982 cmds: Vec::new(),
11983 };
11984 let parent_transform = *current_transform;
11985 active_clips = self.replay_active_clips(
11986 &parent_clips,
11987 &parent_transform,
11988 (rect.x, rect.y),
11989 (width as f32, height as f32),
11990 &mut layer_pass,
11991 encoder,
11992 );
11993 let saved = std::mem::replace(&mut current_pass, layer_pass);
11994 let layer_projective = transform_is_projective(current_transform);
11995 if let Some(top) = transform_stack.last_mut() {
11996 *top = Transform::identity();
11997 }
11998 layer_stack.push(LayerState {
11999 layer_id: *layer_id,
12000 parent_target: saved.target,
12001 parent_scissors,
12002 parent_root_clip,
12003 parent_size: current_target_size,
12004 parent_transform,
12005 parent_scissor: saved.active_scissor,
12006 parent_clips,
12007 alpha: *alpha,
12008 blur: (blur_radius_x.0, blur_radius_y.0),
12009 rectangle_edge: *rectangle_edge,
12010 blend_mode: *blend_mode,
12011 color_filter: *color_filter,
12012 compositing_strategy: *compositing_strategy,
12013 projective: layer_projective,
12014 });
12015 passes.push(saved);
12016 if self.get_or_create_layer(*layer_id, width, height, *rect, false) {
12021 self.producer_layer_ids.insert(*layer_id);
12022 }
12023 current_target_size = (width as f32, height as f32);
12024 }
12025 SceneNode::EndLayer { layer_id } => {
12026 flush_batch!();
12027 if layer_stack.last().map(|state| state.layer_id) != Some(*layer_id) {
12028 log::warn!("EndLayer {} does not match active layer", layer_id);
12029 continue;
12030 }
12031 let state = layer_stack.pop().expect("checked above");
12032 scissor_stack = state.parent_scissors;
12033 root_clip_rect = state.parent_root_clip;
12034 active_clips = state.parent_clips;
12035 if let Some(top) = transform_stack.last_mut() {
12036 *top = state.parent_transform;
12037 }
12038 current_target_size = state.parent_size;
12039 let resumed_pass_id = next_pass_id;
12040 next_pass_id += 1;
12041 let saved = std::mem::replace(
12042 &mut current_pass,
12043 Pass {
12044 id: resumed_pass_id,
12045 target: state.parent_target,
12046 initial_scissor: state.parent_scissor.unwrap_or((0, 0, 1, 1)),
12047 active_scissor: state.parent_scissor,
12048 clear_color: None,
12049 cmds: Vec::new(),
12050 },
12051 );
12052 passes.push(saved);
12053 let Some(layer) = self.layer_pool.get(layer_id).cloned() else {
12054 continue;
12055 };
12056 let layer_rect = repose_core::Rect {
12057 x: layer.rect_px.0,
12058 y: layer.rect_px.1,
12059 w: layer.rect_px.2,
12060 h: layer.rect_px.3,
12061 };
12062 let local_layer_rect = affine_aabb(&state.parent_transform, &layer_rect);
12063 let (parent_width, parent_height) = state.parent_size;
12064 let parent_clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
12065 let composite_rect = if state.blur.0 > 0.0 || state.blur.1 > 0.0 {
12066 let pad_x = blur_pad(state.blur.0);
12067 let pad_y = blur_pad(state.blur.1);
12068 repose_core::Rect {
12069 x: local_layer_rect.x - pad_x,
12070 y: local_layer_rect.y - pad_y,
12071 w: local_layer_rect.w + pad_x * 2.0,
12072 h: local_layer_rect.h + pad_y * 2.0,
12073 }
12074 } else {
12075 local_layer_rect
12076 };
12077 let shadow_follows = shadow_layer_ids.contains(layer_id);
12078 if !visible(composite_rect, parent_clip) {
12079 continue;
12080 }
12081 let group_color = layer_group_color(state.alpha, state.color_filter);
12082 let needs_isolation = state.blend_mode.needs_isolation()
12083 || color_filter_fields(state.color_filter).1 != 0
12084 || matches!(state.compositing_strategy, CompositingStrategy::Offscreen);
12085 let scissor = to_scissor(
12086 &parent_clip,
12087 parent_width.max(1.0) as u32,
12088 parent_height.max(1.0) as u32,
12089 );
12090 let mut composite = None;
12091
12092 if needs_isolation && state.blur.0 <= 0.0 && state.blur.1 <= 0.0 {
12093 if state.projective {
12094 let map = state.parent_transform.projective_matrix();
12098 let parent_bounds = repose_core::Rect {
12099 x: 0.0,
12100 y: 0.0,
12101 w: parent_width,
12102 h: parent_height,
12103 };
12104 let projected = projected_rect(&map, layer_rect);
12105 let intersected = intersect(projected, parent_bounds);
12106 let ox = intersected.x.floor();
12107 let oy = intersected.y.floor();
12108 let mut shifted = map;
12109 shifted[0] -= ox * map[6];
12110 shifted[1] -= ox * map[7];
12111 shifted[2] -= ox * map[8];
12112 shifted[3] -= oy * map[6];
12113 shifted[4] -= oy * map[7];
12114 shifted[5] -= oy * map[8];
12115 let uv_bounds = uv_for_layer(&layer);
12116 let uv = [0.0, 0.0, uv_bounds.0, uv_bounds.1];
12117 composite = self.emit_isolated_blend_source(
12118 projected,
12119 state.blend_mode,
12120 group_color,
12121 state.color_filter,
12122 &state.parent_transform,
12123 &mut current_pass,
12124 &active_clips,
12125 &mut passes,
12126 &mut flatten_id_head,
12127 &mut next_pass_id,
12128 &mut flatten_ids_used,
12129 scissor,
12130 encoder,
12131 parent_width,
12132 parent_height,
12133 |slf, pass, _local, w, h, encoder| {
12134 let Some(inst) = make_projective_instance(
12135 &shifted,
12136 layer_rect,
12137 w,
12138 h,
12139 uv,
12140 1.0,
12141 [1.0, 1.0, 1.0],
12142 ) else {
12143 return;
12144 };
12145 if slf
12146 .projective_ring
12147 .grow_to_fit(
12148 &slf.device,
12149 encoder,
12150 std::mem::size_of::<ProjectiveInstance>() as u64,
12151 )
12152 .is_err()
12153 {
12154 return;
12155 }
12156 let Ok(off) = slf
12157 .projective_ring
12158 .alloc_write(&slf.queue, bytemuck::bytes_of(&inst))
12159 else {
12160 return;
12161 };
12162 pass.cmds.push(Cmd::CompositeProjective {
12163 off,
12164 cnt: 1,
12165 layer_id: *layer_id,
12166 blend: BlendMode::Alpha,
12167 });
12168 },
12169 );
12170 } else {
12171 let parent_bounds = repose_core::Rect {
12172 x: 0.0,
12173 y: 0.0,
12174 w: parent_width,
12175 h: parent_height,
12176 };
12177 let origin = intersect(local_layer_rect, parent_bounds);
12178 let ox = origin.x.floor();
12179 let oy = origin.y.floor();
12180 composite = self.emit_isolated_blend_source(
12181 local_layer_rect,
12182 state.blend_mode,
12183 group_color,
12184 state.color_filter,
12185 &state.parent_transform,
12186 &mut current_pass,
12187 &active_clips,
12188 &mut passes,
12189 &mut flatten_id_head,
12190 &mut next_pass_id,
12191 &mut flatten_ids_used,
12192 scissor,
12193 encoder,
12194 parent_width,
12195 parent_height,
12196 |slf, pass, _local, w, h, encoder| {
12197 let ndc = to_ndc(
12198 local_layer_rect.x - ox,
12199 local_layer_rect.y - oy,
12200 local_layer_rect.w,
12201 local_layer_rect.h,
12202 w,
12203 h,
12204 );
12205 let inst = GlyphInstance {
12206 xywh: [
12207 ndc[0] + ndc[2] * 0.5,
12208 ndc[1] + ndc[3] * 0.5,
12209 ndc[2],
12210 ndc[3],
12211 ],
12212 uv: [0.0, 1.0, 1.0, 0.0],
12213 color: [1.0, 1.0, 1.0, 1.0],
12214 fwd_mat: [1.0, 0.0, 0.0, 1.0],
12215 };
12216 if let Some((off, cnt)) = slf.glyph_color.upload(
12217 &slf.device,
12218 &slf.queue,
12219 encoder,
12220 &[inst],
12221 ) {
12222 pass.cmds.push(Cmd::CompositeLayer {
12223 off,
12224 cnt,
12225 layer_id: *layer_id,
12226 blend: BlendMode::Alpha,
12227 color: [1.0, 1.0, 1.0, 1.0],
12228 });
12229 }
12230 },
12231 );
12232 }
12233 } else {
12234 if needs_isolation {
12235 log::warn!(
12236 "advanced layer blend/color-filter with content blur is not supported"
12237 );
12238 }
12239 if state.blur.0 > 0.0 || state.blur.1 > 0.0 {
12240 flush_batch!();
12241 let pad_x = blur_pad(state.blur.0);
12242 let pad_y = blur_pad(state.blur.1);
12243 let rect = repose_core::Rect {
12244 x: local_layer_rect.x - pad_x,
12245 y: local_layer_rect.y - pad_y,
12246 w: local_layer_rect.w + pad_x * 2.0,
12247 h: local_layer_rect.h + pad_y * 2.0,
12248 };
12249 let ndc =
12250 to_ndc(rect.x, rect.y, rect.w, rect.h, parent_width, parent_height);
12251 let edge_mode = if state.rectangle_edge { 0 } else { 1 };
12252 let sigma = [blur_sigma(state.blur.0), blur_sigma(state.blur.1)];
12253 if let Some(scratch_id) = self.emit_separable_blur(
12254 *layer_id,
12255 BLUR_SLOT_CONTENT,
12256 sigma,
12257 (pad_x, pad_y),
12258 (0.0, 0.0),
12259 edge_mode,
12260 false,
12261 [0.0; 4],
12262 &mut passes,
12263 &mut current_pass,
12264 &mut next_pass_id,
12265 encoder,
12266 ) {
12267 let inst = BlurInstance {
12268 xywh: [
12269 ndc[0] + ndc[2] * 0.5,
12270 ndc[1] + ndc[3] * 0.5,
12271 ndc[2],
12272 ndc[3],
12273 ],
12274 uv: [0.0, 0.0, 1.0, 1.0],
12275 color: group_color,
12276 sigma_px: sigma,
12277 fwd_mat: [1.0, 0.0, 0.0, 1.0],
12278 axis: 1,
12279 edge_mode,
12280 shape: [0.0; 4],
12281 };
12282 if let Some(off) = self.upload_blur_instance(&inst, encoder) {
12283 composite = Some(Cmd::CompositeBlur {
12284 off,
12285 cnt: 1,
12286 layer_id: scratch_id,
12287 blend: state.blend_mode,
12288 });
12289 }
12290 }
12291 }
12292 if composite.is_none() {
12295 let ndc = to_ndc(
12296 local_layer_rect.x,
12297 local_layer_rect.y,
12298 local_layer_rect.w,
12299 local_layer_rect.h,
12300 parent_width,
12301 parent_height,
12302 );
12303 if state.projective {
12304 let map = state.parent_transform.projective_matrix();
12305 let uv = uv_for_layer(&layer);
12306 if let Some(inst) = make_projective_instance(
12307 &map,
12308 layer_rect,
12309 parent_width,
12310 parent_height,
12311 [0.0, 0.0, uv.0, uv.1],
12312 group_color[3],
12313 [group_color[0], group_color[1], group_color[2]],
12314 ) && self
12315 .projective_ring
12316 .grow_to_fit(
12317 &self.device,
12318 encoder,
12319 std::mem::size_of::<ProjectiveInstance>() as u64,
12320 )
12321 .is_ok()
12322 {
12323 if let Ok(off) = self
12324 .projective_ring
12325 .alloc_write(&self.queue, bytemuck::bytes_of(&inst))
12326 {
12327 composite = Some(Cmd::CompositeProjective {
12328 off,
12329 cnt: 1,
12330 layer_id: *layer_id,
12331 blend: state.blend_mode,
12332 });
12333 }
12334 }
12335 } else {
12336 let inst = GlyphInstance {
12337 xywh: [
12338 ndc[0] + ndc[2] * 0.5,
12339 ndc[1] + ndc[3] * 0.5,
12340 ndc[2],
12341 ndc[3],
12342 ],
12343 uv: [0.0, 1.0, 1.0, 0.0],
12344 color: group_color,
12345 fwd_mat: [1.0, 0.0, 0.0, 1.0],
12346 };
12347 composite = self
12348 .glyph_color
12349 .upload(&self.device, &self.queue, encoder, &[inst])
12350 .map(|(off, cnt)| Cmd::CompositeLayer {
12351 off,
12352 cnt,
12353 layer_id: *layer_id,
12354 blend: state.blend_mode,
12355 color: group_color,
12356 });
12357 }
12358 }
12359 }
12360 if let Some(command) = composite {
12361 if shadow_follows {
12362 pending_layer_composite = Some(command);
12363 } else {
12364 current_pass.cmds.push(command);
12365 }
12366 }
12367 }
12368 SceneNode::CompositeShadow {
12369 layer_id,
12370 blur_px,
12371 offset_px,
12372 color,
12373 shape_px,
12374 spread_px,
12375 inset,
12376 } => {
12377 let sigma = blur_sigma(blur_px.0);
12378 let pad = blur_pad(blur_px.0);
12379 let spread = spread_px.0;
12380 let layer = self.layer_pool.get(layer_id).cloned();
12381 if let Some(layer) = layer {
12382 let layer_rect = repose_core::Rect {
12383 x: layer.rect_px.0,
12384 y: layer.rect_px.1,
12385 w: layer.rect_px.2,
12386 h: layer.rect_px.3,
12387 };
12388 let local_layer_rect =
12389 affine_aabb(transform_stack.last().unwrap_or(&t_identity), &layer_rect);
12390 let spread_x = spread.max(-pad).max((1.0 - local_layer_rect.w) * 0.5);
12391 let spread_y = spread.max(-pad).max((1.0 - local_layer_rect.h) * 0.5);
12392 let sx = local_layer_rect.x + offset_px.0.0 - spread_x - pad;
12393 let sy = local_layer_rect.y + offset_px.1.0 - spread_y - pad;
12394 let sw = local_layer_rect.w + 2.0 * (spread_x + pad);
12395 let sh = local_layer_rect.h + 2.0 * (spread_y + pad);
12396 let top_clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
12397 if !visible(
12398 repose_core::Rect {
12399 x: sx,
12400 y: sy,
12401 w: sw,
12402 h: sh,
12403 },
12404 top_clip,
12405 ) || (*inset && !visible(local_layer_rect, top_clip))
12406 {
12407 flush_pending_layer!();
12408 continue;
12409 }
12410 flush_batch!();
12411 let shadow_color = color.to_linear();
12412 let max_r = 0.5 * layer.rect_px.2.min(layer.rect_px.3).max(0.0);
12413 let shape = shape_px.map(|r| r.0.clamp(0.0, max_r));
12414 let scratch_id = self.emit_separable_blur(
12418 *layer_id,
12419 BLUR_SLOT_SHADOW,
12420 [sigma, sigma],
12421 (pad, pad),
12422 (spread_x, spread_y),
12423 1,
12424 true,
12425 shape,
12426 &mut passes,
12427 &mut current_pass,
12428 &mut next_pass_id,
12429 encoder,
12430 );
12431 if let Some(scratch_id) = scratch_id {
12432 let ndc_tl = to_ndc(
12433 sx,
12434 sy,
12435 sw,
12436 sh,
12437 current_target_size.0,
12438 current_target_size.1,
12439 );
12440 let inst = BlurInstance {
12441 xywh: [
12442 ndc_tl[0] + ndc_tl[2] * 0.5,
12443 ndc_tl[1] + ndc_tl[3] * 0.5,
12444 ndc_tl[2],
12445 ndc_tl[3],
12446 ],
12447 uv: [0.0, 0.0, 1.0, 1.0],
12448 color: shadow_color,
12449 sigma_px: [sigma, sigma],
12450 fwd_mat: [1.0, 0.0, 0.0, 1.0],
12451 axis: 1,
12452 edge_mode: 1,
12453 shape: [0.0; 4],
12454 };
12455 if let Some(off) = self.upload_blur_instance(&inst, encoder) {
12456 if *inset {
12457 let inner = intersect(top_clip, local_layer_rect);
12461 let inner_scissor = to_scissor(
12462 &inner,
12463 current_target_size.0 as u32,
12464 current_target_size.1 as u32,
12465 );
12466 let outer_scissor = to_scissor(
12467 &top_clip,
12468 current_target_size.0 as u32,
12469 current_target_size.1 as u32,
12470 );
12471 if inner_scissor.2 > 0
12472 && inner_scissor.3 > 0
12473 && current_pass.active_scissor.is_some()
12474 {
12475 let clip_ndc = to_ndc(
12476 local_layer_rect.x,
12477 local_layer_rect.y,
12478 local_layer_rect.w,
12479 local_layer_rect.h,
12480 current_target_size.0,
12481 current_target_size.1,
12482 );
12483 let clip_inst = ClipInstance {
12484 xywh: [
12485 clip_ndc[0] + clip_ndc[2] * 0.5,
12486 clip_ndc[1] + clip_ndc[3] * 0.5,
12487 clip_ndc[2],
12488 clip_ndc[3],
12489 ],
12490 radii: shape,
12491 fwd_mat: [1.0, 0.0, 0.0, 1.0],
12492 };
12493 let bytes = bytemuck::bytes_of(&clip_inst);
12494 if self
12495 .clip_ring
12496 .grow_to_fit(&self.device, encoder, bytes.len() as u64)
12497 .is_ok()
12498 && let Ok(co) =
12499 self.clip_ring.alloc_write(&self.queue, bytes)
12500 {
12501 let saved_scissor = current_pass.active_scissor;
12502 current_pass.cmds.push(Cmd::ClipPush {
12503 off: co,
12504 cnt: 1,
12505 scissor: inner_scissor,
12506 difference: false,
12507 applied: true,
12508 });
12509 current_pass.active_scissor = Some(inner_scissor);
12510 current_pass.cmds.push(Cmd::CompositeShadow {
12511 off,
12512 cnt: 1,
12513 layer_id: scratch_id,
12514 spread_px: spread,
12515 inset: true,
12516 });
12517 current_pass.cmds.push(Cmd::ClipPop {
12518 off: co,
12519 cnt: 1,
12520 scissor: outer_scissor,
12521 stencil_scissor: inner_scissor,
12522 difference: false,
12523 applied: true,
12524 });
12525 current_pass.active_scissor = saved_scissor;
12526 }
12527 }
12528 } else {
12529 current_pass.cmds.push(Cmd::CompositeShadow {
12530 off,
12531 cnt: 1,
12532 layer_id: scratch_id,
12533 spread_px: spread,
12534 inset: false,
12535 });
12536 }
12537 }
12538 }
12539 }
12540 flush_pending_layer!();
12541 }
12542 SceneNode::VectorMesh {
12543 mesh,
12544 transform,
12545 paint,
12546 clip: _,
12547 blend,
12548 } => {
12549 let affine = combine_mesh_affine(current_transform, *transform);
12550 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
12551 if !visible(mesh_aabb(mesh, affine), clip) {
12552 continue;
12553 }
12554 flush_batch!();
12555 let needs_isolated = mesh_blend_needs_isolation(*blend, mesh, paint);
12556 if needs_isolated {
12557 let blend_scissor = to_scissor(
12558 &scissor_stack.last().copied().unwrap_or(root_clip_rect),
12559 current_target_size.0 as u32,
12560 current_target_size.1 as u32,
12561 );
12562 self.emit_isolated_blend(
12563 mesh.clone(),
12564 *transform,
12565 *paint,
12566 *blend,
12567 [1.0, 1.0, 1.0, 1.0],
12568 ColorFilter::None,
12569 current_transform,
12570 &mut current_pass,
12571 &active_clips,
12572 &mut passes,
12573 &mut flatten_id_head,
12574 &mut next_pass_id,
12575 &mut flatten_ids_used,
12576 blend_scissor,
12577 encoder,
12578 fb_w,
12579 fb_h,
12580 );
12581 } else {
12582 let t_identity = Transform::identity();
12583 let current_transform = transform_stack.last().unwrap_or(&t_identity);
12584 self.emit_vector_mesh(
12585 current_transform,
12586 mesh,
12587 *transform,
12588 paint,
12589 *blend,
12590 &mut current_pass.cmds,
12591 );
12592 }
12593 }
12594 SceneNode::VectorMeshInstanced {
12595 mesh,
12596 transforms,
12597 paint,
12598 blend,
12599 } => {
12600 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
12601 let t_identity = Transform::identity();
12602 let current_transform = transform_stack.last().unwrap_or(&t_identity);
12603 let live: Vec<[f32; 6]> = transforms
12606 .iter()
12607 .copied()
12608 .filter(|transform| {
12609 let affine = combine_mesh_affine(current_transform, *transform);
12610 visible(mesh_aabb(mesh, affine), clip)
12611 })
12612 .collect();
12613 if live.is_empty() {
12614 continue;
12615 }
12616 flush_batch!();
12617 if mesh_blend_needs_isolation(*blend, mesh, paint) {
12618 for transform in &live {
12621 self.emit_vector_mesh(
12622 current_transform,
12623 mesh,
12624 *transform,
12625 paint,
12626 *blend,
12627 &mut current_pass.cmds,
12628 );
12629 }
12630 } else {
12631 self.emit_vector_mesh_affines(
12632 current_transform,
12633 mesh,
12634 &live,
12635 paint,
12636 *blend,
12637 &mut current_pass.cmds,
12638 );
12639 }
12640 }
12641 SceneNode::VectorOverlay { meshes } => {
12642 let clip = scissor_stack.last().copied().unwrap_or(root_clip_rect);
12643 let has_visible = meshes
12644 .iter()
12645 .any(|mesh| visible(mesh_aabb(mesh, [1.0, 0.0, 0.0, 0.0, 1.0, 0.0]), clip));
12646 if !has_visible {
12647 continue;
12648 }
12649 flush_batch!();
12650 for (index, m) in meshes.iter().enumerate() {
12651 if !visible(mesh_aabb(m, [1.0, 0.0, 0.0, 0.0, 1.0, 0.0]), clip) {
12652 continue;
12653 }
12654 let Some(mesh_gpu) = self.upload_overlay_mesh(meshes, index) else {
12655 continue;
12656 };
12657 let Some(uoff) = self.alloc_mesh_uniform(MeshUniform::identity()) else {
12658 continue;
12659 };
12660 let Some((ioff, icnt)) = self.alloc_mesh_instances(&[IDENTITY_AFFINE])
12661 else {
12662 continue;
12663 };
12664 current_pass.cmds.push(Cmd::VectorOverlay {
12665 mesh: mesh_gpu,
12666 uoff,
12667 ioff,
12668 icnt,
12669 });
12670 }
12671 }
12672 SceneNode::PushVectorClip { mesh, op } => {
12673 flush_batch!();
12674 let difference = matches!(op, repose_core::ClipOp::Difference);
12675 let t_identity = Transform::identity();
12676 let current_transform = transform_stack.last().unwrap_or(&t_identity);
12677 let affine =
12678 combine_mesh_affine(current_transform, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
12679 let aabb = mesh_aabb(mesh, affine);
12680 let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
12681 let next = if difference {
12682 top
12683 } else {
12684 intersect(top, aabb)
12685 };
12686 scissor_stack.push(next);
12687 let scissor = to_scissor(
12688 &next,
12689 current_target_size.0 as u32,
12690 current_target_size.1 as u32,
12691 );
12692 let has_inverse = active_clips.iter().any(ActiveClip::difference);
12693 let mut blocked = current_pass.active_scissor.is_none() || has_inverse;
12694 if has_inverse {
12695 log::error!(
12696 "unsupported clip nesting: a Difference clip cannot contain another vector clip"
12697 );
12698 }
12699 let has_area = aabb.x.is_finite()
12700 && aabb.y.is_finite()
12701 && aabb.w.is_finite()
12702 && aabb.h.is_finite()
12703 && aabb.w > 0.0
12704 && aabb.h > 0.0;
12705 let mut applied = false;
12706 let mut geometry = None;
12707 let mut uoff = 0;
12708 let mut ioff = 0;
12709 let mut icnt = 0;
12710 if !blocked
12711 && has_area
12712 && (if difference {
12713 visible(aabb, top)
12714 } else {
12715 scissor.2 > 0 && scissor.3 > 0
12716 })
12717 {
12718 if let Some(mesh_gpu) = self.upload_mesh_geometry(mesh)
12719 && let Some(slot) = self.alloc_mesh_uniform(mesh_uniform_from_paint(
12720 &repose_core::PaintDesc::Solid,
12721 ))
12722 && let Some((run_off, run_cnt)) = self.alloc_mesh_instances(&[affine])
12723 {
12724 geometry = Some(mesh_gpu.clone());
12725 uoff = slot;
12726 ioff = run_off;
12727 icnt = run_cnt;
12728 applied = true;
12729 current_pass.cmds.push(Cmd::VectorClipPush {
12730 mesh: mesh_gpu,
12731 uoff,
12732 ioff,
12733 icnt,
12734 scissor,
12735 difference,
12736 applied,
12737 });
12738 } else {
12739 blocked = !difference;
12740 }
12741 } else if !difference {
12742 blocked = true;
12743 }
12744 current_pass.active_scissor = if blocked {
12745 None
12746 } else {
12747 (scissor.2 > 0 && scissor.3 > 0).then_some(scissor)
12748 };
12749 active_clips.push(ActiveClip::Vector {
12750 mesh: geometry,
12751 source: mesh.clone(),
12752 uoff,
12753 ioff,
12754 icnt,
12755 affine,
12756 scissor,
12757 difference,
12758 applied,
12759 blocked,
12760 });
12761 }
12762 SceneNode::PopVectorClip => {
12763 flush_batch!();
12764 if scissor_stack.is_empty() || active_clips.is_empty() {
12765 log::error!("PopVectorClip does not match an active clip");
12766 } else {
12767 scissor_stack.pop();
12768 }
12769 let clip = active_clips.pop();
12770 let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
12771 let scissor = to_scissor(
12772 &top,
12773 current_target_size.0 as u32,
12774 current_target_size.1 as u32,
12775 );
12776 current_pass.active_scissor =
12777 (scissor.2 > 0 && scissor.3 > 0).then_some(scissor);
12778 match clip {
12779 Some(ActiveClip::Vector {
12780 mesh: Some(mesh),
12781 uoff,
12782 ioff,
12783 icnt,
12784 scissor: stencil_scissor,
12785 difference,
12786 applied,
12787 ..
12788 }) if applied && mesh.vertex_count > 0 && mesh.index_count > 0 => {
12789 current_pass.cmds.push(Cmd::VectorClipPop {
12790 mesh,
12791 uoff,
12792 ioff,
12793 icnt,
12794 scissor,
12795 stencil_scissor,
12796 difference,
12797 applied: true,
12798 });
12799 }
12800 Some(ActiveClip::Rect { .. }) => {
12801 log::error!("PopVectorClip matched a rounded-rect clip");
12802 }
12803 None => {}
12804 _ => {}
12805 }
12806 }
12807 SceneNode::Callback { rect, payload } => {
12808 let t = transform_stack
12809 .last()
12810 .copied()
12811 .unwrap_or(Transform::identity());
12812 let transformed = affine_aabb(&t, rect);
12813 let top = scissor_stack.last().copied().unwrap_or(root_clip_rect);
12814 let clip_rect = intersect(transformed, top);
12815 let scissor = to_scissor(
12816 &clip_rect,
12817 current_target_size.0 as u32,
12818 current_target_size.1 as u32,
12819 );
12820 let restore_scissor = to_scissor(
12821 &top,
12822 current_target_size.0 as u32,
12823 current_target_size.1 as u32,
12824 );
12825 if current_pass.active_scissor.is_none()
12826 || !visible(transformed, top)
12827 || scissor.2 == 0
12828 || scissor.3 == 0
12829 {
12830 continue;
12831 }
12832 flush_batch!();
12833 current_pass.cmds.push(Cmd::Callback {
12834 rect: transformed,
12835 clip_rect,
12836 scissor,
12837 restore_scissor,
12838 callback_id: Arc::as_ptr(payload) as *const () as usize,
12839 payload: payload.clone(),
12840 });
12841 }
12842 _ => {}
12843 }
12844 }
12845
12846 flush_pending_layer!();
12847 flush_batch!();
12848 passes.push(current_pass);
12849
12850 if !shape_stops.is_empty() {
12851 let rows = shape_stops.len().min(MAX_SHAPE_GRADIENT_TABLES as usize) as u32;
12852 let mut pixels =
12853 Vec::with_capacity((rows as usize) * (SHAPE_STOPS_TEXELS as usize) * 4);
12854 for table in shape_stops.iter().take(rows as usize) {
12855 for texel in table.texels {
12856 pixels.extend_from_slice(&texel);
12857 }
12858 }
12859 self.queue.write_texture(
12860 wgpu::TexelCopyTextureInfo {
12861 texture: &self.shape_stops_tex,
12862 mip_level: 0,
12863 origin: wgpu::Origin3d::ZERO,
12864 aspect: wgpu::TextureAspect::All,
12865 },
12866 bytemuck::cast_slice(&pixels),
12867 wgpu::TexelCopyBufferLayout {
12868 offset: 0,
12869 bytes_per_row: Some(SHAPE_STOPS_TEXELS * 4 * 4),
12870 rows_per_image: Some(MAX_SHAPE_GRADIENT_TABLES),
12871 },
12872 wgpu::Extent3d {
12873 width: SHAPE_STOPS_TEXELS,
12874 height: rows,
12875 depth_or_array_layers: 1,
12876 },
12877 );
12878 }
12879
12880 {
12881 let mut seen: std::collections::HashSet<usize> = std::collections::HashSet::new();
12882 let mut prepare_list: Vec<(usize, Arc<Callback>)> = Vec::new();
12883 for pass in &passes {
12884 for command in &pass.cmds {
12885 if let Cmd::Callback { payload, .. } = command
12886 && payload.downcast_ref::<Callback>().is_some()
12887 {
12888 let ptr = Arc::as_ptr(payload) as *const () as usize;
12889 if seen.insert(ptr)
12890 && let Ok(cb_arc) = payload.clone().downcast::<Callback>()
12891 {
12892 prepare_list.push((ptr, cb_arc));
12893 }
12894 }
12895 }
12896 }
12897 if !prepare_list.is_empty() {
12898 let mut callback_targets: HashMap<usize, Vec<(PassTarget, ScreenDescriptor)>> =
12899 HashMap::new();
12900 for pass in &passes {
12901 let (size, target_format, sample_count) = match pass.target {
12902 PassTarget::Surface => (
12903 [self.output_width, self.output_height],
12904 if self.working_space {
12905 wgpu::TextureFormat::Rgba16Float
12906 } else {
12907 self.output_format
12908 },
12909 self.active_surface_msaa_samples(),
12910 ),
12911 PassTarget::Layer(layer_id) => {
12912 let layer = self.layer_pool.get(&layer_id);
12913 (
12914 layer.map_or([self.output_width, self.output_height], |layer| {
12915 [layer.width, layer.height]
12916 }),
12917 self.layer_target_format(),
12918 1,
12919 )
12920 }
12921 };
12922 for command in &pass.cmds {
12923 if let Cmd::Callback { payload, .. } = command {
12924 let descriptor = ScreenDescriptor {
12925 size_in_pixels: size,
12926 pixels_per_point: self.pixels_per_point,
12927 target_format,
12928 sample_count,
12929 };
12930 let targets = callback_targets
12931 .entry(Arc::as_ptr(payload) as *const () as usize)
12932 .or_default();
12933 if !targets.iter().any(|(target, target_desc)| {
12934 *target == pass.target
12935 && target_desc.target_format == descriptor.target_format
12936 && target_desc.sample_count == descriptor.sample_count
12937 }) {
12938 targets.push((pass.target, descriptor));
12939 }
12940 }
12941 }
12942 }
12943
12944 let default_descriptor = ScreenDescriptor {
12945 size_in_pixels: [self.output_width, self.output_height],
12946 pixels_per_point: self.pixels_per_point,
12947 target_format: if self.working_space {
12948 wgpu::TextureFormat::Rgba16Float
12949 } else {
12950 self.output_format
12951 },
12952 sample_count: self.active_surface_msaa_samples(),
12953 };
12954 let default_descriptors = [(PassTarget::Surface, default_descriptor)];
12955 let mut prepare_encoder =
12956 self.device
12957 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
12958 label: Some("callback prepare"),
12959 });
12960 let mut finish_encoder =
12961 self.device
12962 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
12963 label: Some("callback finish prepare"),
12964 });
12965 let mut active_callback_scopes = HashSet::new();
12966 for (key, cb) in &prepare_list {
12967 let descriptors = callback_targets
12968 .get(key)
12969 .map(Vec::as_slice)
12970 .unwrap_or(&default_descriptors);
12971 for &(target, screen_desc) in descriptors {
12972 let scope = callback_scope_key(cb, *key, target, &screen_desc);
12973 active_callback_scopes.insert(scope.clone());
12974 if !scope.callback.reusable
12975 && self
12976 .callback_scope_payloads
12977 .get(&scope)
12978 .is_some_and(|payload| payload.upgrade().is_none())
12979 {
12980 self.remove_callback_scope(&scope);
12981 }
12982 let payload: Weak<Callback> = Arc::downgrade(cb);
12983 self.callback_scope_payloads.insert(scope, payload);
12984 }
12985 }
12986 let mut prepare_buffers = Vec::new();
12987 let mut finish_buffers = Vec::new();
12988 for (key, cb) in &prepare_list {
12989 let descriptors = callback_targets
12990 .get(key)
12991 .map(Vec::as_slice)
12992 .unwrap_or(&default_descriptors);
12993 for &(target, screen_desc) in descriptors {
12994 let scope = callback_scope_key(cb, *key, target, &screen_desc);
12995 self.touch_callback_scope(scope.clone());
12996 if !self.callback_scoped_resources.contains_key(&scope)
12997 && self.callback_scoped_resources.len() >= MAX_CALLBACK_SCOPES
12998 {
12999 self.evict_callback_scope(&active_callback_scopes);
13000 }
13001 let resources = self.callback_scoped_resources.entry(scope).or_default();
13002 if !resources.contains::<wgpu::DownlevelCapabilities>()
13007 && let Some(capabilities) =
13008 self.callback_resources.get::<wgpu::DownlevelCapabilities>()
13009 {
13010 resources.insert(capabilities.clone());
13011 }
13012 prepare_buffers.extend(cb.0.prepare(
13013 &self.device,
13014 &self.queue,
13015 &mut prepare_encoder,
13016 &screen_desc,
13017 resources,
13018 ));
13019 }
13020 }
13021 for (key, cb) in &prepare_list {
13022 let descriptors = callback_targets
13023 .get(key)
13024 .map(Vec::as_slice)
13025 .unwrap_or(&default_descriptors);
13026 for &(target, screen_desc) in descriptors {
13027 let scope = callback_scope_key(cb, *key, target, &screen_desc);
13028 self.touch_callback_scope(scope.clone());
13029 if let Some(resources) = self.callback_scoped_resources.get_mut(&scope) {
13030 finish_buffers.extend(cb.0.finish_prepare(
13031 &self.device,
13032 &self.queue,
13033 &mut finish_encoder,
13034 &screen_desc,
13035 resources,
13036 ));
13037 }
13038 }
13039 }
13040 let mut callback_buffers =
13041 Vec::with_capacity(2 + prepare_buffers.len() + finish_buffers.len());
13042 callback_buffers.push(prepare_encoder.finish());
13043 callback_buffers.extend(prepare_buffers);
13044 callback_buffers.push(finish_encoder.finish());
13045 callback_buffers.extend(finish_buffers);
13046 self.queue.submit(callback_buffers);
13047 }
13048 }
13049
13050 let globals_bytes = std::mem::size_of::<Globals>() as u64;
13051 if !self.ensure_globals_staging(passes.len()) {
13052 return;
13053 }
13054 for (i, pass) in passes.iter().enumerate() {
13055 let (target_w, target_h) = match pass.target {
13056 PassTarget::Surface => (fb_w, fb_h),
13057 PassTarget::Layer(layer_id) => {
13058 let lt = self.layer_pool.get(&layer_id);
13059 (
13060 lt.map_or(fb_w, |l| l.width as f32),
13061 lt.map_or(fb_h, |l| l.height as f32),
13062 )
13063 }
13064 };
13065 self.queue.write_buffer(
13066 &self.globals_staging,
13067 (i as u64) * globals_bytes,
13068 bytemuck::bytes_of(&make_globals(target_w, target_h)),
13069 );
13070 }
13071
13072 let bind_mask = self.atlas_bind_group_mask();
13073 let bind_color = self.atlas_bind_group_color();
13074 let mut clip_depth: u32 = 0;
13075 let mut clip_depth_stack: Vec<u32> = Vec::new();
13076
13077 let snapshot_source = target_texture.cloned();
13078 let last_surface_pass = passes
13079 .iter()
13080 .rposition(|pass| matches!(pass.target, PassTarget::Surface));
13081 for (pass_index, pass) in std::mem::take(&mut passes).into_iter().enumerate() {
13082 let needs_snapshot = pass
13090 .cmds
13091 .iter()
13092 .any(|c| matches!(c, Cmd::BlendLayer { .. }));
13093 if needs_snapshot {
13094 let copies = std::mem::take(&mut self.blend_copies);
13095 let has_surface_copy = copies.iter().any(|copy| copy.target == PassTarget::Surface);
13096 let mut resolved_surface = None;
13097 if has_surface_copy
13098 && !self.working_space
13099 && let (Some(msaa_view), Some(resolve_view)) =
13100 (self.msaa_view.as_ref(), self.surface_resolve_view.as_ref())
13101 {
13102 let resolve_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
13103 label: Some("surface blend resolve"),
13104 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
13105 view: msaa_view,
13106 resolve_target: Some(resolve_view),
13107 ops: wgpu::Operations {
13108 load: wgpu::LoadOp::Load,
13109 store: wgpu::StoreOp::Store,
13110 },
13111 depth_slice: None,
13112 })],
13113 depth_stencil_attachment: None,
13114 timestamp_writes: None,
13115 occlusion_query_set: None,
13116 multiview_mask: None,
13117 });
13118 drop(resolve_pass);
13119 resolved_surface = self.surface_resolve_tex.clone();
13120 }
13121 let mut remaining = Vec::with_capacity(copies.len());
13122 for copy in copies {
13123 if copy.pass_id != pass.id {
13124 remaining.push(copy);
13125 continue;
13126 }
13127 let BlendCopy {
13128 blend_id,
13129 target,
13130 region,
13131 ..
13132 } = copy;
13133 let (src_tex, tw, th) = match target {
13134 PassTarget::Layer(parent_id) => match self.layer_pool.get(&parent_id) {
13135 Some(lt) => (lt.texture.clone(), lt.width, lt.height),
13136 None => continue,
13137 },
13138 PassTarget::Surface => {
13139 let texture = if self.working_space {
13140 self.ws_tex.clone()
13141 } else if self.msaa_view.is_some() {
13142 resolved_surface.clone()
13143 } else {
13144 snapshot_source.clone()
13145 };
13146 match texture {
13147 Some(texture) => (texture, self.output_width, self.output_height),
13148 None => {
13149 self.remove_blend_snapshot(blend_id);
13150 continue;
13151 }
13152 }
13153 }
13154 };
13155 let Some(dst_tex) = self.blend_snapshot_texture(blend_id) else {
13156 continue;
13157 };
13158 if !src_tex.usage().contains(wgpu::TextureUsages::COPY_SRC)
13159 || !dst_tex.usage().contains(wgpu::TextureUsages::COPY_DST)
13160 {
13161 self.remove_blend_snapshot(blend_id);
13162 continue;
13163 }
13164 let Some((sx, sy, cw, ch)) = checked_copy_region(region, tw, th) else {
13165 self.remove_blend_snapshot(blend_id);
13166 continue;
13167 };
13168 encoder.copy_texture_to_texture(
13169 wgpu::TexelCopyTextureInfo {
13170 texture: &src_tex,
13171 mip_level: 0,
13172 origin: wgpu::Origin3d { x: sx, y: sy, z: 0 },
13173 aspect: wgpu::TextureAspect::All,
13174 },
13175 wgpu::TexelCopyTextureInfo {
13176 texture: &dst_tex,
13177 mip_level: 0,
13178 origin: wgpu::Origin3d::ZERO,
13179 aspect: wgpu::TextureAspect::All,
13180 },
13181 wgpu::Extent3d {
13182 width: cw,
13183 height: ch,
13184 depth_or_array_layers: 1,
13185 },
13186 );
13187 }
13188 self.blend_copies = remaining;
13189 }
13190 let (color_view, resolve_target, depth_stencil_view, is_layer, working_target) =
13191 match pass.target {
13192 PassTarget::Surface => {
13193 let swap_view = target_view.clone();
13194 let use_ws = self.working_space && self.ws_view.is_some();
13195 let (color, resolve) = if use_ws {
13196 let ws_view = self.ws_view.as_ref().unwrap();
13197 if let Some(msaa_view) = &self.ws_msaa_view {
13198 (msaa_view.clone(), Some(ws_view.clone()))
13199 } else {
13200 (ws_view.clone(), None)
13201 }
13202 } else if let Some(msaa_view) = &self.msaa_view {
13203 let resolve =
13208 (Some(pass_index) == last_surface_pass).then(|| swap_view.clone());
13209 (msaa_view.clone(), resolve)
13210 } else {
13211 (swap_view, None)
13212 };
13213 (
13214 color,
13215 resolve,
13216 self.depth_stencil_view.clone(),
13217 false,
13218 use_ws,
13219 )
13220 }
13221 PassTarget::Layer(layer_id) => {
13222 if let Some(lt) = self.layer_pool.get(&layer_id) {
13223 (
13224 lt.view.clone(),
13225 None,
13226 lt.depth_stencil_view.clone(),
13227 true,
13228 false,
13229 )
13230 } else {
13231 log::warn!("missing layer target {layer_id}");
13232 continue;
13233 }
13234 }
13235 };
13236
13237 encoder.copy_buffer_to_buffer(
13238 &self.globals_staging,
13239 (pass_index as u64) * globals_bytes,
13240 &self.globals_buf,
13241 0,
13242 globals_bytes,
13243 );
13244
13245 if is_layer {
13246 clip_depth_stack.push(clip_depth);
13247 clip_depth = 0;
13248 }
13249
13250 let (tw, th) = match pass.target {
13251 PassTarget::Surface => (self.output_width, self.output_height),
13252 PassTarget::Layer(layer_id) => self
13253 .layer_pool
13254 .get(&layer_id)
13255 .map(|l| (l.width, l.height))
13256 .unwrap_or((self.output_width, self.output_height)),
13257 };
13258 let initial_scissor = clamp_scissor(
13259 pass.initial_scissor.0,
13260 pass.initial_scissor.1,
13261 pass.initial_scissor.2,
13262 pass.initial_scissor.3,
13263 tw,
13264 th,
13265 );
13266 let mut active_scissor = pass
13267 .active_scissor
13268 .map(|scissor| clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th));
13269 if active_scissor.is_some_and(|scissor| scissor.2 == 0 || scissor.3 == 0) {
13270 active_scissor = None;
13271 }
13272
13273 let pipes: &Pipelines = if is_layer {
13274 if self.working_space {
13275 &self.working_space_layer_pipes
13276 } else {
13277 &self.layer_pipes
13278 }
13279 } else if working_target {
13280 &self.working_space_pipes
13281 } else {
13282 &self.surface_pipes
13283 };
13284
13285 let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
13286 label: Some("pass"),
13287 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
13288 view: &color_view,
13289 resolve_target: resolve_target.as_ref(),
13290 ops: wgpu::Operations {
13291 load: match pass.clear_color {
13292 Some(c) => wgpu::LoadOp::Clear(wgpu::Color {
13293 r: c[0] as f64,
13294 g: c[1] as f64,
13295 b: c[2] as f64,
13296 a: c[3] as f64,
13297 }),
13298 None => wgpu::LoadOp::Load,
13299 },
13300 store: wgpu::StoreOp::Store,
13301 },
13302 depth_slice: None,
13303 })],
13304 depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
13305 view: &depth_stencil_view,
13306 depth_ops: None,
13307 stencil_ops: Some(wgpu::Operations {
13308 load: if pass.clear_color.is_some() {
13309 wgpu::LoadOp::Clear(STENCIL_BASE)
13310 } else {
13311 wgpu::LoadOp::Load
13312 },
13313 store: wgpu::StoreOp::Store,
13314 }),
13315 }),
13316 timestamp_writes: None,
13317 occlusion_query_set: None,
13318 multiview_mask: None,
13319 });
13320
13321 rpass.set_bind_group(0, &self.globals_bind, &[]);
13322 rpass.set_stencil_reference(STENCIL_BASE + clip_depth);
13323 let initial_draw_scissor = if initial_scissor.2 == 0 || initial_scissor.3 == 0 {
13324 (0, 0, 1, 1)
13325 } else {
13326 initial_scissor
13327 };
13328 rpass.set_scissor_rect(
13329 initial_draw_scissor.0,
13330 initial_draw_scissor.1,
13331 initial_draw_scissor.2,
13332 initial_draw_scissor.3,
13333 );
13334
13335 macro_rules! draw_simple {
13336 ($pipeline:expr, $ring:expr, $inst:ty, $off:ident, $n:ident) => {{
13337 rpass.set_pipeline($pipeline);
13338 rpass.set_bind_group(1, &self.shape_stops_bind, &[]);
13339 let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
13340 rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
13341 rpass.draw(0..6, 0..$n);
13342 }};
13343 }
13344
13345 macro_rules! draw_with_bind {
13346 ($pipeline:expr, $ring:expr, $inst:ty, $bind:expr, $off:ident, $n:ident) => {{
13347 rpass.set_pipeline($pipeline);
13348 rpass.set_bind_group(1, $bind, &[]);
13349 let bytes = ($n as u64) * std::mem::size_of::<$inst>() as u64;
13350 rpass.set_vertex_buffer(0, $ring.buf.slice($off..$off + bytes));
13351 rpass.draw(0..6, 0..$n);
13352 }};
13353 }
13354
13355 macro_rules! draw_indexed_mesh {
13356 ($pipeline:expr, $uoff:ident, $mesh:ident, $ioff:ident, $icnt:ident) => {{
13357 rpass.set_pipeline($pipeline);
13358 rpass.set_bind_group(1, &self.mesh_bind, &[$uoff as u32]);
13359 let vbytes =
13360 ($mesh.vertex_count as u64) * std::mem::size_of::<MeshVertex>() as u64;
13361 rpass.set_vertex_buffer(0, $mesh.vertices.slice(0..vbytes));
13362 let ibytes = ($mesh.index_count as u64) * std::mem::size_of::<u32>() as u64;
13363 rpass.set_index_buffer(
13364 $mesh.indices.slice(0..ibytes),
13365 wgpu::IndexFormat::Uint32,
13366 );
13367 let ibytes = ($icnt as u64) * std::mem::size_of::<MeshInstance>() as u64;
13368 rpass.set_vertex_buffer(1, self.mesh_instance_buf.slice($ioff..$ioff + ibytes));
13369 rpass.draw_indexed(0..$mesh.index_count, 0, 0..$icnt);
13370 }};
13371 }
13372
13373 for cmd in pass.cmds {
13374 if active_scissor.is_none()
13375 && !matches!(
13376 &cmd,
13377 Cmd::ClipPush { .. }
13378 | Cmd::ClipPop { .. }
13379 | Cmd::VectorClipPush { .. }
13380 | Cmd::VectorClipPop { .. }
13381 )
13382 {
13383 continue;
13384 }
13385 match cmd {
13386 Cmd::ClipPush {
13387 off,
13388 cnt: n,
13389 scissor,
13390 difference,
13391 applied,
13392 } => {
13393 let scissor =
13394 clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
13395 let usable = applied && scissor.2 > 0 && scissor.3 > 0;
13396 if usable {
13397 rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
13398 active_scissor = Some(scissor);
13399 rpass.set_pipeline(if difference {
13400 &pipes.clip_dec
13401 } else {
13402 &pipes.clip_bin
13403 });
13404
13405 let bytes = (n as u64) * std::mem::size_of::<ClipInstance>() as u64;
13406 rpass.set_vertex_buffer(0, self.clip_ring.buf.slice(off..off + bytes));
13407 rpass.draw(0..6, 0..n);
13408 if !difference {
13409 clip_depth = (clip_depth + 1).min(STENCIL_MAX_DEPTH);
13410 }
13411 } else {
13412 active_scissor = None;
13413 }
13414 rpass.set_stencil_reference(STENCIL_BASE + clip_depth);
13415 }
13416
13417 Cmd::ClipPop {
13418 off,
13419 cnt: n,
13420 scissor,
13421 stencil_scissor,
13422 difference,
13423 applied,
13424 } => {
13425 let scissor =
13426 clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
13427 let dec = clamp_scissor(
13428 stencil_scissor.0,
13429 stencil_scissor.1,
13430 stencil_scissor.2,
13431 stencil_scissor.3,
13432 tw,
13433 th,
13434 );
13435 if scissor.2 > 0 && scissor.3 > 0 {
13436 rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
13437 active_scissor = Some(scissor);
13438 } else {
13439 active_scissor = None;
13440 }
13441 if applied && n > 0 && dec.2 > 0 && dec.3 > 0 {
13442 rpass.set_scissor_rect(dec.0, dec.1, dec.2, dec.3);
13443 rpass.set_pipeline(if difference {
13444 &pipes.clip_bin
13445 } else {
13446 &pipes.clip_dec
13447 });
13448 let bytes = (n as u64) * std::mem::size_of::<ClipInstance>() as u64;
13449 rpass.set_vertex_buffer(0, self.clip_ring.buf.slice(off..off + bytes));
13450 rpass.draw(0..6, 0..n);
13451 if scissor.2 > 0 && scissor.3 > 0 {
13452 rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
13453 }
13454 if !difference {
13455 clip_depth = clip_depth.saturating_sub(1);
13456 }
13457 }
13458 rpass.set_stencil_reference(STENCIL_BASE + clip_depth);
13459 }
13460
13461 Cmd::Rect { off, cnt: n } => {
13462 draw_simple!(&pipes.rects, self.rects.ring, RectInstance, off, n);
13463 }
13464
13465 Cmd::Border { off, cnt: n } => {
13466 draw_simple!(&pipes.borders, self.borders.ring, BorderInstance, off, n);
13467 }
13468
13469 Cmd::GlyphsMask { off, cnt: n } => {
13470 draw_with_bind!(
13471 &pipes.text_mask,
13472 self.glyph_mask.ring,
13473 GlyphInstance,
13474 &bind_mask,
13475 off,
13476 n
13477 );
13478 }
13479
13480 Cmd::GlyphsColor { off, cnt: n } => {
13481 draw_with_bind!(
13482 &pipes.text_color,
13483 self.glyph_color.ring,
13484 GlyphInstance,
13485 &bind_color,
13486 off,
13487 n
13488 );
13489 }
13490
13491 Cmd::GlyphsVector { off, cnt: n } => {
13492 if let Some(slug_pipe) = pipes.slug.as_ref() {
13493 rpass.set_pipeline(slug_pipe);
13494 let bytes = (n as u64) * std::mem::size_of::<slug::TessVertex>() as u64;
13495 rpass.set_vertex_buffer(0, self.slug_ring.buf.slice(off..off + bytes));
13496 rpass.draw(0..n, 0..1);
13497 }
13498 }
13499
13500 Cmd::ImageRgba {
13501 off,
13502 cnt: n,
13503 handle,
13504 filter,
13505 tile,
13506 blend,
13507 } => {
13508 let bind_opt = match self.images.get(&handle) {
13509 Some(ImageTex::Rgba { binds, .. }) => Some(binds.get(filter, tile)),
13510 Some(ImageTex::User { binds, .. }) => Some(binds.get(filter, tile)),
13511 _ => None,
13512 };
13513 if let Some(bind) = bind_opt {
13514 let pipe = match FIXED_FUNCTION_BLENDS.iter().position(|m| *m == blend)
13515 {
13516 Some(index) => &pipes.image_blends[index],
13517 None => &pipes.image_rgba,
13518 };
13519 draw_with_bind!(
13520 pipe,
13521 self.glyph_color.ring,
13522 GlyphInstance,
13523 bind,
13524 off,
13525 n
13526 );
13527 }
13528 }
13529 Cmd::Coverage {
13530 off,
13531 cnt: n,
13532 handle,
13533 } => {
13534 if let Some(tile) = self.coverages.get(&handle) {
13535 draw_with_bind!(
13536 &pipes.coverage,
13537 self.glyph_color.ring,
13538 GlyphInstance,
13539 &tile.bind,
13540 off,
13541 n
13542 );
13543 }
13544 }
13545
13546 Cmd::ImageNv12 {
13547 off,
13548 cnt: n,
13549 handle,
13550 filter,
13551 blend,
13552 } => {
13553 if let Some(ImageTex::Nv12 { binds, .. }) = self.images.get(&handle) {
13554 let pipe = match FIXED_FUNCTION_BLENDS.iter().position(|m| *m == blend)
13555 {
13556 Some(index) => &pipes.image_nv12_blends[index],
13557 None => &pipes.image_nv12,
13558 };
13559 draw_with_bind!(
13560 pipe,
13561 self.nv12.ring,
13562 Nv12Instance,
13563 binds.get(filter, false),
13564 off,
13565 n
13566 );
13567 }
13568 }
13569
13570 Cmd::Ellipse { off, cnt: n } => {
13571 draw_simple!(&pipes.ellipses, self.ellipses.ring, EllipseInstance, off, n);
13572 }
13573
13574 Cmd::EllipseBorder { off, cnt: n } => {
13575 draw_simple!(
13576 &pipes.ellipse_borders,
13577 self.ellipse_borders.ring,
13578 EllipseBorderInstance,
13579 off,
13580 n
13581 );
13582 }
13583
13584 Cmd::Arc { off, cnt: n } => {
13585 draw_simple!(&pipes.arcs, self.arcs.ring, ArcInstance, off, n);
13586 }
13587
13588 Cmd::CompositeLayer {
13589 off,
13590 cnt: n,
13591 layer_id,
13592 blend,
13593 color: _,
13594 } => {
13595 if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
13596 let pipe = match FIXED_FUNCTION_BLENDS.iter().position(|m| *m == blend)
13597 {
13598 Some(index) => &pipes.image_blends[index],
13599 None => &pipes.image_rgba,
13600 };
13601 draw_with_bind!(
13602 pipe,
13603 self.glyph_color.ring,
13604 GlyphInstance,
13605 <.bind,
13606 off,
13607 n
13608 );
13609 }
13610 }
13611 Cmd::CompositeShadow {
13612 off,
13613 cnt: n,
13614 layer_id,
13615 spread_px: _,
13616 inset,
13617 } => {
13618 if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
13619 draw_with_bind!(
13620 if inset {
13621 &pipes.inset_shadow
13622 } else {
13623 &pipes.blur
13624 },
13625 self.blur_ring,
13626 BlurInstance,
13627 <.bind_linear,
13628 off,
13629 n
13630 );
13631 }
13632 }
13633 Cmd::CompositeBlur {
13634 off,
13635 cnt: n,
13636 layer_id,
13637 blend,
13638 } => {
13639 if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
13640 let pipe = match FIXED_FUNCTION_BLENDS.iter().position(|m| *m == blend)
13641 {
13642 Some(index) => &pipes.blur_content_blends[index],
13643 None => &pipes.blur_content,
13644 };
13645 draw_with_bind!(
13646 pipe,
13647 self.blur_ring,
13648 BlurInstance,
13649 <.bind_linear,
13650 off,
13651 n
13652 );
13653 }
13654 }
13655 Cmd::CompositeProjective {
13656 off,
13657 cnt: n,
13658 layer_id,
13659 blend,
13660 } => {
13661 if let Some(lt) = self.layer_pool.get(&layer_id).cloned() {
13662 let pipe = match FIXED_FUNCTION_BLENDS.iter().position(|m| *m == blend)
13666 {
13667 Some(index) => &pipes.projective_blends[index],
13668 None => &pipes.projective_layer,
13669 };
13670 draw_with_bind!(
13671 pipe,
13672 self.projective_ring,
13673 ProjectiveInstance,
13674 <.bind,
13675 off,
13676 n
13677 );
13678 }
13679 }
13680
13681 Cmd::BlendLayer {
13682 off,
13683 cnt: n,
13684 src_layer,
13685 dst_layer,
13686 parent,
13687 scissor,
13688 } => {
13689 let src = self.layer_pool.get(&src_layer).cloned();
13690 let dst = dst_layer.and_then(|id| self.blend_snapshots.get(&id).cloned());
13697 let in_parent = match parent {
13698 PassTarget::Surface => !is_layer,
13699 PassTarget::Layer(id) => {
13700 matches!(pass.target, PassTarget::Layer(pid) if pid == id)
13701 }
13702 };
13703 if let (Some(src_lt), Some(dst_snap)) = (src, dst)
13704 && in_parent
13705 {
13706 let bytes = (n as u64) * std::mem::size_of::<BlendInstance>() as u64;
13707 rpass.set_pipeline(&pipes.blend_layer);
13708 let scissor =
13709 clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
13710 if scissor.2 > 0 && scissor.3 > 0 {
13711 rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
13712 rpass.set_bind_group(0, &self.globals_bind, &[]);
13713 rpass.set_bind_group(1, &src_lt.bind, &[]);
13714 rpass.set_bind_group(2, &dst_snap.bind, &[]);
13715 rpass.set_vertex_buffer(
13716 0,
13717 self.blend_ring.buf.slice(off..off + bytes),
13718 );
13719 rpass.draw(0..6, 0..n);
13720 }
13721 }
13722 }
13723
13724 Cmd::VectorMesh {
13725 mesh,
13726 uoff,
13727 ioff,
13728 icnt,
13729 blend,
13730 } => {
13731 let pipe = match FIXED_FUNCTION_BLENDS.iter().position(|m| *m == blend) {
13732 Some(index) => &pipes.mesh_blends[index],
13733 None => &pipes.mesh,
13734 };
13735 draw_indexed_mesh!(pipe, uoff, mesh, ioff, icnt);
13736 }
13737
13738 Cmd::VectorOverlay {
13739 mesh,
13740 uoff,
13741 ioff,
13742 icnt,
13743 } => {
13744 rpass.set_stencil_reference(STENCIL_BASE + clip_depth);
13745 draw_indexed_mesh!(&pipes.mesh_overlay, uoff, mesh, ioff, icnt);
13746 }
13747
13748 Cmd::VectorClipPush {
13749 mesh,
13750 uoff,
13751 ioff,
13752 icnt,
13753 scissor,
13754 difference,
13755 applied,
13756 } => {
13757 let scissor =
13758 clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
13759 let usable = applied && scissor.2 > 0 && scissor.3 > 0;
13760 if usable {
13761 rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
13762 active_scissor = Some(scissor);
13763 let pipe = if difference {
13764 &pipes.mesh_clip_dec
13765 } else {
13766 &pipes.mesh_clip_inc
13767 };
13768 draw_indexed_mesh!(pipe, uoff, mesh, ioff, icnt);
13769 if !difference {
13770 clip_depth = (clip_depth + 1).min(STENCIL_MAX_DEPTH);
13771 }
13772 } else {
13773 active_scissor = None;
13774 }
13775 rpass.set_stencil_reference(STENCIL_BASE + clip_depth);
13776 }
13777
13778 Cmd::VectorClipPop {
13779 mesh,
13780 uoff,
13781 ioff,
13782 icnt,
13783 scissor,
13784 stencil_scissor,
13785 difference,
13786 applied,
13787 } => {
13788 let scissor =
13789 clamp_scissor(scissor.0, scissor.1, scissor.2, scissor.3, tw, th);
13790 let dec = clamp_scissor(
13791 stencil_scissor.0,
13792 stencil_scissor.1,
13793 stencil_scissor.2,
13794 stencil_scissor.3,
13795 tw,
13796 th,
13797 );
13798 if scissor.2 > 0 && scissor.3 > 0 {
13799 rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
13800 active_scissor = Some(scissor);
13801 } else {
13802 active_scissor = None;
13803 }
13804 if applied && dec.2 > 0 && dec.3 > 0 {
13805 rpass.set_scissor_rect(dec.0, dec.1, dec.2, dec.3);
13806 let pipe = if difference {
13807 &pipes.mesh_clip_inc
13808 } else {
13809 &pipes.mesh_clip_dec
13810 };
13811 draw_indexed_mesh!(pipe, uoff, mesh, ioff, icnt);
13812 if scissor.2 > 0 && scissor.3 > 0 {
13813 rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
13814 }
13815 if !difference {
13816 clip_depth = clip_depth.saturating_sub(1);
13817 }
13818 }
13819 rpass.set_stencil_reference(STENCIL_BASE + clip_depth);
13820 }
13821
13822 Cmd::Callback {
13823 rect,
13824 clip_rect,
13825 scissor,
13826 restore_scissor,
13827 callback_id,
13828 payload,
13829 } => {
13830 if let Some(cb) = payload.downcast_ref::<Callback>() {
13831 let vp_x = rect.x.ceil().max(0.0);
13837 let vp_y = rect.y.ceil().max(0.0);
13838 let vp_w = ((rect.x + rect.w).floor() - vp_x).max(1.0);
13839 let vp_h = ((rect.y + rect.h).floor() - vp_y).max(1.0);
13840 if vp_w > 0.0 && vp_h > 0.0 && clip_rect.w > 0.0 && clip_rect.h > 0.0 {
13841 rpass.set_scissor_rect(scissor.0, scissor.1, scissor.2, scissor.3);
13842 rpass.set_viewport(vp_x, vp_y, vp_w, vp_h, 0.0, 1.0);
13843 let info = repose_core::PaintCallbackInfo {
13844 viewport: rect,
13845 clip_rect,
13846 pixels_per_point: self.pixels_per_point,
13847 screen_size_px: [tw, th],
13848 };
13849 let descriptor = ScreenDescriptor {
13850 size_in_pixels: [tw, th],
13851 pixels_per_point: self.pixels_per_point,
13852 target_format: if is_layer {
13853 self.layer_target_format()
13854 } else if working_target {
13855 wgpu::TextureFormat::Rgba16Float
13856 } else {
13857 self.output_format
13858 },
13859 sample_count: if is_layer {
13860 1
13861 } else {
13862 self.active_surface_msaa_samples()
13863 },
13864 };
13865 let scope =
13866 callback_scope_key(cb, callback_id, pass.target, &descriptor);
13867 let resources = self
13868 .callback_scoped_resources
13869 .get(&scope)
13870 .unwrap_or(&self.callback_resources);
13871 let outcome = {
13878 let mut callback_pass = CallbackRenderPass::new(
13879 &mut rpass,
13880 descriptor.target_format,
13881 descriptor.sample_count,
13882 );
13883 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
13884 cb.0.paint(info, &mut callback_pass, resources)
13885 }))
13886 };
13887 if outcome.is_err() {
13888 log::warn!("paint callback panicked; state restored");
13889 }
13890 rpass.set_viewport(0.0, 0.0, tw as f32, th as f32, 0.0, 1.0);
13891 let restore = if restore_scissor.2 > 0 && restore_scissor.3 > 0 {
13892 restore_scissor
13893 } else {
13894 (0, 0, 1, 1)
13895 };
13896 rpass.set_scissor_rect(restore.0, restore.1, restore.2, restore.3);
13897 rpass.set_bind_group(0, &self.globals_bind, &[]);
13898 rpass.set_stencil_reference(STENCIL_BASE + clip_depth);
13899 }
13900 } else {
13901 log::warn!("Unknown paint callback payload");
13902 }
13903 }
13904 }
13905 }
13906 if is_layer {
13907 clip_depth = clip_depth_stack.pop().unwrap_or(0);
13908 }
13909 }
13910
13911 let transient_ids: HashSet<u32> = flatten_ids_used.iter().copied().collect();
13912 let producer_ids = std::mem::take(&mut self.producer_layer_ids);
13913 self.blur_scratch_ids
13917 .retain(|&(source, _), _| producer_ids.contains(&source));
13918 let live_scratch: HashSet<u32> = self.blur_scratch_ids.values().copied().collect();
13919 let stale_layers: Vec<u32> = self
13920 .layer_pool
13921 .keys()
13922 .filter_map(|id| {
13923 (!producer_ids.contains(id)
13924 && !transient_ids.contains(id)
13925 && !live_scratch.contains(id))
13926 .then_some(*id)
13927 })
13928 .collect();
13929 for id in stale_layers {
13930 if let Some(layer) = self.layer_pool.remove(&id) {
13931 self.layer_bytes_total = self.layer_bytes_total.saturating_sub(layer.bytes);
13932 if layer.transient {
13933 self.transient_layer_bytes_total =
13934 self.transient_layer_bytes_total.saturating_sub(layer.bytes);
13935 }
13936 }
13937 }
13938 self.flatten_layer_ids = flatten_ids_used;
13939
13940 if self.working_space
13942 && let (Some(_ws_view), Some(ws_bind), Some(display_pipeline)) =
13943 (&self.ws_view, &self.ws_bind, &self.display_pipeline)
13944 {
13945 let swap_view = target_view.clone();
13946 let mut display_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
13947 label: Some("display transform"),
13948 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
13949 view: &swap_view,
13950 resolve_target: None,
13951 ops: wgpu::Operations {
13952 load: wgpu::LoadOp::Load,
13953 store: wgpu::StoreOp::Store,
13954 },
13955 depth_slice: None,
13956 })],
13957 depth_stencil_attachment: None,
13958 timestamp_writes: None,
13959 occlusion_query_set: None,
13960 multiview_mask: None,
13961 });
13962 display_pass.set_pipeline(display_pipeline);
13963 display_pass.set_bind_group(1, ws_bind, &[]);
13964 display_pass.draw(0..3, 0..1);
13965 }
13966 self.recycle_blend_snapshots();
13967 }
13968
13969 pub fn render_to_view(
13973 &mut self,
13974 scene: &Scene,
13975 encoder: &mut wgpu::CommandEncoder,
13976 target_view: &wgpu::TextureView,
13977 width: u32,
13978 height: u32,
13979 clear_color: Option<[f64; 4]>,
13980 ) {
13981 self.resize(width, height);
13982
13983 if let Err(error) = self.begin_frame() {
13984 log::error!("render_to_view: {error:#}");
13985 return;
13986 }
13987
13988 if self.output_width == 0 || self.output_height == 0 {
13989 self.end_frame();
13990 return;
13991 }
13992
13993 self.render_scene_to_encoder(scene, encoder, target_view, clear_color);
13994 self.end_frame();
13995 }
13996}
13997
13998#[cfg(target_os = "linux")]
13999fn validate_dmabuf_plane(
14000 fd: &std::os::unix::io::OwnedFd,
14001 offset: u64,
14002 stride: u32,
14003 width: u32,
14004 height: u32,
14005 bytes_per_pixel: u32,
14006) -> anyhow::Result<u64> {
14007 if width == 0 || height == 0 || bytes_per_pixel == 0 {
14008 anyhow::bail!("DMA-BUF plane dimensions and bytes per pixel must be non-zero");
14009 }
14010 if !offset.is_multiple_of(4) || !stride.is_multiple_of(4) {
14011 anyhow::bail!("DMA-BUF offset and stride must be 4-byte aligned");
14012 }
14013 let row_bytes = (width as u64)
14014 .checked_mul(bytes_per_pixel as u64)
14015 .ok_or_else(|| anyhow::anyhow!("DMA-BUF row size overflow"))?;
14016 if (stride as u64) < row_bytes {
14017 anyhow::bail!(
14018 "DMA-BUF stride {} is smaller than row size {row_bytes}",
14019 stride
14020 );
14021 }
14022 let span = (height as u64 - 1)
14023 .checked_mul(stride as u64)
14024 .and_then(|value| value.checked_add(row_bytes))
14025 .ok_or_else(|| anyhow::anyhow!("DMA-BUF plane size overflow"))?;
14026 let file = std::fs::File::from(
14027 fd.try_clone()
14028 .map_err(|error| anyhow::anyhow!("duplicate DMA-BUF fd: {error}"))?,
14029 );
14030 let file_size = file
14031 .metadata()
14032 .map_err(|error| anyhow::anyhow!("stat DMA-BUF fd: {error}"))?
14033 .len();
14034 if offset > file_size || span > file_size - offset {
14035 anyhow::bail!("DMA-BUF plane offset/size {offset}+{span} exceeds file size {file_size}");
14036 }
14037 Ok(file_size)
14038}
14039
14040fn is_filterable_color_format(format: wgpu::TextureFormat) -> bool {
14041 matches!(
14042 format,
14043 wgpu::TextureFormat::Rgba8Unorm
14044 | wgpu::TextureFormat::Rgba8UnormSrgb
14045 | wgpu::TextureFormat::Bgra8Unorm
14046 | wgpu::TextureFormat::Bgra8UnormSrgb
14047 | wgpu::TextureFormat::Rgba16Unorm
14048 | wgpu::TextureFormat::Rgba16Float
14049 | wgpu::TextureFormat::Rgba32Float
14050 | wgpu::TextureFormat::Rgb10a2Unorm
14051 )
14052}
14053
14054fn native_format_supported(format: wgpu::TextureFormat, features: wgpu::Features) -> bool {
14055 if !is_filterable_color_format(format) {
14056 return false;
14057 }
14058 match format {
14059 wgpu::TextureFormat::Rgba16Unorm => {
14060 features.contains(wgpu::Features::TEXTURE_FORMAT_16BIT_NORM)
14061 }
14062 wgpu::TextureFormat::Rgba32Float => features.contains(wgpu::Features::FLOAT32_FILTERABLE),
14063 _ => true,
14064 }
14065}
14066
14067fn validate_sampler_descriptor(
14068 device: &wgpu::Device,
14069 sampler: &wgpu::SamplerDescriptor<'_>,
14070) -> anyhow::Result<()> {
14071 if sampler.compare.is_some()
14072 || !matches!(
14073 sampler.mag_filter,
14074 wgpu::FilterMode::Nearest | wgpu::FilterMode::Linear
14075 )
14076 || !matches!(
14077 sampler.min_filter,
14078 wgpu::FilterMode::Nearest | wgpu::FilterMode::Linear
14079 )
14080 || sampler.anisotropy_clamp == 0
14081 || !sampler.lod_min_clamp.is_finite()
14082 || !sampler.lod_max_clamp.is_finite()
14083 || sampler.lod_min_clamp < 0.0
14084 || sampler.lod_max_clamp < sampler.lod_min_clamp
14085 {
14086 anyhow::bail!("native sampler must be non-comparison linear filtering with finite LODs");
14087 }
14088 if (matches!(sampler.address_mode_u, wgpu::AddressMode::ClampToBorder)
14089 || matches!(sampler.address_mode_v, wgpu::AddressMode::ClampToBorder)
14090 || matches!(sampler.address_mode_w, wgpu::AddressMode::ClampToBorder))
14091 && !device
14092 .features()
14093 .contains(wgpu::Features::ADDRESS_MODE_CLAMP_TO_BORDER)
14094 {
14095 anyhow::bail!("native sampler uses unsupported clamp-to-border addressing");
14096 }
14097 Ok(())
14098}
14099
14100fn validate_texture_dimensions(
14101 device: &wgpu::Device,
14102 width: u32,
14103 height: u32,
14104) -> anyhow::Result<()> {
14105 if width == 0
14106 || height == 0
14107 || width > device.limits().max_texture_dimension_2d
14108 || height > device.limits().max_texture_dimension_2d
14109 {
14110 anyhow::bail!("texture dimensions are outside the device limit");
14111 }
14112 Ok(())
14113}
14114
14115fn validate_image_handle(handle: u64) -> anyhow::Result<()> {
14116 if handle == 0 {
14117 anyhow::bail!("image handle 0 is reserved");
14118 }
14119 Ok(())
14120}
14121
14122fn decode_limits(max_dimension: u32) -> image::Limits {
14127 let mut limits = image::Limits::default();
14128 limits.max_image_width = Some(max_dimension);
14129 limits.max_image_height = Some(max_dimension);
14130 limits.max_alloc = Some(MAX_IMAGE_DECODE_BYTES);
14131 limits
14132}
14133
14134fn decode_image_rgba8(data: &[u8], max_dimension: u32) -> anyhow::Result<(u32, u32, Vec<u8>)> {
14138 let format = image::guess_format(data)?;
14139 let (w, h) = {
14140 let mut probe = image::ImageReader::with_format(std::io::Cursor::new(data), format);
14141 probe.limits(decode_limits(max_dimension));
14142 probe.into_dimensions()?
14143 };
14144 validate_image_decode_budget(w, h, max_dimension)?;
14145 let mut reader = image::ImageReader::with_format(std::io::Cursor::new(data), format);
14146 reader.limits(decode_limits(max_dimension));
14147 let rgba = reader.decode()?.into_rgba8();
14148 Ok((w, h, rgba.into_raw()))
14149}
14150
14151fn validate_image_decode_budget(w: u32, h: u32, max_dimension: u32) -> anyhow::Result<()> {
14152 if w == 0 || h == 0 {
14153 anyhow::bail!("encoded image has zero dimensions");
14154 }
14155 if w > max_dimension || h > max_dimension {
14156 anyhow::bail!("encoded image {w}x{h} exceeds the device texture limit {max_dimension}");
14157 }
14158 let bytes = checked_image_bytes(w, h, 4)?;
14159 if bytes > MAX_IMAGE_DECODE_BYTES {
14160 anyhow::bail!(
14161 "encoded image {w}x{h} needs {bytes} bytes to decode, over the {MAX_IMAGE_DECODE_BYTES} byte limit"
14162 );
14163 }
14164 Ok(())
14165}
14166
14167fn checked_image_bytes(w: u32, h: u32, bytes_per_pixel: u32) -> anyhow::Result<u64> {
14168 if w == 0 || h == 0 || bytes_per_pixel == 0 {
14169 anyhow::bail!("image dimensions and bytes per pixel must be non-zero");
14170 }
14171 (w as u64)
14172 .checked_mul(h as u64)
14173 .and_then(|size| size.checked_mul(bytes_per_pixel as u64))
14174 .ok_or_else(|| anyhow::anyhow!("image byte size overflow"))
14175}
14176
14177fn texture_storage_bytes(
14178 format: wgpu::TextureFormat,
14179 width: u32,
14180 height: u32,
14181) -> anyhow::Result<u64> {
14182 if width == 0 || height == 0 {
14183 anyhow::bail!("texture dimensions must be non-zero");
14184 }
14185 let bytes = format.theoretical_memory_footprint(wgpu::Extent3d {
14186 width,
14187 height,
14188 depth_or_array_layers: 1,
14189 });
14190 if bytes == 0 {
14191 anyhow::bail!("texture format has no storage size");
14192 }
14193 Ok(bytes)
14194}
14195
14196fn texture_storage_bytes_with_samples(
14197 format: wgpu::TextureFormat,
14198 width: u32,
14199 height: u32,
14200 sample_count: u32,
14201) -> anyhow::Result<u64> {
14202 texture_storage_bytes(format, width, height)?
14203 .checked_mul(u64::from(sample_count.max(1)))
14204 .ok_or_else(|| anyhow::anyhow!("multisample texture size overflow"))
14205}
14206
14207fn checked_image_bytes_usize(w: u32, h: u32, bytes_per_pixel: u32) -> anyhow::Result<usize> {
14208 usize::try_from(checked_image_bytes(w, h, bytes_per_pixel)?)
14209 .map_err(|_| anyhow::anyhow!("image byte size exceeds addressable memory"))
14210}
14211
14212fn clamp_scissor(x: u32, y: u32, w: u32, h: u32, tw: u32, th: u32) -> (u32, u32, u32, u32) {
14213 if w == 0 || h == 0 || tw == 0 || th == 0 {
14214 return (0, 0, 0, 0);
14215 }
14216 let x = x.min(tw - 1);
14217 let y = y.min(th - 1);
14218 let w = w.min(tw - x);
14219 let h = h.min(th - y);
14220 (x, y, w, h)
14221}
14222
14223fn rect_to_scissor(r: repose_core::Rect, width: u32, height: u32) -> (u32, u32, u32, u32) {
14224 if width == 0
14225 || height == 0
14226 || !r.x.is_finite()
14227 || !r.y.is_finite()
14228 || !r.w.is_finite()
14229 || !r.h.is_finite()
14230 || r.w <= 0.0
14231 || r.h <= 0.0
14232 {
14233 return (0, 0, 0, 0);
14234 }
14235 let x0 = r.x.ceil().max(0.0).min(width as f32);
14238 let y0 = r.y.ceil().max(0.0).min(height as f32);
14239 let x1 = (r.x + r.w).floor().max(x0).min(width as f32);
14240 let y1 = (r.y + r.h).floor().max(y0).min(height as f32);
14241 if x1 <= x0 || y1 <= y0 {
14242 return (0, 0, 0, 0);
14243 }
14244 (x0 as u32, y0 as u32, (x1 - x0) as u32, (y1 - y0) as u32)
14245}
14246
14247fn rect_to_ndc(r: repose_core::Rect, width: f32, height: f32) -> [f32; 4] {
14248 if width <= 0.0 || height <= 0.0 || !r.x.is_finite() || !r.y.is_finite() {
14249 return [0.0, 0.0, 0.0, 0.0];
14250 }
14251 let x0 = r.x / width * 2.0 - 1.0;
14252 let y0 = 1.0 - r.y / height * 2.0;
14253 let x1 = (r.x + r.w) / width * 2.0 - 1.0;
14254 let y1 = 1.0 - (r.y + r.h) / height * 2.0;
14255 [x0.min(x1), y0.min(y1), (x1 - x0).abs(), (y1 - y0).abs()]
14256}
14257
14258fn parent_rect_to_layer_rect(
14259 rect: repose_core::Rect,
14260 parent_transform: &Transform,
14261 origin: (f32, f32),
14262) -> Option<repose_core::Rect> {
14263 let inverse = parent_transform.inverse_linear()?;
14264 let tx = parent_transform.translate_x;
14265 let ty = parent_transform.translate_y;
14266 let corners = [
14267 (rect.x, rect.y),
14268 (rect.x + rect.w, rect.y),
14269 (rect.x, rect.y + rect.h),
14270 (rect.x + rect.w, rect.y + rect.h),
14271 ];
14272 let mut min_x = f32::INFINITY;
14273 let mut min_y = f32::INFINITY;
14274 let mut max_x = f32::NEG_INFINITY;
14275 let mut max_y = f32::NEG_INFINITY;
14276 for (x, y) in corners {
14277 let local_x = x - tx;
14278 let local_y = y - ty;
14279 let transformed_x = inverse[0] * local_x + inverse[1] * local_y;
14280 let transformed_y = inverse[2] * local_x + inverse[3] * local_y;
14281 min_x = min_x.min(transformed_x);
14282 min_y = min_y.min(transformed_y);
14283 max_x = max_x.max(transformed_x);
14284 max_y = max_y.max(transformed_y);
14285 }
14286 let result = repose_core::Rect {
14287 x: min_x - origin.0,
14288 y: min_y - origin.1,
14289 w: (max_x - min_x).max(0.0),
14290 h: (max_y - min_y).max(0.0),
14291 };
14292 (result.x.is_finite() && result.y.is_finite() && result.w.is_finite() && result.h.is_finite())
14293 .then_some(result)
14294}
14295
14296fn parent_radii_to_layer_radii(radii: [f32; 4], parent_transform: &Transform) -> Option<[f32; 4]> {
14297 let m = parent_transform.linear();
14298 let sx = (m[0] * m[0] + m[2] * m[2]).sqrt();
14299 let sy = (m[1] * m[1] + m[3] * m[3]).sqrt();
14300 (sx.is_finite() && sy.is_finite() && sx > 1e-6 && sy > 1e-6)
14301 .then(|| [radii[0] / sx, radii[1] / sy, radii[2] / sx, radii[3] / sy])
14302}
14303
14304fn parent_affine_to_layer_affine(
14305 affine: [f32; 6],
14306 parent_transform: &Transform,
14307 origin: (f32, f32),
14308) -> Option<[f32; 6]> {
14309 let inverse = parent_transform.inverse_linear()?;
14310 let tx = affine[4] - parent_transform.translate_x;
14311 let ty = affine[5] - parent_transform.translate_y;
14312 Some([
14313 inverse[0] * affine[0] + inverse[1] * affine[2],
14314 inverse[0] * affine[1] + inverse[1] * affine[3],
14315 inverse[2] * affine[0] + inverse[3] * affine[2],
14316 inverse[2] * affine[1] + inverse[3] * affine[3],
14317 inverse[0] * tx + inverse[1] * ty - origin.0,
14318 inverse[2] * tx + inverse[3] * ty - origin.1,
14319 ])
14320}
14321
14322fn checked_copy_region(
14323 region: repose_core::Rect,
14324 target_width: u32,
14325 target_height: u32,
14326) -> Option<(u32, u32, u32, u32)> {
14327 if target_width == 0
14328 || target_height == 0
14329 || !region.x.is_finite()
14330 || !region.y.is_finite()
14331 || !region.w.is_finite()
14332 || !region.h.is_finite()
14333 || region.w <= 0.0
14334 || region.h <= 0.0
14335 {
14336 return None;
14337 }
14338 let x0 = region.x.floor().max(0.0).min(target_width as f32) as u32;
14339 let y0 = region.y.floor().max(0.0).min(target_height as f32) as u32;
14340 let x1 = (region.x + region.w)
14341 .ceil()
14342 .max(x0 as f32)
14343 .min(target_width as f32) as u32;
14344 let y1 = (region.y + region.h)
14345 .ceil()
14346 .max(y0 as f32)
14347 .min(target_height as f32) as u32;
14348 (x1 > x0 && y1 > y0).then_some((x0, y0, x1 - x0, y1 - y0))
14349}
14350
14351fn intersect(a: repose_core::Rect, b: repose_core::Rect) -> repose_core::Rect {
14352 let x0 = a.x.max(b.x);
14353 let y0 = a.y.max(b.y);
14354 let x1 = (a.x + a.w).min(b.x + b.w);
14355 let y1 = (a.y + a.h).min(b.y + b.h);
14356 repose_core::Rect {
14357 x: x0,
14358 y: y0,
14359 w: (x1 - x0).max(0.0),
14360 h: (y1 - y0).max(0.0),
14361 }
14362}
14363
14364#[cfg(test)]
14365mod tests {
14366 use super::*;
14367
14368 #[test]
14369 fn image_source_rect_uses_texel_edges() {
14370 let source = resolve_image_source(Some(ImageSourceRect::new(2, 1, 3, 2)), 10, 8)
14371 .expect("source should be valid");
14372 assert_eq!(source.uv_min, [0.2, 0.125]);
14373 assert_eq!(source.uv_max, [0.5, 0.375]);
14374 assert_eq!(source.width, 3.0);
14375 assert_eq!(source.height, 2.0);
14376 assert!(resolve_image_source(Some(ImageSourceRect::new(8, 0, 3, 1)), 10, 8).is_none());
14377 assert!(resolve_image_source(Some(ImageSourceRect::new(0, 0, 0, 1)), 10, 8).is_none());
14378 }
14379
14380 #[test]
14381 fn image_fit_stays_inside_selected_source() {
14382 let source = resolve_image_source(Some(ImageSourceRect::new(2, 1, 4, 2)), 10, 8)
14383 .expect("source should be valid");
14384 let rect = repose_core::Rect {
14385 x: 20.0,
14386 y: 30.0,
14387 w: 8.0,
14388 h: 8.0,
14389 };
14390 let (_, uv) = image_fit_geometry(rect, ImageFit::Cover, ImageAlignment::Center, &source)
14391 .expect("cover geometry should be valid");
14392 assert!(uv[0] >= source.uv_min[0] && uv[2] <= source.uv_max[0]);
14393 assert!(uv[1] >= source.uv_min[1] && uv[3] <= source.uv_max[1]);
14394 }
14395
14396 #[test]
14397 fn ring_alignment_rejects_bad_input() {
14398 assert_eq!(align_up(0, 4).unwrap(), 0);
14399 assert_eq!(align_up(1, 4).unwrap(), 4);
14400 assert!(align_up(1, 3).is_err());
14401 assert!(align_up(u64::MAX, 4).is_err());
14402 }
14403
14404 #[test]
14407 fn mesh_uniform_stride_is_always_a_power_of_two() {
14408 for base in [4u64, 16, 32, 64, 128, 256, 512] {
14409 for size in [
14410 std::mem::size_of::<MeshUniform>() as u64,
14411 96,
14412 272,
14413 288,
14414 1024,
14415 ] {
14416 let stride = mesh_uniform_stride(size, base);
14417 assert!(
14418 stride.is_power_of_two(),
14419 "stride {stride} for size {size} base {base} is not a power of two"
14420 );
14421 assert_eq!(stride % base, 0, "stride {stride} misaligned to {base}");
14422 assert!(stride >= size, "stride {stride} below size {size}");
14423 assert!(
14424 align_up(size, stride).is_ok(),
14425 "capacity alignment rejects stride {stride}"
14426 );
14427 }
14428 }
14429 }
14430
14431 fn wgsl_type_size(module: &naga::Module, ty: naga::Handle<naga::Type>) -> u32 {
14433 match &module.types[ty].inner {
14434 naga::TypeInner::Scalar(_) | naga::TypeInner::Atomic(_) => 4,
14435 naga::TypeInner::Vector { size, .. } => 4 * *size as u32,
14436 naga::TypeInner::Array {
14437 size: naga::ArraySize::Constant(count),
14438 stride,
14439 ..
14440 } => stride * count.get(),
14441 _ => 0,
14442 }
14443 }
14444
14445 #[test]
14450 fn mesh_uniform_matches_the_wgsl_member_layout() {
14451 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/shaders/mesh.wgsl");
14452 let module = naga::front::wgsl::parse_str(&std::fs::read_to_string(path).expect("read"))
14453 .expect("mesh.wgsl parses");
14454 let wgsl = module
14455 .types
14456 .iter()
14457 .filter(|(_, ty)| ty.name.as_deref() == Some("MeshUniform"))
14458 .find_map(|(_, ty)| match &ty.inner {
14459 naga::TypeInner::Struct { members, .. } => Some(members.as_slice()),
14460 _ => None,
14461 })
14462 .expect("mesh.wgsl declares MeshUniform");
14463 let rust = [
14464 ("paint", std::mem::offset_of!(MeshUniform, paint)),
14465 ("color0", std::mem::offset_of!(MeshUniform, color0)),
14466 ("color1", std::mem::offset_of!(MeshUniform, color1)),
14467 ("grad_start", std::mem::offset_of!(MeshUniform, grad_start)),
14468 ("grad_end", std::mem::offset_of!(MeshUniform, grad_end)),
14469 (
14470 "stop_colors",
14471 std::mem::offset_of!(MeshUniform, stop_colors),
14472 ),
14473 (
14474 "stop_offsets",
14475 std::mem::offset_of!(MeshUniform, stop_offsets),
14476 ),
14477 ];
14478 assert_eq!(wgsl.len(), rust.len(), "MeshUniform member count");
14479 for (member, (name, offset)) in wgsl.iter().zip(rust) {
14480 assert_eq!(member.name.as_deref(), Some(name), "member order");
14481 assert_eq!(member.offset as usize, offset, "offset of {name}");
14482 }
14483 let last = wgsl.last().expect("non-empty");
14484 let wgsl_size = last.offset as usize + wgsl_type_size(&module, last.ty) as usize;
14485 assert_eq!(wgsl_size, std::mem::size_of::<MeshUniform>());
14486 assert_eq!(wgsl_size, MESH_UNIFORM_BYTES);
14487 }
14488
14489 #[test]
14493 fn gradient_stops_pack_clamped_and_monotonic() {
14494 let stops = GradientStops::from_slice(&[
14495 repose_core::GradientStop {
14496 offset: 0.25,
14497 color: repose_core::Color::from_rgba(255, 0, 0, 255),
14498 },
14499 repose_core::GradientStop {
14500 offset: f32::NAN,
14501 color: repose_core::Color::from_rgba(0, 255, 0, 255),
14502 },
14503 repose_core::GradientStop {
14504 offset: -2.0,
14505 color: repose_core::Color::from_rgba(0, 0, 255, 255),
14506 },
14507 repose_core::GradientStop {
14508 offset: 9.0,
14509 color: repose_core::Color::from_rgba(255, 255, 255, 255),
14510 },
14511 ]);
14512 let (colors, offsets, count) = pack_gradient_stops(&stops);
14513 assert_eq!(count, 4);
14514 assert_eq!(offsets, [[0.25, 0.25, 0.25, 1.0], [0.0, 0.0, 0.0, 0.0]]);
14515 assert_eq!(colors[0], [1.0, 0.0, 0.0, 1.0]);
14516 assert_eq!(colors[1], [0.0, 1.0, 0.0, 1.0]);
14517 assert_eq!(colors[2], [0.0, 0.0, 1.0, 1.0]);
14518 assert_eq!(colors[3], [1.0, 1.0, 1.0, 1.0]);
14519 assert_eq!(
14520 pack_gradient_stops(&GradientStops::default()).2,
14521 0,
14522 "an empty table paints nothing"
14523 );
14524 }
14525
14526 #[test]
14531 fn atlas_eviction_spares_the_frame_in_flight() {
14532 fn key(glyph_id: u32) -> repose_text::CacheKey {
14533 repose_text::CacheKey {
14534 font_id: 1,
14535 glyph_id,
14536 font_size_bits: 16.0f32.to_bits(),
14537 variation: None,
14538 }
14539 }
14540 let mut map: HashMap<repose_text::CacheKey, GlyphInfo> = HashMap::new();
14541 for (glyph_id, last_touch, last_used_frame) in
14542 [(1u32, 10u64, 9u64), (2, 20, 7), (3, 30, 7), (4, 40, 7)]
14543 {
14544 map.insert(
14545 key(glyph_id),
14546 GlyphInfo {
14547 u0: 0.0,
14548 v0: 0.0,
14549 u1: 0.1,
14550 v1: 0.1,
14551 w: 10.0,
14552 h: 10.0,
14553 last_touch,
14554 last_used_frame,
14555 },
14556 );
14557 }
14558 let mut used_area = 400;
14559 assert!(evict_atlas_lru(&mut map, &mut used_area, 9, 250));
14560 assert_eq!(used_area, 200);
14561 assert!(map.contains_key(&key(1)), "in-flight glyph was evicted");
14562 assert!(!map.contains_key(&key(2)) && !map.contains_key(&key(3)));
14563 assert!(map.contains_key(&key(4)));
14564 }
14565
14566 #[test]
14567 fn atlas_eviction_refuses_to_empty_the_atlas() {
14568 let only = repose_text::CacheKey {
14569 font_id: 1,
14570 glyph_id: 1,
14571 font_size_bits: 16.0f32.to_bits(),
14572 variation: None,
14573 };
14574 let mut map: HashMap<repose_text::CacheKey, GlyphInfo> = HashMap::new();
14575 map.insert(
14576 only,
14577 GlyphInfo {
14578 u0: 0.0,
14579 v0: 0.0,
14580 u1: 0.1,
14581 v1: 0.1,
14582 w: 10.0,
14583 h: 10.0,
14584 last_touch: 1,
14585 last_used_frame: 1,
14586 },
14587 );
14588 let mut used_area = 100;
14589 assert!(!evict_atlas_lru(&mut map, &mut used_area, 2, 0));
14590 assert_eq!(map.len(), 1);
14591 assert_eq!(used_area, 100);
14592 }
14593
14594 #[test]
14595 fn empty_and_negative_rects_are_suppressed() {
14596 assert_eq!(
14597 rect_to_scissor(
14598 repose_core::Rect {
14599 x: 0.0,
14600 y: 0.0,
14601 w: 0.0,
14602 h: 4.0,
14603 },
14604 16,
14605 16,
14606 ),
14607 (0, 0, 0, 0)
14608 );
14609 assert_eq!(
14610 rect_to_scissor(
14611 repose_core::Rect {
14612 x: 0.0,
14613 y: 0.0,
14614 w: -1.0,
14615 h: 4.0,
14616 },
14617 16,
14618 16,
14619 ),
14620 (0, 0, 0, 0)
14621 );
14622 }
14623
14624 #[test]
14625 fn copy_region_is_checked() {
14626 assert_eq!(
14627 checked_copy_region(
14628 repose_core::Rect {
14629 x: 2.25,
14630 y: 3.5,
14631 w: 4.0,
14632 h: 5.0,
14633 },
14634 16,
14635 16,
14636 ),
14637 Some((2, 3, 5, 6))
14638 );
14639 assert_eq!(
14640 checked_copy_region(
14641 repose_core::Rect {
14642 x: 20.0,
14643 y: 0.0,
14644 w: 2.0,
14645 h: 2.0,
14646 },
14647 16,
14648 16,
14649 ),
14650 None
14651 );
14652 }
14653
14654 #[test]
14655 fn decode_budget_rejects_oversized_encoded_images() {
14656 assert!(validate_image_decode_budget(64, 64, 8192).is_ok());
14657 assert!(validate_image_decode_budget(0, 64, 8192).is_err());
14658 assert!(validate_image_decode_budget(64, 0, 8192).is_err());
14659 assert!(validate_image_decode_budget(8193, 1, 8192).is_err());
14660 assert!(validate_image_decode_budget(1, 8193, 8192).is_err());
14661 assert!(validate_image_decode_budget(8192, 4096, 8192).is_err());
14663 }
14664
14665 #[test]
14666 fn only_wgpu_supported_sample_counts_are_accepted() {
14667 for samples in [1, 2, 4, 8, 16] {
14668 assert!(validate_sample_count("msaa_samples", samples).is_ok());
14669 }
14670 for samples in [0, 3, 5, 7, 9, 17, 32, u32::MAX] {
14671 assert!(
14672 validate_sample_count("msaa_samples", samples).is_err(),
14673 "{samples} must be rejected"
14674 );
14675 }
14676 }
14677
14678 #[test]
14679 fn p010_uses_ten_bit_sample_range() {
14680 let raw = make_yuv_transform_raw(ColorInfo::default(), PixelFormat::P010);
14681 let expected = 65535.0 / (64.0 * 1020.0);
14682 assert!((raw.b[3] - expected).abs() < 1e-6);
14683 assert_eq!(canonical_fourcc(PixelFormat::P010), P010_FOURCC);
14684 assert_eq!(canonical_fourcc(PixelFormat::Nv12), NV12_FOURCC);
14685 assert_eq!(
14686 make_yuv_transform_raw(
14687 ColorInfo {
14688 transfer: repose_core::color::Transfer::Pq,
14689 ..ColorInfo::default()
14690 },
14691 PixelFormat::Nv12,
14692 )
14693 .transfer[0],
14694 3.0
14695 );
14696 assert_eq!(
14697 make_yuv_transform_raw(
14698 ColorInfo {
14699 transfer: repose_core::color::Transfer::Hlg,
14700 ..ColorInfo::default()
14701 },
14702 PixelFormat::Nv12,
14703 )
14704 .transfer[0],
14705 4.0
14706 );
14707 }
14708}