1use ::wgpu;
4use std::collections::HashMap;
5use std::string::String;
6use std::sync::Arc;
7use std::vec::Vec;
8
9use crate::display::{measure_char_advance, measure_char_kerning, Rgba8888};
10use crate::element::SpriteSource;
11use crate::motion::{DrawOp, DrawPayload};
12use crate::renderers::software::{
13 align_offset_x, compute_scaled_text_box, compute_unoccluded_clip, rasterize_sprite_source,
14 split_text_lines, with_spatial_occlusion,
15};
16use crate::solver::Region;
17use crate::style::Color;
18
19use super::atlas::{GlyphAtlas, SpriteAtlas, SpriteCacheKey, GLYPH_ATLAS_INIT_SIZE};
20use super::effects_pass::{
21 clamp_rect_u32, EffectUniform, GpuEffectsEngine, GpuPassStep, EFFECT_KIND_BACKDROP,
22 EFFECT_KIND_BLIT, EFFECT_KIND_COMPOSITE, EFFECT_KIND_EXTERNAL_TEX, EFFECT_KIND_SHADOW_EXTRACT,
23};
24use super::ramp::GradientRampAtlas;
25use super::{
26 color_to_f32, make_arc_primitive, make_quad_primitive, make_shadow_primitive,
27 make_styled_quad_primitive, pod_as_bytes, snap_bounds, snap_clip, GpuPrimitive,
28 ViewportUniform, IDENTITY_XFORM, KIND_GLYPH, KIND_SPRITE,
29};
30use crate::paint::{BlendMode, ExternalTextureId, LayerSpec, Paint, StyledQuad};
31use crate::renderers::software::{ops_have_layers_or_blend, snap_bounds_region_scaled, snap_clip_region_scaled};
32
33const SDF_WGSL: &str = include_str!("shader.wgsl");
34const INITIAL_INSTANCE_CAPACITY: usize = 512;
35const MAX_TEXT_LAYOUT_CACHE_ENTRIES: usize = 512;
36
37#[derive(Copy, Clone, PartialEq, Eq, Hash)]
38struct TextLayoutKey {
39 text_hash: u64,
40 text_len: u32,
41 logical_font_size: u8,
42 font_size_q4: u16,
43 max_width: i16,
44 text_flags: u8,
45 use_ttf: bool,
46}
47
48#[derive(Copy, Clone)]
49struct ShapedGlyphPos {
50 ch: char,
51 rel_x: i16,
52 rel_y: i16,
53}
54
55struct CachedTextLayout {
56 text: String,
57 total_h: i16,
58 glyphs: Vec<ShapedGlyphPos>,
59}
60
61#[inline]
62fn hash_layout_text(text: &str) -> u64 {
63 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
64 for &b in text.as_bytes() {
65 h ^= b as u64;
66 h = h.wrapping_mul(0x0100_0000_01b3);
67 }
68 h
69}
70
71#[inline]
72fn mix_u64(h: &mut u64, v: u64) {
73 *h ^= v;
74 *h = h.wrapping_mul(0x0100_0000_01b3);
75}
76
77#[inline]
78fn mix_region(h: &mut u64, r: Region) {
79 let packed = ((r.x as u16 as u64) << 48)
80 | ((r.y as u16 as u64) << 32)
81 | ((r.w as u16 as u64) << 16)
82 | (r.h as u16 as u64);
83 mix_u64(h, packed);
84}
85
86fn dirty_intersects_phys_rect(
88 dirty_regions: &[Region],
89 sx: u32,
90 sy: u32,
91 sw: u32,
92 sh: u32,
93 sf: f32,
94) -> bool {
95 let bx0 = sx as i64;
96 let by0 = sy as i64;
97 let bx1 = bx0 + sw as i64;
98 let by1 = by0 + sh as i64;
99 for &d in dirty_regions {
100 if d.is_empty() {
101 continue;
102 }
103 let dx0 = ((d.x as f32) * sf).floor() as i64 - 1;
104 let dy0 = ((d.y as f32) * sf).floor() as i64 - 1;
105 let dx1 = ((d.right() as f32) * sf).ceil() as i64 + 1;
106 let dy1 = ((d.bottom() as f32) * sf).ceil() as i64 + 1;
107 if dx0 < bx1 && dx1 > bx0 && dy0 < by1 && dy1 > by0 {
108 return true;
109 }
110 }
111 false
112}
113
114fn compute_backdrop_underlay_hash(
118 ops_before: &[DrawOp<'_>],
119 sample_logical: Region,
120 clear_color: wgpu::Color,
121) -> Option<u64> {
122 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
123 mix_u64(&mut h, clear_color.r.to_bits());
124 mix_u64(&mut h, clear_color.g.to_bits());
125 mix_u64(&mut h, clear_color.b.to_bits());
126 mix_u64(&mut h, clear_color.a.to_bits());
127
128 for op in ops_before {
129 let always_affect = matches!(
130 op.payload,
131 DrawPayload::PushLayer(_)
132 | DrawPayload::PopLayer
133 | DrawPayload::ExternalTexture(_)
134 | DrawPayload::StyledQuad(_)
135 );
136 if !always_affect && op.bounds.intersect(sample_logical).is_empty() {
137 continue;
138 }
139 if matches!(op.payload, DrawPayload::ExternalTexture(_))
140 && !op.bounds.intersect(sample_logical).is_empty()
141 {
142 return None;
143 }
144 if let DrawPayload::StyledQuad(sq) = op.payload {
145 if sq.transform.is_none() && op.bounds.intersect(sample_logical).is_empty() {
146 continue;
147 }
148 }
149 let snap = op.to_snapshot();
150 mix_region(&mut h, snap.effective_bounds);
151 mix_region(&mut h, op.clip);
152 mix_u64(&mut h, snap.payload_hash as u64);
153 match op.payload {
154 DrawPayload::SceneCanvas(sc) => {
155 mix_u64(&mut h, sc.content_hash() as u64);
156 }
157 DrawPayload::Vector(vs) => {
158 let mut vh = 0x5645_4354u32;
159 vs.mix_hash(&mut vh);
160 mix_u64(&mut h, vh as u64);
161 }
162 DrawPayload::DecodedImage(img) => {
163 mix_u64(&mut h, img.id.0 as u64);
164 mix_u64(&mut h, crate::image_pipeline::image_revision(img.id).unwrap_or(0));
165 }
166 _ => {}
167 }
168 }
169 Some(h)
170}
171
172#[repr(C)]
174#[derive(Copy, Clone, Debug)]
175struct AlignedViewportSlot {
176 uniform: ViewportUniform,
177 _pad: [u8; 256 - core::mem::size_of::<ViewportUniform>()],
178}
179
180impl Default for AlignedViewportSlot {
181 fn default() -> Self {
182 Self {
183 uniform: ViewportUniform::default(),
184 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
185 }
186 }
187}
188
189const _: () = assert!(core::mem::size_of::<AlignedViewportSlot>() == 256);
190const INIT_VIEWPORT_SLOTS: usize = 8;
191
192struct AtlasGrowNeed {
194 glyph_full: bool,
195 sprite_need: Option<(u32, u32)>,
196 ramp_full: bool,
197}
198
199pub(crate) struct ExternalTextureEntry {
201 pub(crate) view: wgpu::TextureView,
202 pub(crate) sampler: Option<wgpu::Sampler>,
203 pub(crate) generation: u64,
204}
205
206#[derive(Copy, Clone, Debug, Default, PartialEq)]
208pub struct WgpuMemoryStats {
209 pub glyph_atlas_size: u32,
210 pub glyph_atlas_bytes: usize,
211 pub glyph_atlas_entries: usize,
212 pub glyph_atlas_occupancy: f32,
213 pub sprite_atlas_size: u32,
214 pub sprite_atlas_bytes: usize,
215 pub sprite_atlas_entries: usize,
216 pub sprite_atlas_occupancy: f32,
217 pub ramp_atlas_bytes: usize,
218 pub instance_buf_bytes: usize,
219 pub uploaded_primitives_cpu_bytes: usize,
220 pub layer_pool_targets: usize,
221 pub layer_pool_target_bytes: usize,
222 pub layer_pool_masks: usize,
223 pub layer_pool_mask_bytes: usize,
224 pub canvas_scenes: usize,
225 pub canvas_gpu_bytes: usize,
226 pub slug_cached_glyphs: usize,
227 pub slug_gpu_bytes: usize,
228 pub slug_last_drawn_glyphs: usize,
229 pub text_layout_cache_entries: usize,
230 pub backdrop_blur_cache_hits: u64,
231 pub backdrop_blur_cache_misses: u64,
232}
233
234impl WgpuMemoryStats {
235 #[inline]
237 pub const fn total_gpu_bytes(&self) -> usize {
238 self.glyph_atlas_bytes
239 + self.sprite_atlas_bytes
240 + self.ramp_atlas_bytes
241 + self.instance_buf_bytes
242 + self.layer_pool_target_bytes
243 + self.layer_pool_mask_bytes
244 + self.canvas_gpu_bytes
245 + self.slug_gpu_bytes
246 }
247}
248
249pub const DEFAULT_SLUG_TEXT_THRESHOLD_PX: f32 = 28.0;
254
255pub struct WgpuRenderer {
257 pipeline: wgpu::RenderPipeline,
258 bind_group_layout: wgpu::BindGroupLayout,
259 bind_group: wgpu::BindGroup,
260 viewport_buf: wgpu::Buffer,
261 viewport_capacity: usize,
262 viewport_slots: Vec<AlignedViewportSlot>,
263 instance_buf: wgpu::Buffer,
264 instance_capacity: usize,
265 sampler: wgpu::Sampler,
266 linear_sampler: wgpu::Sampler,
267 glyph_atlas: GlyphAtlas,
268 sprite_atlas: SpriteAtlas,
269 ramp_atlas: GradientRampAtlas,
270 effects: Option<GpuEffectsEngine>,
271 canvas_engine: Option<super::canvas_pipeline::CanvasGpuEngine>,
272 ui_slug_engine: Option<super::slug_glyph::SlugTextEngine>,
274 slug_text_threshold_px: f32,
276 ui_slug_segments: Vec<(u32, u32, u32, u32)>,
278 pipeline_cache: Option<Arc<super::pso_cache::DiskPipelineCache>>,
279 bg_effects_rx: Option<std::sync::mpsc::Receiver<GpuEffectsEngine>>,
280 bg_canvas_rx: Option<std::sync::mpsc::Receiver<super::canvas_pipeline::CanvasGpuEngine>>,
281 external_textures: HashMap<ExternalTextureId, ExternalTextureEntry>,
282 next_external_id: u32,
283 next_external_gen: u64,
284 target_format: wgpu::TextureFormat,
285 primitives: Vec<GpuPrimitive>,
286 uploaded_primitives: Vec<GpuPrimitive>,
288 instance_buf_dirty_all: bool,
289 last_uploaded_instance_bytes: usize,
290 sprite_scratch: Vec<Rgba8888>,
291 #[cfg(not(target_endian = "little"))]
292 sprite_bytes_scratch: Vec<u8>,
293 text_layout_cache: HashMap<TextLayoutKey, Arc<CachedTextLayout>>,
294 text_layout_hits: u64,
295 target_is_srgb: bool,
296}
297
298impl WgpuRenderer {
299 pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
301 Self::new_with_cache(device, target_format, None)
302 }
303
304 pub(crate) fn new_with_cache(
306 device: &wgpu::Device,
307 target_format: wgpu::TextureFormat,
308 pipeline_cache: Option<Arc<super::pso_cache::DiskPipelineCache>>,
309 ) -> Self {
310 let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
311 let t0 = std::time::Instant::now();
312 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
313 label: Some("velox_wgpu_2d_shader"),
314 source: wgpu::ShaderSource::Wgsl(SDF_WGSL.into()),
315 });
316 let t_shader = t0.elapsed();
317
318 let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
319 label: Some("velox_wgpu_bgl"),
320 entries: &[
321 wgpu::BindGroupLayoutEntry {
322 binding: 0,
323 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
324 ty: wgpu::BindingType::Buffer {
325 ty: wgpu::BufferBindingType::Uniform,
326 has_dynamic_offset: true,
327 min_binding_size: wgpu::BufferSize::new(
328 core::mem::size_of::<ViewportUniform>() as u64,
329 ),
330 },
331 count: None,
332 },
333 wgpu::BindGroupLayoutEntry {
334 binding: 1,
335 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
336 ty: wgpu::BindingType::Buffer {
337 ty: wgpu::BufferBindingType::Storage { read_only: true },
338 has_dynamic_offset: false,
339 min_binding_size: None,
340 },
341 count: None,
342 },
343 wgpu::BindGroupLayoutEntry {
344 binding: 2,
345 visibility: wgpu::ShaderStages::FRAGMENT,
346 ty: wgpu::BindingType::Texture {
347 sample_type: wgpu::TextureSampleType::Float { filterable: true },
348 view_dimension: wgpu::TextureViewDimension::D2,
349 multisampled: false,
350 },
351 count: None,
352 },
353 wgpu::BindGroupLayoutEntry {
354 binding: 3,
355 visibility: wgpu::ShaderStages::FRAGMENT,
356 ty: wgpu::BindingType::Texture {
357 sample_type: wgpu::TextureSampleType::Float { filterable: true },
358 view_dimension: wgpu::TextureViewDimension::D2,
359 multisampled: false,
360 },
361 count: None,
362 },
363 wgpu::BindGroupLayoutEntry {
364 binding: 4,
365 visibility: wgpu::ShaderStages::FRAGMENT,
366 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
367 count: None,
368 },
369 wgpu::BindGroupLayoutEntry {
370 binding: 5,
371 visibility: wgpu::ShaderStages::FRAGMENT,
372 ty: wgpu::BindingType::Texture {
373 sample_type: wgpu::TextureSampleType::Float { filterable: true },
374 view_dimension: wgpu::TextureViewDimension::D2,
375 multisampled: false,
376 },
377 count: None,
378 },
379 wgpu::BindGroupLayoutEntry {
380 binding: 6,
381 visibility: wgpu::ShaderStages::FRAGMENT,
382 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
383 count: None,
384 },
385 ],
386 });
387
388 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
389 label: Some("velox_wgpu_pipeline_layout"),
390 bind_group_layouts: &[Some(&bind_group_layout)],
391 immediate_size: 0,
392 });
393
394 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
395 label: Some("velox_wgpu_2d_pipeline"),
396 layout: Some(&pipeline_layout),
397 vertex: wgpu::VertexState {
398 module: &shader,
399 entry_point: Some("vs_main"),
400 compilation_options: wgpu::PipelineCompilationOptions::default(),
401 buffers: &[],
402 },
403 primitive: wgpu::PrimitiveState {
404 topology: wgpu::PrimitiveTopology::TriangleList,
405 strip_index_format: None,
406 front_face: wgpu::FrontFace::Ccw,
407 cull_mode: None,
408 unclipped_depth: false,
409 polygon_mode: wgpu::PolygonMode::Fill,
410 conservative: false,
411 },
412 depth_stencil: None,
413 multisample: wgpu::MultisampleState::default(),
414 fragment: Some(wgpu::FragmentState {
415 module: &shader,
416 entry_point: Some("fs_main"),
417 compilation_options: wgpu::PipelineCompilationOptions::default(),
418 targets: &[Some(wgpu::ColorTargetState {
419 format: target_format,
420 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
421 write_mask: wgpu::ColorWrites::ALL,
422 })],
423 }),
424 multiview_mask: None,
425 cache: pipeline_cache.as_deref().map(|c| c.wgpu_cache()),
426 });
427 let t_pso = t0.elapsed();
428 if let Some(c) = &pipeline_cache {
429 c.persist();
430 }
431 if trace {
432 std::println!(
433 "[VELOX_STARTUP_TRACE] pipeline detail: create_shader_module={:.1}ms, create_render_pipeline=+{:.1}ms, pso_cache_hit={}",
434 t_shader.as_secs_f64() * 1000.0,
435 (t_pso - t_shader).as_secs_f64() * 1000.0,
436 pipeline_cache.as_ref().is_some_and(|c| c.loaded_from_disk()),
437 );
438 }
439
440 let viewport_buf = Self::create_viewport_buffer(device, INIT_VIEWPORT_SLOTS);
441 let instance_buf = Self::create_instance_buffer(device, INITIAL_INSTANCE_CAPACITY);
442 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
443 label: Some("velox_atlas_sampler"),
444 address_mode_u: wgpu::AddressMode::ClampToEdge,
445 address_mode_v: wgpu::AddressMode::ClampToEdge,
446 address_mode_w: wgpu::AddressMode::ClampToEdge,
447 mag_filter: wgpu::FilterMode::Nearest,
448 min_filter: wgpu::FilterMode::Nearest,
449 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
450 ..Default::default()
451 });
452 let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
453 label: Some("velox_linear_sampler"),
454 address_mode_u: wgpu::AddressMode::ClampToEdge,
455 address_mode_v: wgpu::AddressMode::ClampToEdge,
456 address_mode_w: wgpu::AddressMode::ClampToEdge,
457 mag_filter: wgpu::FilterMode::Linear,
458 min_filter: wgpu::FilterMode::Linear,
459 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
460 ..Default::default()
461 });
462
463 let glyph_atlas = GlyphAtlas::new(device, GLYPH_ATLAS_INIT_SIZE);
464 let sprite_atlas = SpriteAtlas::new(device, 1);
465 let ramp_atlas = GradientRampAtlas::new(device);
466 let bind_group = Self::create_bind_group(
467 device,
468 &bind_group_layout,
469 &viewport_buf,
470 &instance_buf,
471 &glyph_atlas.view,
472 &sprite_atlas.view,
473 &sampler,
474 &ramp_atlas.view,
475 &linear_sampler,
476 );
477
478 Self {
479 pipeline,
480 bind_group_layout,
481 bind_group,
482 viewport_buf,
483 viewport_capacity: INIT_VIEWPORT_SLOTS,
484 viewport_slots: Vec::with_capacity(INIT_VIEWPORT_SLOTS),
485 instance_buf,
486 instance_capacity: INITIAL_INSTANCE_CAPACITY,
487 sampler,
488 linear_sampler,
489 glyph_atlas,
490 sprite_atlas,
491 ramp_atlas,
492 effects: None,
493 canvas_engine: None,
494 ui_slug_engine: None,
495 slug_text_threshold_px: DEFAULT_SLUG_TEXT_THRESHOLD_PX,
496 ui_slug_segments: Vec::new(),
497 pipeline_cache,
498 bg_effects_rx: None,
499 bg_canvas_rx: None,
500 external_textures: HashMap::new(),
501 next_external_id: 1,
502 next_external_gen: 1,
503 target_format,
504 primitives: Vec::with_capacity(INITIAL_INSTANCE_CAPACITY),
505 uploaded_primitives: Vec::with_capacity(INITIAL_INSTANCE_CAPACITY),
506 instance_buf_dirty_all: true,
507 last_uploaded_instance_bytes: 0,
508 sprite_scratch: Vec::new(),
509 #[cfg(not(target_endian = "little"))]
510 sprite_bytes_scratch: Vec::new(),
511 text_layout_cache: HashMap::with_capacity(64),
512 text_layout_hits: 0,
513 target_is_srgb: target_format.is_srgb(),
514 }
515 }
516
517 fn create_viewport_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
518 device.create_buffer(&wgpu::BufferDescriptor {
519 label: Some("velox_wgpu_viewport"),
520 size: (capacity.max(1) * core::mem::size_of::<AlignedViewportSlot>()) as u64,
521 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
522 mapped_at_creation: false,
523 })
524 }
525
526 fn create_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
527 device.create_buffer(&wgpu::BufferDescriptor {
528 label: Some("velox_wgpu_instances"),
529 size: (capacity.max(1) * core::mem::size_of::<GpuPrimitive>()) as u64,
530 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
531 mapped_at_creation: false,
532 })
533 }
534
535 #[allow(clippy::too_many_arguments)]
536 fn create_bind_group(
537 device: &wgpu::Device,
538 layout: &wgpu::BindGroupLayout,
539 viewport_buf: &wgpu::Buffer,
540 instance_buf: &wgpu::Buffer,
541 glyph_view: &wgpu::TextureView,
542 sprite_view: &wgpu::TextureView,
543 sampler: &wgpu::Sampler,
544 ramp_view: &wgpu::TextureView,
545 linear_sampler: &wgpu::Sampler,
546 ) -> wgpu::BindGroup {
547 device.create_bind_group(&wgpu::BindGroupDescriptor {
548 label: Some("velox_wgpu_bg"),
549 layout,
550 entries: &[
551 wgpu::BindGroupEntry {
552 binding: 0,
553 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
554 buffer: viewport_buf,
555 offset: 0,
556 size: wgpu::BufferSize::new(core::mem::size_of::<ViewportUniform>() as u64),
557 }),
558 },
559 wgpu::BindGroupEntry {
560 binding: 1,
561 resource: instance_buf.as_entire_binding(),
562 },
563 wgpu::BindGroupEntry {
564 binding: 2,
565 resource: wgpu::BindingResource::TextureView(glyph_view),
566 },
567 wgpu::BindGroupEntry {
568 binding: 3,
569 resource: wgpu::BindingResource::TextureView(sprite_view),
570 },
571 wgpu::BindGroupEntry {
572 binding: 4,
573 resource: wgpu::BindingResource::Sampler(sampler),
574 },
575 wgpu::BindGroupEntry {
576 binding: 5,
577 resource: wgpu::BindingResource::TextureView(ramp_view),
578 },
579 wgpu::BindGroupEntry {
580 binding: 6,
581 resource: wgpu::BindingResource::Sampler(linear_sampler),
582 },
583 ],
584 })
585 }
586
587 #[inline]
589 pub fn last_primitive_count(&self) -> usize {
590 self.uploaded_primitives.len()
591 }
592
593 #[inline]
595 pub const fn atlas_sizes(&self) -> (u32, u32) {
596 (self.glyph_atlas.width, self.sprite_atlas.width)
597 }
598
599 #[inline]
601 pub const fn sprite_cache_hits(&self) -> u64 {
602 self.sprite_atlas.cache_hits
603 }
604
605 #[inline]
607 pub const fn text_layout_cache_hits(&self) -> u64 {
608 self.text_layout_hits
609 }
610
611 #[inline]
613 pub fn text_layout_cache_len(&self) -> usize {
614 self.text_layout_cache.len()
615 }
616
617 pub fn register_external_texture(
620 &mut self,
621 view: wgpu::TextureView,
622 sampler: Option<wgpu::Sampler>,
623 ) -> ExternalTextureId {
624 let mut id = self.next_external_id;
625 while id == 0 || self.external_textures.contains_key(&ExternalTextureId(id)) {
626 id = id.wrapping_add(1);
627 }
628 self.next_external_id = id.wrapping_add(1).max(1);
629 let generation = self.next_external_gen;
630 self.next_external_gen = self.next_external_gen.wrapping_add(1).max(1);
631 let tex_id = ExternalTextureId(id);
632 self.external_textures.insert(
633 tex_id,
634 ExternalTextureEntry {
635 view,
636 sampler,
637 generation,
638 },
639 );
640 tex_id
641 }
642
643 pub fn register_external_texture_with_id(
645 &mut self,
646 id: ExternalTextureId,
647 view: wgpu::TextureView,
648 sampler: Option<wgpu::Sampler>,
649 ) {
650 let generation = self.next_external_gen;
651 self.next_external_gen = self.next_external_gen.wrapping_add(1).max(1);
652 self.external_textures.insert(
653 id,
654 ExternalTextureEntry {
655 view,
656 sampler,
657 generation,
658 },
659 );
660 }
661
662 pub fn update_external_texture(&mut self, id: ExternalTextureId, view: wgpu::TextureView) -> bool {
664 if let Some(entry) = self.external_textures.get_mut(&id) {
665 entry.view = view;
666 let generation = self.next_external_gen;
667 self.next_external_gen = self.next_external_gen.wrapping_add(1).max(1);
668 entry.generation = generation;
669 true
670 } else {
671 false
672 }
673 }
674
675 pub fn unregister_external_texture(&mut self, id: ExternalTextureId) -> bool {
677 self.external_textures.remove(&id).is_some()
678 }
679
680 #[inline]
682 pub fn external_texture_count(&self) -> usize {
683 self.external_textures.len()
684 }
685
686 #[inline]
688 pub fn layer_pool_bytes(&self) -> usize {
689 self.effects.as_ref().map(|fx| fx.pool.target_bytes()).unwrap_or(0)
690 }
691
692 #[inline]
694 pub fn layer_pool_target_count(&self) -> usize {
695 self.effects.as_ref().map(|fx| fx.pool.target_count()).unwrap_or(0)
696 }
697
698 #[inline]
700 pub fn layer_mask_cache_bytes(&self) -> usize {
701 self.effects.as_ref().map(|fx| fx.pool.mask_bytes()).unwrap_or(0)
702 }
703
704 #[inline]
706 pub fn layer_mask_cache_count(&self) -> usize {
707 self.effects.as_ref().map(|fx| fx.pool.mask_count()).unwrap_or(0)
708 }
709
710 #[inline]
712 pub fn pso_cache_loaded_from_disk(&self) -> bool {
713 self.pipeline_cache
714 .as_ref()
715 .is_some_and(|c| c.loaded_from_disk())
716 }
717
718 pub fn spawn_background_pipeline_warmup(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
721 let need_effects = self.effects.is_none() && self.bg_effects_rx.is_none();
722 let need_canvas = self.canvas_engine.is_none() && self.bg_canvas_rx.is_none();
723 if !need_effects && !need_canvas {
724 return;
725 }
726 struct WarmupPayload {
727 device: wgpu::Device,
728 queue: wgpu::Queue,
729 fmt: wgpu::TextureFormat,
730 cache: Option<Arc<super::pso_cache::DiskPipelineCache>>,
731 fx_tx: Option<std::sync::mpsc::Sender<GpuEffectsEngine>>,
732 cv_tx: Option<std::sync::mpsc::Sender<super::canvas_pipeline::CanvasGpuEngine>>,
733 }
734 unsafe impl Send for WarmupPayload {}
736
737 let payload = WarmupPayload {
738 device: device.clone(),
739 queue: queue.clone(),
740 fmt: self.target_format,
741 cache: self.pipeline_cache.clone(),
742 fx_tx: if need_effects {
743 let (tx, rx) = std::sync::mpsc::channel();
744 self.bg_effects_rx = Some(rx);
745 Some(tx)
746 } else {
747 None
748 },
749 cv_tx: if need_canvas {
750 let (tx, rx) = std::sync::mpsc::channel();
751 self.bg_canvas_rx = Some(rx);
752 Some(tx)
753 } else {
754 None
755 },
756 };
757
758 let _ = std::thread::Builder::new()
759 .name(String::from("velox-pso-warmup"))
760 .stack_size(512 * 1024)
761 .spawn(move || {
762 let payload = payload;
763 let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
764 let t0 = std::time::Instant::now();
765 let raw_cache = payload.cache.as_deref().map(|c| c.wgpu_cache());
766 if let Some(tx) = payload.fx_tx {
767 let fx = GpuEffectsEngine::new(&payload.device, &payload.queue, payload.fmt, raw_cache);
768 if let Some(c) = &payload.cache {
769 c.persist();
770 }
771 let _ = tx.send(fx);
772 }
773 let t_fx = t0.elapsed();
774 if let Some(tx) = payload.cv_tx {
775 let cv = super::canvas_pipeline::CanvasGpuEngine::new(
776 &payload.device,
777 payload.fmt,
778 raw_cache,
779 );
780 if let Some(c) = &payload.cache {
781 c.persist();
782 }
783 let _ = tx.send(cv);
784 }
785 if trace {
786 let t_all = t0.elapsed();
787 std::println!(
788 "[VELOX_STARTUP_TRACE] async bg sub-pipeline warmup: effects={:.1}ms, canvas=+{:.1}ms, total={:.1}ms",
789 t_fx.as_secs_f64() * 1000.0,
790 (t_all - t_fx).as_secs_f64() * 1000.0,
791 t_all.as_secs_f64() * 1000.0,
792 );
793 }
794 });
795 }
796
797 pub(crate) fn poll_warmed_subengines(&mut self) {
799 if self.effects.is_none() {
800 if let Some(rx) = &self.bg_effects_rx {
801 match rx.try_recv() {
802 Ok(fx) => {
803 self.effects = Some(fx);
804 self.bg_effects_rx = None;
805 }
806 Err(std::sync::mpsc::TryRecvError::Disconnected) => {
807 self.bg_effects_rx = None;
808 }
809 Err(std::sync::mpsc::TryRecvError::Empty) => {}
810 }
811 }
812 }
813 if self.canvas_engine.is_none() {
814 if let Some(rx) = &self.bg_canvas_rx {
815 match rx.try_recv() {
816 Ok(cv) => {
817 self.canvas_engine = Some(cv);
818 self.bg_canvas_rx = None;
819 }
820 Err(std::sync::mpsc::TryRecvError::Disconnected) => {
821 self.bg_canvas_rx = None;
822 }
823 Err(std::sync::mpsc::TryRecvError::Empty) => {}
824 }
825 }
826 }
827 }
828
829 pub fn wait_background_pipeline_warmup(&mut self) {
831 if let Some(rx) = self.bg_effects_rx.take() {
832 if let Ok(fx) = rx.recv() {
833 if self.effects.is_none() {
834 self.effects = Some(fx);
835 }
836 }
837 }
838 if let Some(rx) = self.bg_canvas_rx.take() {
839 if let Ok(cv) = rx.recv() {
840 if self.canvas_engine.is_none() {
841 self.canvas_engine = Some(cv);
842 }
843 }
844 }
845 }
846
847 #[inline]
849 pub fn backdrop_blur_cache_stats(&self) -> (u64, u64) {
850 self.effects
851 .as_ref()
852 .map(|fx| fx.pool.backdrop_cache_stats())
853 .unwrap_or((0, 0))
854 }
855
856 #[inline]
862 pub fn set_slug_text_threshold_px(&mut self, threshold_px: f32) {
863 self.slug_text_threshold_px = threshold_px.max(0.0);
864 }
865
866 #[inline]
868 pub const fn slug_text_threshold_px(&self) -> f32 {
869 self.slug_text_threshold_px
870 }
871
872 pub fn memory_stats(&self) -> WgpuMemoryStats {
874 let (canvas_scenes, canvas_gpu_bytes) = self
875 .canvas_engine
876 .as_ref()
877 .map(|c| (c.scene_count(), c.total_gpu_bytes()))
878 .unwrap_or((0, 0));
879 let (slug_cached_glyphs, slug_gpu_bytes, slug_last_drawn_glyphs) = self
880 .ui_slug_engine
881 .as_ref()
882 .map(|s| (s.cached_glyph_count(), s.gpu_bytes(), s.last_drawn_glyphs()))
883 .unwrap_or((0, 0, 0));
884 let (backdrop_blur_cache_hits, backdrop_blur_cache_misses) = self.backdrop_blur_cache_stats();
885 WgpuMemoryStats {
886 glyph_atlas_size: self.glyph_atlas.width,
887 glyph_atlas_bytes: self.glyph_atlas.gpu_bytes(),
888 glyph_atlas_entries: self.glyph_atlas.entry_count(),
889 glyph_atlas_occupancy: self.glyph_atlas.occupancy_ratio(),
890 sprite_atlas_size: self.sprite_atlas.width,
891 sprite_atlas_bytes: self.sprite_atlas.gpu_bytes(),
892 sprite_atlas_entries: self.sprite_atlas.entry_count(),
893 sprite_atlas_occupancy: self.sprite_atlas.occupancy_ratio(),
894 ramp_atlas_bytes: (super::ramp::RAMP_WIDTH as usize)
895 .saturating_mul(self.ramp_atlas.rows as usize)
896 .saturating_mul(4),
897 instance_buf_bytes: self
898 .instance_capacity
899 .saturating_mul(core::mem::size_of::<GpuPrimitive>()),
900 uploaded_primitives_cpu_bytes: self
901 .uploaded_primitives
902 .capacity()
903 .saturating_add(self.primitives.capacity())
904 .saturating_mul(core::mem::size_of::<GpuPrimitive>()),
905 layer_pool_targets: self.layer_pool_target_count(),
906 layer_pool_target_bytes: self.layer_pool_bytes(),
907 layer_pool_masks: self.layer_mask_cache_count(),
908 layer_pool_mask_bytes: self.layer_mask_cache_bytes(),
909 canvas_scenes,
910 canvas_gpu_bytes,
911 slug_cached_glyphs,
912 slug_gpu_bytes,
913 slug_last_drawn_glyphs,
914 text_layout_cache_entries: self.text_layout_cache.len(),
915 backdrop_blur_cache_hits,
916 backdrop_blur_cache_misses,
917 }
918 }
919
920 pub fn set_layer_pool_idle_budget(&mut self, bytes: usize) {
922 if let Some(fx) = &mut self.effects {
923 if fx.pool.set_idle_target_budget_bytes(bytes) {
924 fx.prune_stale_bind_groups();
925 }
926 }
927 }
928
929 pub fn set_layer_pool_idle_max_age_frames(&mut self, frames: u64) {
931 if let Some(fx) = &mut self.effects {
932 if fx.pool.set_idle_target_max_age_frames(frames) {
933 fx.prune_stale_bind_groups();
934 }
935 }
936 }
937
938 pub fn set_layer_mask_cache_budget(&mut self, bytes: usize) {
940 if let Some(fx) = &mut self.effects {
941 if fx.pool.set_mask_budget_bytes(bytes) {
942 fx.prune_stale_bind_groups();
943 }
944 }
945 }
946
947 pub fn on_viewport_resized(&mut self, phys_width: u32, phys_height: u32) {
949 if let Some(fx) = &mut self.effects {
950 fx.on_viewport_resized(phys_width, phys_height);
951 }
952 }
953
954 pub fn trim_gpu_memory(&mut self) {
956 if let Some(fx) = &mut self.effects {
957 fx.trim_idle_all();
958 }
959 if let Some(canvas) = &mut self.canvas_engine {
960 canvas.trim_idle_scenes();
961 }
962 }
963
964 #[inline]
966 pub fn last_uploaded_instance_bytes(&self) -> usize {
967 self.last_uploaded_instance_bytes
968 }
969
970 #[inline]
972 pub fn remove_canvas_scene(&mut self, scene_id: crate::canvas_scene::StaticSceneId) -> bool {
973 self.canvas_engine
974 .as_mut()
975 .is_some_and(|c| c.remove_scene(scene_id))
976 }
977
978 #[inline]
980 pub fn canvas_cache_bytes(&self) -> usize {
981 self.canvas_engine
982 .as_ref()
983 .map(|c| c.total_gpu_bytes())
984 .unwrap_or(0)
985 }
986
987 #[inline]
989 pub fn canvas_scene_count(&self) -> usize {
990 self.canvas_engine
991 .as_ref()
992 .map(|c| c.scene_count())
993 .unwrap_or(0)
994 }
995
996 #[inline]
998 pub fn canvas_last_state_upload_bytes(&self) -> usize {
999 self.canvas_engine
1000 .as_ref()
1001 .map(|c| c.last_state_upload_bytes())
1002 .unwrap_or(0)
1003 }
1004
1005 #[inline]
1007 pub fn set_canvas_idle_budget(&mut self, bytes: usize) {
1008 if let Some(c) = &mut self.canvas_engine {
1009 c.set_idle_budget_bytes(bytes);
1010 }
1011 }
1012
1013 #[inline]
1015 pub fn set_canvas_idle_max_age_frames(&mut self, frames: u64) {
1016 if let Some(c) = &mut self.canvas_engine {
1017 c.set_idle_max_age_frames(frames);
1018 }
1019 }
1020
1021 fn sync_instance_buffer(&mut self, queue: &wgpu::Queue) {
1025 const INSTANCE_STRIDE: usize = core::mem::size_of::<GpuPrimitive>();
1026 const INSTANCE_MERGE_GAP: usize = 16;
1027
1028 let new_len = self.primitives.len();
1029 if new_len == 0 {
1030 self.uploaded_primitives.clear();
1031 self.last_uploaded_instance_bytes = 0;
1032 return;
1033 }
1034
1035 if self.instance_buf_dirty_all || self.uploaded_primitives.is_empty() {
1036 let bytes = pod_as_bytes(&self.primitives);
1037 queue.write_buffer(&self.instance_buf, 0, bytes);
1038 self.last_uploaded_instance_bytes = bytes.len();
1039 core::mem::swap(&mut self.uploaded_primitives, &mut self.primitives);
1040 self.instance_buf_dirty_all = false;
1041 return;
1042 }
1043
1044 let old_len = self.uploaded_primitives.len();
1045 let common = old_len.min(new_len);
1046 let new_bytes = pod_as_bytes(&self.primitives);
1047 let old_bytes = pod_as_bytes(&self.uploaded_primitives);
1048
1049 let mut uploaded_bytes = 0usize;
1050 let mut run_start: Option<usize> = None;
1051 let mut run_end: usize = 0;
1052
1053 for i in 0..new_len {
1054 let changed = if i < common {
1055 let off = i * INSTANCE_STRIDE;
1056 new_bytes[off..off + INSTANCE_STRIDE] != old_bytes[off..off + INSTANCE_STRIDE]
1057 } else {
1058 true
1059 };
1060 if changed {
1061 match run_start {
1062 None => {
1063 run_start = Some(i);
1064 run_end = i + 1;
1065 }
1066 Some(rs) => {
1067 if i.saturating_sub(run_end) <= INSTANCE_MERGE_GAP {
1068 run_end = i + 1;
1069 } else {
1070 let b_start = rs * INSTANCE_STRIDE;
1071 let b_end = run_end * INSTANCE_STRIDE;
1072 queue.write_buffer(
1073 &self.instance_buf,
1074 b_start as u64,
1075 &new_bytes[b_start..b_end],
1076 );
1077 uploaded_bytes += b_end - b_start;
1078 run_start = Some(i);
1079 run_end = i + 1;
1080 }
1081 }
1082 }
1083 }
1084 }
1085 if let Some(rs) = run_start {
1086 let b_start = rs * INSTANCE_STRIDE;
1087 let b_end = run_end * INSTANCE_STRIDE;
1088 queue.write_buffer(
1089 &self.instance_buf,
1090 b_start as u64,
1091 &new_bytes[b_start..b_end],
1092 );
1093 uploaded_bytes += b_end - b_start;
1094 }
1095
1096 if uploaded_bytes > 0 || old_len != new_len {
1097 core::mem::swap(&mut self.uploaded_primitives, &mut self.primitives);
1098 }
1099 self.last_uploaded_instance_bytes = uploaded_bytes;
1100 }
1101
1102 fn rebuild_bind_group(&mut self, device: &wgpu::Device) {
1103 self.bind_group = Self::create_bind_group(
1104 device,
1105 &self.bind_group_layout,
1106 &self.viewport_buf,
1107 &self.instance_buf,
1108 &self.glyph_atlas.view,
1109 &self.sprite_atlas.view,
1110 &self.sampler,
1111 &self.ramp_atlas.view,
1112 &self.linear_sampler,
1113 );
1114 }
1115
1116 #[inline]
1117 fn sprite_cache_hash(sprite: SpriteSource<'_>, rel_x: i16, rel_y: i16, sb_w: i16, sb_h: i16) -> u64 {
1118 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
1119 let mix = |h: &mut u64, v: u64| {
1120 *h ^= v;
1121 *h = h.wrapping_mul(0x0100_0000_01b3);
1122 };
1123 mix(&mut h, ((rel_x as u16 as u64) << 16) | (rel_y as u16 as u64));
1124 mix(&mut h, ((sb_w as u16 as u64) << 16) | (sb_h as u16 as u64));
1125 match sprite {
1126 SpriteSource::Bitmap {
1127 bytes,
1128 format,
1129 tint,
1130 } => {
1131 mix(&mut h, 1);
1132 mix(&mut h, bytes.as_ptr() as usize as u64);
1133 mix(&mut h, bytes.len() as u64);
1134 mix(&mut h, format as u64);
1135 mix(&mut h, tint.0 as u64);
1136 }
1137 SpriteSource::Shader { state_hash, .. } => {
1138 mix(&mut h, 2);
1139 mix(&mut h, state_hash as u64);
1140 }
1141 SpriteSource::Svg {
1142 source,
1143 is_path_only,
1144 tint,
1145 stroke_width_x10,
1146 } => {
1147 mix(&mut h, 3);
1148 mix(&mut h, if is_path_only { 1 } else { 0 });
1149 mix(&mut h, stroke_width_x10 as u64);
1150 mix(&mut h, tint.0 as u64);
1151 let s = source.as_str().as_bytes();
1152 mix(&mut h, s.len() as u64);
1153 for &b in s {
1154 mix(&mut h, b as u64);
1155 }
1156 }
1157 SpriteSource::Arc { .. } => {}
1158 }
1159 h
1160 }
1161
1162 #[allow(clippy::too_many_arguments)]
1165 fn encode_single_op(
1166 &mut self,
1167 device: &wgpu::Device,
1168 queue: &wgpu::Queue,
1169 op: &DrawOp<'_>,
1170 eff_clip: Region,
1171 viewport: Region,
1172 sf: f32,
1173 use_ttf: bool,
1174 origin_x: f32,
1175 origin_y: f32,
1176 target_w: u32,
1177 target_h: u32,
1178 ) -> Result<(), AtlasGrowNeed> {
1179 let mut sb_f = snap_bounds(op.bounds, sf);
1180 if op.subpx_q4 != 0 {
1181 let (dx_q4, dy_q4) = crate::motion::unpack_subpx_q4(op.subpx_q4);
1182 sb_f[0] += (dx_q4 as f32) * (sf * 0.0625);
1183 sb_f[1] += (dy_q4 as f32) * (sf * 0.0625);
1184 }
1185 let clip_region = if op.clip_radius > 0 { op.clip } else { eff_clip };
1186 let mut sc_f = snap_clip(clip_region, sf);
1187 if (op.bounds.w == 1 && eff_clip.w == 1) || (op.bounds.h == 1 && eff_clip.h == 1) {
1188 let vp_clip_f = snap_clip(viewport, sf);
1189 if op.bounds.w == 1 && eff_clip.w == 1 {
1190 sc_f[2] = sc_f[2].max(sb_f[0] + sb_f[2]).min(vp_clip_f[2]);
1191 }
1192 if op.bounds.h == 1 && eff_clip.h == 1 {
1193 sc_f[3] = sc_f[3].max(sb_f[1] + sb_f[3]).min(vp_clip_f[3]);
1194 }
1195 }
1196 let clip_radius_px = (op.clip_radius as f32) * sf;
1197 let shifted_sb = [sb_f[0] - origin_x, sb_f[1] - origin_y, sb_f[2], sb_f[3]];
1198 let shifted_sc = [
1199 sc_f[0] - origin_x,
1200 sc_f[1] - origin_y,
1201 sc_f[2] - origin_x,
1202 sc_f[3] - origin_y,
1203 ];
1204
1205 match op.payload {
1206 DrawPayload::Quad {
1207 bg,
1208 bg_grad,
1209 border_color,
1210 rounded,
1211 border_width,
1212 } => {
1213 let raw_bw = border_width & 0x7F;
1214 let bw = if raw_bw == 0 {
1215 0.0
1216 } else {
1217 ((raw_bw as f32) * sf).round().max(1.0)
1218 };
1219 let horiz = (border_width & 0x80) != 0;
1220 let r = (rounded as f32) * sf;
1221 let is_shadow = border_color.a() == 0 && raw_bw > 0;
1222 if is_shadow {
1223 if bg.a() > 0 {
1224 self.primitives.push(make_shadow_primitive(
1225 shifted_sb,
1226 shifted_sc,
1227 clip_radius_px,
1228 r,
1229 (raw_bw as f32) * sf,
1230 bg,
1231 ));
1232 }
1233 } else if bg.a() > 0 || bg_grad.a() > 0 || (bw > 0.0 && border_color.a() > 0) {
1234 self.primitives.push(make_quad_primitive(
1235 shifted_sb,
1236 shifted_sc,
1237 clip_radius_px,
1238 r,
1239 bw,
1240 horiz,
1241 bg,
1242 bg_grad,
1243 border_color,
1244 ));
1245 }
1246 }
1247 DrawPayload::StyledQuad(sq) => {
1248 let ramp_v = match sq.paint {
1249 Paint::Solid(_) => None,
1250 Paint::LinearGradient { stops, space, .. }
1251 | Paint::RadialGradient { stops, space, .. }
1252 | Paint::ConicGradient { stops, space, .. } => {
1253 let Some(v) = self.ramp_atlas.get_or_insert(queue, stops, space, sq.opacity)
1254 else {
1255 return Err(AtlasGrowNeed {
1256 glyph_full: false,
1257 sprite_need: None,
1258 ramp_full: true,
1259 });
1260 };
1261 Some(v)
1262 }
1263 };
1264 if let Some(prim) = make_styled_quad_primitive(
1265 shifted_sb,
1266 shifted_sc,
1267 clip_radius_px,
1268 sq,
1269 sf,
1270 ramp_v,
1271 ) {
1272 self.primitives.push(prim);
1273 }
1274 }
1275 DrawPayload::TextRun {
1276 text,
1277 color,
1278 font_size,
1279 text_flags,
1280 } => {
1281 if text.is_empty() || color.a() == 0 {
1282 return Ok(());
1283 }
1284 let sb_x0 = sb_f[0].floor();
1285 let sb_y0 = sb_f[1].floor();
1286 let subpx_frac_x = sb_f[0] - sb_x0;
1287 let subpx_frac_y = sb_f[1] - sb_y0;
1288 let sb = Region::new(
1289 sb_x0 as i16,
1290 sb_y0 as i16,
1291 sb_f[2] as i16,
1292 sb_f[3] as i16,
1293 );
1294 let sc = Region::new(
1295 sc_f[0].floor() as i16,
1296 sc_f[1].floor() as i16,
1297 (sc_f[2] - sc_f[0]).max(0.0).ceil() as i16,
1298 (sc_f[3] - sc_f[1]).max(0.0).ceil() as i16,
1299 );
1300 let (adj_bounds, adj_sc, adj_flags, logical_fs, fs_q4) = compute_scaled_text_box(
1301 op.bounds,
1302 op.clip,
1303 viewport,
1304 sb,
1305 sc,
1306 text.as_str(),
1307 font_size,
1308 text_flags,
1309 sf,
1310 );
1311 let adj_sc_f = [
1312 adj_sc.x as f32 - origin_x,
1313 adj_sc.y as f32 - origin_y,
1314 adj_sc.right() as f32 - origin_x,
1315 adj_sc.bottom() as f32 - origin_y,
1316 ];
1317 let prim_before = self.primitives.len();
1318 if !self.encode_text_run(
1319 device,
1320 queue,
1321 adj_bounds,
1322 adj_sc,
1323 adj_sc_f,
1324 clip_radius_px,
1325 text.as_str(),
1326 color,
1327 logical_fs,
1328 fs_q4,
1329 adj_flags,
1330 use_ttf,
1331 subpx_frac_x,
1332 subpx_frac_y,
1333 origin_x,
1334 origin_y,
1335 target_w,
1336 target_h,
1337 ) {
1338 return Err(AtlasGrowNeed {
1339 glyph_full: true,
1340 sprite_need: None,
1341 ramp_full: false,
1342 });
1343 }
1344 if origin_x != 0.0 || origin_y != 0.0 {
1345 for p in &mut self.primitives[prim_before..] {
1346 p.bounds[0] -= origin_x;
1347 p.bounds[1] -= origin_y;
1348 }
1349 }
1350 }
1351 DrawPayload::Sprite(SpriteSource::Arc {
1352 thickness,
1353 start_deg10,
1354 sweep_deg10,
1355 fill_sweep_deg10,
1356 track_color,
1357 fill_color,
1358 }) => {
1359 self.primitives.push(make_arc_primitive(
1360 shifted_sb,
1361 shifted_sc,
1362 clip_radius_px,
1363 ((thickness.max(1) as f32) * sf).max(1.5),
1364 start_deg10,
1365 sweep_deg10,
1366 fill_sweep_deg10,
1367 track_color,
1368 fill_color,
1369 ));
1370 }
1371 DrawPayload::Sprite(sprite) => {
1372 sb_f[0] = sb_f[0].round();
1373 sb_f[1] = sb_f[1].round();
1374 let sb = Region::new(
1375 sb_f[0] as i16,
1376 sb_f[1] as i16,
1377 sb_f[2] as i16,
1378 sb_f[3] as i16,
1379 );
1380 let sc = Region::new(
1381 sc_f[0] as i16,
1382 sc_f[1] as i16,
1383 (sc_f[2] - sc_f[0]).max(0.0) as i16,
1384 (sc_f[3] - sc_f[1]).max(0.0) as i16,
1385 );
1386 let eff = sc.intersect(sb);
1387 if eff.is_empty() {
1388 return Ok(());
1389 }
1390 let w = eff.w.max(1) as usize;
1391 let h = eff.h.max(1) as usize;
1392 let cache_key = SpriteCacheKey {
1393 w: w as u32,
1394 h: h as u32,
1395 hash: Self::sprite_cache_hash(
1396 sprite,
1397 eff.x.saturating_sub(sb.x),
1398 eff.y.saturating_sub(sb.y),
1399 sb.w,
1400 sb.h,
1401 ),
1402 };
1403
1404 let uv = if let Some(cached_uv) = self.sprite_atlas.lookup(cache_key) {
1405 cached_uv
1406 } else {
1407 let len = w * h;
1408 if self.sprite_scratch.len() < len {
1409 self.sprite_scratch.resize(len, Rgba8888(0));
1410 }
1411 let slice = &mut self.sprite_scratch[..len];
1412 slice.fill(Rgba8888(0));
1413 rasterize_sprite_source(sb, eff, sprite, eff.x, eff.y, w, slice);
1414
1415 #[cfg(target_endian = "little")]
1416 let rgba_bytes: &[u8] = pod_as_bytes(slice);
1417 #[cfg(not(target_endian = "little"))]
1418 let rgba_bytes: &[u8] = {
1419 self.sprite_bytes_scratch.clear();
1420 self.sprite_bytes_scratch.reserve(len * 4);
1421 for px in slice.iter() {
1422 self.sprite_bytes_scratch
1423 .extend_from_slice(&px.to_rgba_bytes());
1424 }
1425 &self.sprite_bytes_scratch
1426 };
1427
1428 let Some(uv) = self
1429 .sprite_atlas
1430 .insert_and_upload(queue, cache_key, rgba_bytes)
1431 else {
1432 return Err(AtlasGrowNeed {
1433 glyph_full: false,
1434 sprite_need: Some((w as u32, h as u32)),
1435 ramp_full: false,
1436 });
1437 };
1438 uv
1439 };
1440
1441 self.primitives.push(GpuPrimitive {
1442 bounds: [
1443 eff.x as f32 - origin_x,
1444 eff.y as f32 - origin_y,
1445 w as f32,
1446 h as f32,
1447 ],
1448 clip: shifted_sc,
1449 uv,
1450 color0: [1.0; 4],
1451 color1: [0.0; 4],
1452 border_color: [0.0; 4],
1453 params: [0.0, 0.0, KIND_SPRITE, 0.0],
1454 extra: [clip_radius_px, 0.0, 0.0, 0.0],
1455 radii: [0.0; 4],
1456 grad_a: [0.0; 4],
1457 grad_b: [0.0; 4],
1458 xform: IDENTITY_XFORM,
1459 });
1460 }
1461 DrawPayload::RichText(rt) => {
1462 #[cfg(feature = "swash")]
1465 if use_ttf && clip_radius_px <= 0.0 && !rt.rtl_paragraph && !rt.spans.is_empty() {
1466 let has_var = rt.spans.iter().any(|sp| sp.has_variable_axes());
1467 let max_fs_px = rt
1468 .spans
1469 .iter()
1470 .map(|sp| sp.font_size.unwrap_or(rt.default_font_size).max(8) as f32 * sf)
1471 .fold(0.0f32, f32::max);
1472 let simple_single_line = (has_var
1473 || (self.slug_text_threshold_px.is_finite()
1474 && max_fs_px >= self.slug_text_threshold_px))
1475 && rt.spans.iter().all(|sp| {
1476 sp.bg_color.is_none()
1477 && sp.decoration.0 == 0
1478 && sp.letter_spacing_q4 == 0
1479 && !sp.text.as_str().contains('\n')
1480 && !sp.text.as_str().chars().any(crate::text_rich::is_emoji_char)
1481 });
1482 if simple_single_line {
1483 let mut shaped_runs: Vec<(
1484 std::sync::Arc<crate::swash_shaper::ShapedGlyphRun>,
1485 f32,
1486 [f32; 4],
1487 [Option<crate::swash_shaper::FontVariationAxis>; 2],
1488 )> = Vec::with_capacity(rt.spans.len());
1489 let mut total_adv = 0.0f32;
1490 let mut all_ok = true;
1491 for sp in rt.spans {
1492 let s = sp.text.as_str();
1493 if s.is_empty() {
1494 continue;
1495 }
1496 let span_fs =
1497 (sp.font_size.unwrap_or(rt.default_font_size).max(8) as f32) * sf;
1498 let mut vars: [Option<crate::swash_shaper::FontVariationAxis>; 2] =
1499 [None, None];
1500 let mut var_buf: [crate::swash_shaper::FontVariationAxis; 2] = [
1501 crate::swash_shaper::FontVariationAxis::weight(400.0),
1502 crate::swash_shaper::FontVariationAxis::width(100.0),
1503 ];
1504 let mut var_len = 0usize;
1505 if sp.var_weight_x10 != 0 {
1506 let ax = crate::swash_shaper::FontVariationAxis::weight(
1507 (sp.var_weight_x10 as f32) * 0.1,
1508 );
1509 vars[var_len] = Some(ax);
1510 var_buf[var_len] = ax;
1511 var_len += 1;
1512 }
1513 if sp.var_width_x10 != 0 {
1514 let ax = crate::swash_shaper::FontVariationAxis::width(
1515 (sp.var_width_x10 as f32) * 0.1,
1516 );
1517 vars[var_len] = Some(ax);
1518 var_buf[var_len] = ax;
1519 var_len += 1;
1520 }
1521 let Some(run) = crate::swash_shaper::shape_text_run_swash(
1522 s,
1523 sp.font,
1524 span_fs,
1525 sp.ligatures,
1526 &var_buf[..var_len],
1527 ) else {
1528 all_ok = false;
1529 break;
1530 };
1531 total_adv += run.total_advance;
1532 let col = color_to_f32(sp.color.unwrap_or(rt.default_color));
1533 shaped_runs.push((run, span_fs, col, vars));
1534 }
1535 let tol = (max_fs_px * 0.25).max(4.0);
1536 if all_ok
1537 && !shaped_runs.is_empty()
1538 && (rt.nowrap || total_adv <= sb_f[2] + tol)
1539 {
1540 if self.ui_slug_engine.is_none() {
1541 let raw_cache =
1542 self.pipeline_cache.as_deref().map(|c| c.wgpu_cache());
1543 self.ui_slug_engine =
1544 Some(super::slug_glyph::SlugTextEngine::new(
1545 device,
1546 self.target_format,
1547 raw_cache,
1548 ));
1549 if let Some(c) = &self.pipeline_cache {
1550 c.persist();
1551 }
1552 }
1553 let is_srgb = self.target_is_srgb;
1554 let mut slug = self.ui_slug_engine.take().unwrap();
1555 let align_x = match rt.align {
1556 crate::style::TextAlign::Center => {
1557 ((sb_f[2] - total_adv).max(0.0)) * 0.5
1558 }
1559 crate::style::TextAlign::Right => (sb_f[2] - total_adv).max(0.0),
1560 crate::style::TextAlign::Left => 0.0,
1561 };
1562 let ascent = crate::display::ttf_atlas::get_font_ascent_f32(max_fs_px)
1563 as f32;
1564 let baseline_y = shifted_sb[1] + ascent;
1565 let mut pen_x = shifted_sb[0] + align_x;
1566 let mut total_pushed = 0usize;
1567 for (run, span_fs, col, vars) in &shaped_runs {
1568 let mut var_buf: [crate::swash_shaper::FontVariationAxis; 2] = [
1569 crate::swash_shaper::FontVariationAxis::weight(400.0),
1570 crate::swash_shaper::FontVariationAxis::width(100.0),
1571 ];
1572 let mut var_len = 0usize;
1573 for v in vars.iter().flatten() {
1574 var_buf[var_len] = *v;
1575 var_len += 1;
1576 }
1577 total_pushed += slug.push_swash_run(
1578 run,
1579 pen_x,
1580 baseline_y,
1581 *span_fs,
1582 &var_buf[..var_len],
1583 shifted_sc,
1584 *col,
1585 target_w,
1586 target_h,
1587 is_srgb,
1588 );
1589 pen_x += run.total_advance;
1590 }
1591 self.ui_slug_engine = Some(slug);
1592 if total_pushed > 0 {
1593 return Ok(());
1594 }
1595 }
1596 }
1597 }
1598 let sb = snap_bounds_region_scaled(op.bounds, sf);
1599 let sc = Region::new(
1600 sc_f[0] as i16,
1601 sc_f[1] as i16,
1602 (sc_f[2] - sc_f[0]).max(0.0) as i16,
1603 (sc_f[3] - sc_f[1]).max(0.0) as i16,
1604 );
1605 let eff = sc.intersect(sb);
1606 if eff.is_empty() {
1607 return Ok(());
1608 }
1609 let w = eff.w.max(1) as usize;
1610 let h = eff.h.max(1) as usize;
1611 let mut kh: u32 = 0x5254_4558;
1612 rt.mix_hash(&mut kh);
1613 let hash = ((kh as u64) << 32)
1614 | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
1615 | (eff.y.saturating_sub(sb.y) as u16 as u64))
1616 ^ ((sf * 16.0).round() as u64);
1617 let cache_key = SpriteCacheKey {
1618 w: w as u32,
1619 h: h as u32,
1620 hash,
1621 };
1622 let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
1623 cached
1624 } else {
1625 let len = w * h;
1626 if self.sprite_scratch.len() < len {
1627 self.sprite_scratch.resize(len, Rgba8888(0));
1628 }
1629 let slice = &mut self.sprite_scratch[..len];
1630 slice.fill(Rgba8888(0));
1631 crate::renderers::software::rasterize_rich_text(
1632 rt, sb, eff, sf, eff.x, eff.y, w, slice,
1633 );
1634 let rgba_bytes = pod_as_bytes(slice);
1635 let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
1636 else {
1637 return Err(AtlasGrowNeed {
1638 glyph_full: false,
1639 sprite_need: Some((w as u32, h as u32)),
1640 ramp_full: false,
1641 });
1642 };
1643 u
1644 };
1645 self.primitives.push(GpuPrimitive {
1646 bounds: [
1647 eff.x as f32 - origin_x,
1648 eff.y as f32 - origin_y,
1649 w as f32,
1650 h as f32,
1651 ],
1652 clip: shifted_sc,
1653 uv,
1654 color0: [1.0; 4],
1655 color1: [0.0; 4],
1656 border_color: [0.0; 4],
1657 params: [0.0, 0.0, KIND_SPRITE, 0.0],
1658 extra: [clip_radius_px, 0.0, 0.0, 0.0],
1659 radii: [0.0; 4],
1660 grad_a: [0.0; 4],
1661 grad_b: [0.0; 4],
1662 xform: IDENTITY_XFORM,
1663 });
1664 }
1665 DrawPayload::DecodedImage(img) => {
1666 let sb = snap_bounds_region_scaled(op.bounds, sf);
1667 let sc = Region::new(
1668 sc_f[0] as i16,
1669 sc_f[1] as i16,
1670 (sc_f[2] - sc_f[0]).max(0.0) as i16,
1671 (sc_f[3] - sc_f[1]).max(0.0) as i16,
1672 );
1673 let eff = sc.intersect(sb);
1674 if eff.is_empty() {
1675 return Ok(());
1676 }
1677 let w = eff.w.max(1) as usize;
1678 let h = eff.h.max(1) as usize;
1679 let cache_rev = crate::image_pipeline::image_revision(img.id).unwrap_or(0);
1681 let mut kh: u32 = 0x4449_4D47 ^ (cache_rev as u32);
1682 img.mix_hash(&mut kh);
1683 let hash = ((kh as u64) << 32)
1684 | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
1685 | (eff.y.saturating_sub(sb.y) as u16 as u64))
1686 ^ ((sf * 16.0).round() as u64);
1687 let cache_key = SpriteCacheKey {
1688 w: w as u32,
1689 h: h as u32,
1690 hash,
1691 };
1692 let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
1693 cached
1694 } else {
1695 let len = w * h;
1696 if self.sprite_scratch.len() < len {
1697 self.sprite_scratch.resize(len, Rgba8888(0));
1698 }
1699 let slice = &mut self.sprite_scratch[..len];
1700 slice.fill(Rgba8888(0));
1701 crate::renderers::software::rasterize_decoded_image(
1702 img, sb, eff, sf, eff.x, eff.y, w, slice,
1703 );
1704 let rgba_bytes = pod_as_bytes(slice);
1705 let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
1706 else {
1707 return Err(AtlasGrowNeed {
1708 glyph_full: false,
1709 sprite_need: Some((w as u32, h as u32)),
1710 ramp_full: false,
1711 });
1712 };
1713 u
1714 };
1715 self.primitives.push(GpuPrimitive {
1716 bounds: [
1717 eff.x as f32 - origin_x,
1718 eff.y as f32 - origin_y,
1719 w as f32,
1720 h as f32,
1721 ],
1722 clip: shifted_sc,
1723 uv,
1724 color0: [1.0; 4],
1725 color1: [0.0; 4],
1726 border_color: [0.0; 4],
1727 params: [0.0, 0.0, KIND_SPRITE, 0.0],
1728 extra: [clip_radius_px, 0.0, 0.0, 0.0],
1729 radii: [0.0; 4],
1730 grad_a: [0.0; 4],
1731 grad_b: [0.0; 4],
1732 xform: IDENTITY_XFORM,
1733 });
1734 }
1735 DrawPayload::Vector(vec_spec) => {
1736 let sb = snap_bounds_region_scaled(op.bounds, sf);
1737 let sc = Region::new(
1738 sc_f[0] as i16,
1739 sc_f[1] as i16,
1740 (sc_f[2] - sc_f[0]).max(0.0) as i16,
1741 (sc_f[3] - sc_f[1]).max(0.0) as i16,
1742 );
1743 let eff = sc.intersect(sb);
1744 if eff.is_empty() {
1745 return Ok(());
1746 }
1747 let w = eff.w.max(1) as usize;
1748 let h = eff.h.max(1) as usize;
1749 let mut kh: u32 = 0x5645_4354;
1750 vec_spec.mix_hash(&mut kh);
1751 let hash = ((kh as u64) << 32)
1752 | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
1753 | (eff.y.saturating_sub(sb.y) as u16 as u64))
1754 ^ ((sf * 16.0).round() as u64);
1755 let cache_key = SpriteCacheKey {
1756 w: w as u32,
1757 h: h as u32,
1758 hash,
1759 };
1760 let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
1761 cached
1762 } else {
1763 let len = w * h;
1764 if self.sprite_scratch.len() < len {
1765 self.sprite_scratch.resize(len, Rgba8888(0));
1766 }
1767 let slice = &mut self.sprite_scratch[..len];
1768 slice.fill(Rgba8888(0));
1769 crate::vector_canvas::rasterize_vector_spec(
1770 vec_spec, sb, eff, sf, eff.x, eff.y, w, slice,
1771 );
1772 let rgba_bytes = pod_as_bytes(slice);
1773 let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
1774 else {
1775 return Err(AtlasGrowNeed {
1776 glyph_full: false,
1777 sprite_need: Some((w as u32, h as u32)),
1778 ramp_full: false,
1779 });
1780 };
1781 u
1782 };
1783 self.primitives.push(GpuPrimitive {
1784 bounds: [
1785 eff.x as f32 - origin_x,
1786 eff.y as f32 - origin_y,
1787 w as f32,
1788 h as f32,
1789 ],
1790 clip: shifted_sc,
1791 uv,
1792 color0: [1.0; 4],
1793 color1: [0.0; 4],
1794 border_color: [0.0; 4],
1795 params: [0.0, 0.0, KIND_SPRITE, 0.0],
1796 extra: [clip_radius_px, 0.0, 0.0, 0.0],
1797 radii: [0.0; 4],
1798 grad_a: [0.0; 4],
1799 grad_b: [0.0; 4],
1800 xform: IDENTITY_XFORM,
1801 });
1802 }
1803 DrawPayload::SceneCanvas(spec) => {
1804 let sb = snap_bounds_region_scaled(op.bounds, sf);
1806 let sc = Region::new(
1807 sc_f[0] as i16,
1808 sc_f[1] as i16,
1809 (sc_f[2] - sc_f[0]).max(0.0) as i16,
1810 (sc_f[3] - sc_f[1]).max(0.0) as i16,
1811 );
1812 let eff = sc.intersect(sb);
1813 if eff.is_empty() {
1814 return Ok(());
1815 }
1816 let w = eff.w.max(1) as usize;
1817 let h = eff.h.max(1) as usize;
1818 let hash = ((spec.content_hash() as u64) << 32)
1819 | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
1820 | (eff.y.saturating_sub(sb.y) as u16 as u64))
1821 ^ ((sf * 16.0).round() as u64);
1822 let cache_key = SpriteCacheKey {
1823 w: w as u32,
1824 h: h as u32,
1825 hash,
1826 };
1827 let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
1828 cached
1829 } else {
1830 let len = w * h;
1831 if self.sprite_scratch.len() < len {
1832 self.sprite_scratch.resize(len, Rgba8888(0));
1833 }
1834 let slice = &mut self.sprite_scratch[..len];
1835 slice.fill(Rgba8888(0));
1836 crate::canvas_scene::rasterize_scene_canvas(
1837 sb, eff, spec, sf, eff.x, eff.y, w, slice,
1838 );
1839 let rgba_bytes = pod_as_bytes(slice);
1840 let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
1841 else {
1842 return Err(AtlasGrowNeed {
1843 glyph_full: false,
1844 sprite_need: Some((w as u32, h as u32)),
1845 ramp_full: false,
1846 });
1847 };
1848 u
1849 };
1850 self.primitives.push(GpuPrimitive {
1851 bounds: [
1852 eff.x as f32 - origin_x,
1853 eff.y as f32 - origin_y,
1854 w as f32,
1855 h as f32,
1856 ],
1857 clip: shifted_sc,
1858 uv,
1859 color0: [1.0; 4],
1860 color1: [0.0; 4],
1861 border_color: [0.0; 4],
1862 params: [0.0, 0.0, KIND_SPRITE, 0.0],
1863 extra: [clip_radius_px, 0.0, 0.0, 0.0],
1864 radii: [0.0; 4],
1865 grad_a: [0.0; 4],
1866 grad_b: [0.0; 4],
1867 xform: IDENTITY_XFORM,
1868 });
1869 }
1870 DrawPayload::PushLayer(_)
1871 | DrawPayload::PopLayer
1872 | DrawPayload::ExternalTexture(_) => {}
1873 }
1874 Ok(())
1875 }
1876
1877 fn try_encode_ops(
1880 &mut self,
1881 device: &wgpu::Device,
1882 queue: &wgpu::Queue,
1883 ops: &[DrawOp<'_>],
1884 viewport: Region,
1885 scale_factor: f32,
1886 phys_w: u32,
1887 phys_h: u32,
1888 ) -> Result<(), AtlasGrowNeed> {
1889 self.try_encode_ops_filtered(device, queue, ops, viewport, scale_factor, phys_w, phys_h, None)
1890 }
1891
1892 #[inline]
1897 fn dirty_region_to_phys_scissor(
1898 dirty: Region,
1899 viewport: Region,
1900 sf: f32,
1901 pw: u32,
1902 ph: u32,
1903 ) -> (u32, u32, u32, u32) {
1904 let clipped = dirty.intersect(viewport);
1905 if clipped.is_empty() {
1906 return (0, 0, 0, 0);
1907 }
1908 let pc = snap_clip_region_scaled(clipped, sf);
1909 let pb = snap_bounds_region_scaled(clipped, sf);
1910 let margin = ((sf * 0.5).ceil() as i16).saturating_add(1);
1912 let x0 = pc.x.min(pb.x).saturating_sub(margin).max(0) as u32;
1913 let y0 = pc.y.min(pb.y).saturating_sub(margin).max(0) as u32;
1914 let x1 = (pc.right().max(pb.right()).saturating_add(margin).max(0) as u32).min(pw);
1915 let y1 = (pc.bottom().max(pb.bottom()).saturating_add(margin).max(0) as u32).min(ph);
1916 let sx = x0.min(pw);
1917 let sy = y0.min(ph);
1918 let sw = x1.saturating_sub(sx);
1919 let sh = y1.saturating_sub(sy);
1920 (sx, sy, sw, sh)
1921 }
1922
1923 #[allow(clippy::too_many_arguments)]
1926 fn try_encode_ops_filtered(
1927 &mut self,
1928 device: &wgpu::Device,
1929 queue: &wgpu::Queue,
1930 ops: &[DrawOp<'_>],
1931 viewport: Region,
1932 scale_factor: f32,
1933 phys_w: u32,
1934 phys_h: u32,
1935 dirty_filter: Option<(Region, Region)>,
1936 ) -> Result<(), AtlasGrowNeed> {
1937 self.primitives.clear();
1938 self.ui_slug_segments.clear();
1939 if let Some(slug) = &mut self.ui_slug_engine {
1940 slug.begin_frame();
1941 }
1942 if viewport.is_empty() {
1943 return Ok(());
1944 }
1945
1946 let sf = scale_factor.clamp(0.5, 4.0);
1947 let use_ttf = crate::display::ttf_atlas::has_system_font();
1948 let mut batch_prim_start = 0u32;
1949
1950 with_spatial_occlusion(ops, |occlusion| {
1951 for (idx, op) in ops.iter().enumerate() {
1952 let raw_clip = match op.payload {
1953 DrawPayload::StyledQuad(sq) if sq.transform.is_some() => viewport.intersect(op.clip),
1954 _ => viewport.intersect(op.clip).intersect(op.bounds),
1955 };
1956 if raw_clip.is_empty() {
1957 continue;
1958 }
1959 let eff_clip = match occlusion {
1960 Some(grid) => grid.clip_region(raw_clip, idx),
1961 None => compute_unoccluded_clip(raw_clip, &ops[(idx + 1)..]),
1962 };
1963 if eff_clip.is_empty() {
1964 continue;
1965 }
1966 if let Some((du, du_phys)) = dirty_filter {
1967 let touches_dirty = match op.payload {
1968 DrawPayload::TextRun {
1969 text,
1970 color,
1971 font_size,
1972 text_flags,
1973 } => {
1974 if text.is_empty() || color.a() == 0 {
1975 false
1976 } else if viewport.intersect(op.clip).intersect(du).is_empty() {
1977 false
1979 } else if !raw_clip.intersect(du).is_empty() {
1980 true
1982 } else {
1983 let sb_phys = snap_bounds_region_scaled(op.bounds, sf);
1988 let clip_reg = if op.clip_radius > 0 { op.clip } else { eff_clip };
1989 let sc_phys = snap_clip_region_scaled(clip_reg, sf);
1990 let (_, adj_sc, _, _, _) = compute_scaled_text_box(
1991 op.bounds,
1992 op.clip,
1993 viewport,
1994 sb_phys,
1995 sc_phys,
1996 text.as_str(),
1997 font_size,
1998 text_flags,
1999 sf,
2000 );
2001 !adj_sc.intersect(du_phys).is_empty()
2002 }
2003 }
2004 DrawPayload::StyledQuad(sq) if sq.transform.is_some() => {
2005 !op.clip.intersect(du).is_empty()
2006 }
2007 _ => !eff_clip.intersect(du).is_empty(),
2008 };
2009 if !touches_dirty {
2010 continue;
2011 }
2012 }
2013 let prim_before = self.primitives.len() as u32;
2014 let slug_before = self
2015 .ui_slug_engine
2016 .as_ref()
2017 .map(|s| s.instance_count())
2018 .unwrap_or(0);
2019 self.encode_single_op(
2020 device, queue, op, eff_clip, viewport, sf, use_ttf, 0.0, 0.0, phys_w, phys_h,
2021 )?;
2022 let slug_after = self
2023 .ui_slug_engine
2024 .as_ref()
2025 .map(|s| s.instance_count())
2026 .unwrap_or(0);
2027 if slug_after > slug_before {
2028 self.ui_slug_segments.push((
2029 batch_prim_start,
2030 prim_before,
2031 slug_before,
2032 slug_after,
2033 ));
2034 batch_prim_start = prim_before;
2035 }
2036 }
2037 Ok(())
2038 })?;
2039 if !self.ui_slug_segments.is_empty() {
2040 let final_prim = self.primitives.len() as u32;
2041 if final_prim > batch_prim_start {
2042 self.ui_slug_segments.push((batch_prim_start, final_prim, 0, 0));
2043 }
2044 }
2045 Ok(())
2046 }
2047
2048 fn get_or_build_text_layout(
2049 &mut self,
2050 text: &str,
2051 logical_font_size: u8,
2052 font_size_q4: u16,
2053 max_width: i16,
2054 text_flags: u8,
2055 use_ttf: bool,
2056 ) -> Arc<CachedTextLayout> {
2057 let logical_fs = logical_font_size.max(8);
2058 let q4 = font_size_q4.clamp(32, 1020);
2059 let key = TextLayoutKey {
2060 text_hash: hash_layout_text(text),
2061 text_len: text.len() as u32,
2062 logical_font_size: logical_fs,
2063 font_size_q4: q4,
2064 max_width,
2065 text_flags,
2066 use_ttf,
2067 };
2068 if let Some(hit) = self.text_layout_cache.get(&key) {
2069 if hit.text.as_str() == text {
2070 self.text_layout_hits = self.text_layout_hits.wrapping_add(1);
2071 return Arc::clone(hit);
2072 }
2073 }
2074
2075 let render_fs = (q4 as f32) * 0.25;
2076 let fs_u8 = ((q4 + 2) >> 2).clamp(8, 255) as u8;
2077 let scale_ratio = render_fs / (logical_fs as f32);
2078 let is_ellipsis = (text_flags & 0x04) != 0;
2079 let is_nowrap = (text_flags & 0x08) != 0;
2080 let lines = if use_ttf {
2081 let logical_max_w = ((max_width as f32) / scale_ratio)
2082 .round()
2083 .clamp(1.0, i16::MAX as f32) as i16;
2084 split_text_lines(text, logical_fs, logical_max_w, is_nowrap || is_ellipsis)
2085 } else {
2086 split_text_lines(text, fs_u8, max_width, is_nowrap || is_ellipsis)
2087 };
2088 let line_count = lines.len();
2089 let char_h = if use_ttf {
2090 (render_fs.round() as i16).max(8)
2091 } else {
2092 (fs_u8 as i16).max(8)
2093 };
2094 let line_step = if use_ttf {
2095 ((render_fs * 1.25).round() as i16).max(char_h)
2096 } else {
2097 ((fs_u8 as i16) * 5 / 4).max(char_h)
2098 };
2099 let ascent = if use_ttf {
2100 crate::display::ttf_atlas::get_font_ascent_f32(render_fs) as i16
2101 } else {
2102 char_h
2103 };
2104 let dot_w = measure_char_advance('.', fs_u8);
2105 let dot_adv_f = if use_ttf {
2106 crate::display::ttf_atlas::measure_ttf_char_advance_f32('.', logical_fs)
2107 .map(|a| a * scale_ratio)
2108 .unwrap_or(dot_w as f32)
2109 } else {
2110 dot_w as f32
2111 };
2112 let total_h = if line_count == 0 {
2113 0
2114 } else {
2115 char_h.saturating_add(line_step.saturating_mul((line_count as i16) - 1))
2116 };
2117
2118 let mut glyphs = Vec::with_capacity(text.len().min(128));
2119 for (line_idx, &(b_start, b_end, raw_line_w_orig)) in lines.as_slice().iter().enumerate() {
2120 let line_str = &text[b_start..b_end];
2121 let raw_line_w = if use_ttf {
2122 (crate::display::measure_line_width_f32(line_str, logical_fs) * scale_ratio).ceil()
2123 as i16
2124 } else {
2125 raw_line_w_orig
2126 };
2127 let need_ellipsis = is_ellipsis && raw_line_w > max_width && max_width > dot_w * 3;
2128 let eff_w = if need_ellipsis {
2129 max_width
2130 } else {
2131 raw_line_w.min(max_width)
2132 };
2133 let start_rel_x = align_offset_x(max_width, eff_w, text_flags);
2134 let rel_y = if use_ttf {
2135 ascent.saturating_add((line_idx as i16).saturating_mul(line_step))
2136 } else {
2137 (line_idx as i16).saturating_mul(line_step)
2138 };
2139
2140 if use_ttf {
2141 let mut pen_x = start_rel_x as f32;
2142 let max_x_before_dots_f = (max_width as f32) - dot_adv_f * 3.0;
2143 let mut prev_ch: Option<char> = None;
2144 for ch in line_str.chars() {
2145 if let Some(p) = prev_ch {
2146 pen_x += crate::display::ttf_atlas::measure_ttf_kerning_f32(
2147 p, ch, logical_fs,
2148 ) * scale_ratio;
2149 }
2150 let adv_f =
2151 crate::display::ttf_atlas::measure_ttf_char_advance_f32(ch, logical_fs)
2152 .map(|a| a * scale_ratio)
2153 .unwrap_or_else(|| {
2154 (measure_char_advance(ch, logical_fs) as f32) * scale_ratio
2155 });
2156 if need_ellipsis && pen_x + adv_f > max_x_before_dots_f + 0.01 {
2157 for _ in 0..3 {
2158 glyphs.push(ShapedGlyphPos {
2159 ch: '.',
2160 rel_x: pen_x.round() as i16,
2161 rel_y,
2162 });
2163 pen_x += dot_adv_f;
2164 }
2165 break;
2166 }
2167 if ch != ' ' {
2168 glyphs.push(ShapedGlyphPos {
2169 ch,
2170 rel_x: pen_x.round() as i16,
2171 rel_y,
2172 });
2173 }
2174 pen_x += adv_f;
2175 prev_ch = Some(ch);
2176 }
2177 } else {
2178 let mut rel_x = start_rel_x;
2179 let max_x_before_dots = max_width.saturating_sub(dot_w * 3);
2180 let mut prev_ch: Option<char> = None;
2181 for ch in line_str.chars() {
2182 if let Some(p) = prev_ch {
2183 rel_x = rel_x.saturating_add(measure_char_kerning(p, ch, fs_u8));
2184 }
2185 let adv = measure_char_advance(ch, fs_u8);
2186 if need_ellipsis && rel_x.saturating_add(adv) > max_x_before_dots {
2187 for _ in 0..3 {
2188 glyphs.push(ShapedGlyphPos {
2189 ch: '.',
2190 rel_x,
2191 rel_y,
2192 });
2193 rel_x = rel_x.saturating_add(dot_w);
2194 }
2195 break;
2196 }
2197 if ch != ' ' {
2198 glyphs.push(ShapedGlyphPos { ch, rel_x, rel_y });
2199 }
2200 rel_x = rel_x.saturating_add(adv);
2201 prev_ch = Some(ch);
2202 }
2203 }
2204 }
2205
2206 let built = Arc::new(CachedTextLayout {
2207 text: String::from(text),
2208 total_h,
2209 glyphs,
2210 });
2211 if self.text_layout_cache.len() >= MAX_TEXT_LAYOUT_CACHE_ENTRIES {
2212 self.text_layout_cache.clear();
2213 }
2214 self.text_layout_cache.insert(key, Arc::clone(&built));
2215 built
2216 }
2217
2218 #[allow(clippy::too_many_arguments)]
2219 fn encode_text_run(
2220 &mut self,
2221 device: &wgpu::Device,
2222 queue: &wgpu::Queue,
2223 bounds: Region,
2224 clip: Region,
2225 clip_f32: [f32; 4],
2226 clip_radius_px: f32,
2227 text: &str,
2228 color: Color,
2229 logical_font_size: u8,
2230 font_size_q4: u16,
2231 text_flags: u8,
2232 use_ttf: bool,
2233 subpx_frac_x: f32,
2234 subpx_frac_y: f32,
2235 origin_x: f32,
2236 origin_y: f32,
2237 target_w: u32,
2238 target_h: u32,
2239 ) -> bool {
2240 let col_f32 = color_to_f32(color);
2241 let render_fs = (font_size_q4.clamp(32, 1020) as f32) * 0.25;
2242 let slug_offset_x = subpx_frac_x - origin_x;
2243 let slug_offset_y = subpx_frac_y - origin_y;
2244 let has_subpx = if subpx_frac_x != 0.0 || subpx_frac_y != 0.0 {
2245 1.0
2246 } else {
2247 0.0
2248 };
2249 let route_to_slug = use_ttf
2250 && clip_radius_px <= 0.0
2251 && self.slug_text_threshold_px.is_finite()
2252 && render_fs >= self.slug_text_threshold_px;
2253
2254 #[cfg(feature = "swash")]
2256 if route_to_slug {
2257 let is_ellipsis = (text_flags & 0x04) != 0;
2258 let is_nowrap = (text_flags & 0x08) != 0;
2259 if !is_ellipsis
2260 && !text.contains('\n')
2261 && !text.chars().any(crate::text_rich::is_emoji_char)
2262 {
2263 if let Some(run) = crate::swash_shaper::shape_text_run_swash(
2264 text,
2265 crate::text_rich::FontSpec::SANS,
2266 render_fs,
2267 true,
2268 &[],
2269 ) {
2270 let tol = (render_fs * 0.25).max(4.0);
2271 if is_nowrap || run.total_advance <= (bounds.w as f32) + tol {
2272 if self.ui_slug_engine.is_none() {
2273 let raw_cache = self.pipeline_cache.as_deref().map(|c| c.wgpu_cache());
2274 self.ui_slug_engine = Some(super::slug_glyph::SlugTextEngine::new(
2275 device,
2276 self.target_format,
2277 raw_cache,
2278 ));
2279 if let Some(c) = &self.pipeline_cache {
2280 c.persist();
2281 }
2282 }
2283 let is_srgb = self.target_is_srgb;
2284 let mut slug = self.ui_slug_engine.take().unwrap();
2285 let line_h = (render_fs.round() as i16).max(8);
2286 let top_y = bounds
2287 .y
2288 .saturating_add(bounds.h.saturating_sub(line_h).max(0) >> 1);
2289 let eff_w = (run.total_advance.ceil() as i16).clamp(0, bounds.w);
2290 let align_x = align_offset_x(bounds.w, eff_w, text_flags) as f32;
2291 let ascent =
2292 crate::display::ttf_atlas::get_font_ascent_f32(render_fs) as i16;
2293 let baseline_y =
2294 (top_y.saturating_add(ascent) as f32) + slug_offset_y;
2295 let pen_x0 = (bounds.x as f32) + align_x + slug_offset_x;
2296 let pushed = slug.push_swash_run(
2297 &run,
2298 pen_x0,
2299 baseline_y,
2300 render_fs,
2301 &[],
2302 clip_f32,
2303 col_f32,
2304 target_w,
2305 target_h,
2306 is_srgb,
2307 );
2308 self.ui_slug_engine = Some(slug);
2309 if pushed > 0 {
2310 return true;
2311 }
2312 }
2313 }
2314 }
2315 }
2316
2317 let layout = self.get_or_build_text_layout(
2318 text,
2319 logical_font_size,
2320 font_size_q4,
2321 bounds.w,
2322 text_flags,
2323 use_ttf,
2324 );
2325 if layout.glyphs.is_empty() {
2326 return true;
2327 }
2328 let top_y = bounds
2329 .y
2330 .saturating_add(bounds.h.saturating_sub(layout.total_h).max(0) >> 1);
2331
2332 if route_to_slug {
2333 if self.ui_slug_engine.is_none() {
2334 let raw_cache = self.pipeline_cache.as_deref().map(|c| c.wgpu_cache());
2335 self.ui_slug_engine = Some(super::slug_glyph::SlugTextEngine::new(
2336 device,
2337 self.target_format,
2338 raw_cache,
2339 ));
2340 if let Some(c) = &self.pipeline_cache {
2341 c.persist();
2342 }
2343 }
2344 let is_srgb = self.target_is_srgb;
2345 let mut slug = self.ui_slug_engine.take().unwrap();
2346 let mut ok = true;
2347 for g in &layout.glyphs {
2348 let pen_x = (bounds.x.saturating_add(g.rel_x) as f32) + slug_offset_x;
2349 let baseline_y = (top_y.saturating_add(g.rel_y) as f32) + slug_offset_y;
2350 if !slug.push_ui_glyph(
2351 g.ch,
2352 pen_x,
2353 baseline_y,
2354 render_fs,
2355 clip_f32,
2356 col_f32,
2357 target_w,
2358 target_h,
2359 is_srgb,
2360 ) {
2361 let Some(entry) = self
2363 .glyph_atlas
2364 .get_or_insert(queue, g.ch, font_size_q4, use_ttf)
2365 else {
2366 ok = false;
2367 break;
2368 };
2369 if entry.width > 0 && entry.height > 0 {
2370 let gx = bounds
2371 .x
2372 .saturating_add(g.rel_x)
2373 .saturating_add(entry.xmin);
2374 let gy = top_y
2375 .saturating_add(g.rel_y)
2376 .saturating_sub(entry.height)
2377 .saturating_sub(entry.ymin);
2378 let greg = Region::new(gx, gy, entry.width, entry.height);
2379 if !clip.intersect(greg).is_empty() {
2380 self.primitives.push(GpuPrimitive {
2381 bounds: [
2382 (gx as f32) + subpx_frac_x,
2383 (gy as f32) + subpx_frac_y,
2384 entry.width as f32,
2385 entry.height as f32,
2386 ],
2387 clip: clip_f32,
2388 uv: entry.uv,
2389 color0: col_f32,
2390 color1: [0.0; 4],
2391 border_color: [0.0; 4],
2392 params: [0.0, 0.0, KIND_GLYPH, 0.0],
2393 extra: [clip_radius_px, has_subpx, 0.0, 0.0],
2394 radii: [0.0; 4],
2395 grad_a: [0.0; 4],
2396 grad_b: [0.0; 4],
2397 xform: IDENTITY_XFORM,
2398 });
2399 }
2400 }
2401 }
2402 }
2403 self.ui_slug_engine = Some(slug);
2404 return ok;
2405 }
2406
2407 for g in &layout.glyphs {
2408 let Some(entry) = self
2409 .glyph_atlas
2410 .get_or_insert(queue, g.ch, font_size_q4, use_ttf)
2411 else {
2412 return false;
2413 };
2414 if entry.width > 0 && entry.height > 0 {
2415 let gx = bounds
2416 .x
2417 .saturating_add(g.rel_x)
2418 .saturating_add(entry.xmin);
2419 let gy = if use_ttf {
2420 top_y
2421 .saturating_add(g.rel_y)
2422 .saturating_sub(entry.height)
2423 .saturating_sub(entry.ymin)
2424 } else {
2425 top_y.saturating_add(g.rel_y)
2426 };
2427 let greg = Region::new(gx, gy, entry.width, entry.height);
2428 if !clip.intersect(greg).is_empty() {
2429 self.primitives.push(GpuPrimitive {
2431 bounds: [
2432 (gx as f32) + subpx_frac_x,
2433 (gy as f32) + subpx_frac_y,
2434 entry.width as f32,
2435 entry.height as f32,
2436 ],
2437 clip: clip_f32,
2438 uv: entry.uv,
2439 color0: col_f32,
2440 color1: [0.0; 4],
2441 border_color: [0.0; 4],
2442 params: [0.0, 0.0, KIND_GLYPH, 0.0],
2443 extra: [clip_radius_px, has_subpx, 0.0, 0.0],
2444 radii: [0.0; 4],
2445 grad_a: [0.0; 4],
2446 grad_b: [0.0; 4],
2447 xform: IDENTITY_XFORM,
2448 });
2449 }
2450 }
2451 }
2452 true
2453 }
2454
2455 fn handle_atlas_grow(&mut self, device: &wgpu::Device, need: AtlasGrowNeed) -> (bool, bool) {
2456 let mut dirty = false;
2457 let mut can_retry = true;
2458 if need.glyph_full && self.glyph_atlas.reset_or_grow(device) {
2459 dirty = true;
2460 }
2461 if need.ramp_full && self.ramp_atlas.reset_or_grow(device) {
2462 dirty = true;
2463 }
2464 if let Some((sw, sh)) = need.sprite_need {
2465 let (recreated, retry) = self.sprite_atlas.reset_or_grow(device, sw, sh);
2466 if recreated {
2467 dirty = true;
2468 }
2469 if !retry {
2470 can_retry = false;
2471 }
2472 }
2473 (dirty, can_retry)
2474 }
2475
2476 #[allow(clippy::too_many_arguments)]
2480 pub fn render_to_view(
2481 &mut self,
2482 device: &wgpu::Device,
2483 queue: &wgpu::Queue,
2484 ops: &[DrawOp<'_>],
2485 viewport: Region,
2486 scale_factor: f32,
2487 target_view: &wgpu::TextureView,
2488 phys_width: u32,
2489 phys_height: u32,
2490 clear_color: wgpu::Color,
2491 ) {
2492 self.render_to_view_with_damage_hints(
2493 device,
2494 queue,
2495 ops,
2496 viewport,
2497 scale_factor,
2498 target_view,
2499 phys_width,
2500 phys_height,
2501 clear_color,
2502 None,
2503 );
2504 }
2505
2506 #[allow(clippy::too_many_arguments)]
2509 pub fn render_to_view_with_damage_hints(
2510 &mut self,
2511 device: &wgpu::Device,
2512 queue: &wgpu::Queue,
2513 ops: &[DrawOp<'_>],
2514 viewport: Region,
2515 scale_factor: f32,
2516 target_view: &wgpu::TextureView,
2517 phys_width: u32,
2518 phys_height: u32,
2519 clear_color: wgpu::Color,
2520 damage_hints: Option<&[Region]>,
2521 ) {
2522 if ops_have_layers_or_blend(ops) && !viewport.is_empty() {
2523 self.render_to_view_multi_pass(
2524 device,
2525 queue,
2526 ops,
2527 viewport,
2528 scale_factor,
2529 target_view,
2530 phys_width,
2531 phys_height,
2532 clear_color,
2533 damage_hints,
2534 );
2535 return;
2536 }
2537
2538 if ops
2539 .iter()
2540 .any(|op| matches!(op.payload, DrawPayload::SceneCanvas(_)))
2541 && !viewport.is_empty()
2542 {
2543 self.render_to_view_with_scene_canvas(
2544 device,
2545 queue,
2546 ops,
2547 viewport,
2548 scale_factor,
2549 target_view,
2550 phys_width,
2551 phys_height,
2552 clear_color,
2553 );
2554 return;
2555 }
2556
2557 let mut bind_group_dirty = false;
2558 for _attempt in 0..4 {
2559 match self.try_encode_ops(
2560 device,
2561 queue,
2562 ops,
2563 viewport,
2564 scale_factor,
2565 phys_width.max(1),
2566 phys_height.max(1),
2567 ) {
2568 Ok(()) => break,
2569 Err(need) => {
2570 let (dirty, can_retry) = self.handle_atlas_grow(device, need);
2571 if dirty {
2572 bind_group_dirty = true;
2573 }
2574 if !can_retry {
2575 break;
2576 }
2577 }
2578 }
2579 }
2580 if let Some(slug) = &mut self.ui_slug_engine {
2581 slug.sync_and_finalize(device, queue);
2582 }
2583
2584 if self.primitives.len() > self.instance_capacity {
2585 self.instance_capacity = self.primitives.len().next_power_of_two();
2586 self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
2587 self.instance_buf_dirty_all = true;
2588 bind_group_dirty = true;
2589 }
2590 if bind_group_dirty {
2591 self.rebuild_bind_group(device);
2592 }
2593
2594 let slot0 = AlignedViewportSlot {
2595 uniform: ViewportUniform {
2596 size: [phys_width.max(1) as f32, phys_height.max(1) as f32],
2597 is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
2598 _pad: 0.0,
2599 },
2600 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
2601 };
2602 queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
2603 self.sync_instance_buffer(queue);
2604
2605 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
2606 label: Some("velox_wgpu_render_encoder"),
2607 });
2608 {
2609 let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2610 label: Some("velox_wgpu_render_pass"),
2611 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2612 view: target_view,
2613 depth_slice: None,
2614 resolve_target: None,
2615 ops: wgpu::Operations {
2616 load: wgpu::LoadOp::Clear(clear_color),
2617 store: wgpu::StoreOp::Store,
2618 },
2619 })],
2620 depth_stencil_attachment: None,
2621 occlusion_query_set: None,
2622 timestamp_writes: None,
2623 multiview_mask: None,
2624 });
2625 if self.ui_slug_segments.is_empty() {
2626 if !self.uploaded_primitives.is_empty() {
2627 rpass.set_pipeline(&self.pipeline);
2628 rpass.set_bind_group(0, &self.bind_group, &[0]);
2629 rpass.draw(0..6, 0..(self.uploaded_primitives.len() as u32));
2630 }
2631 } else {
2632 for &(p_start, p_end, s_start, s_end) in &self.ui_slug_segments {
2633 if p_end > p_start {
2634 rpass.set_pipeline(&self.pipeline);
2635 rpass.set_bind_group(0, &self.bind_group, &[0]);
2636 rpass.draw(0..6, p_start..p_end);
2637 }
2638 if s_end > s_start {
2639 if let Some(slug) = &self.ui_slug_engine {
2640 slug.draw_range(&mut rpass, s_start, s_end);
2641 }
2642 }
2643 }
2644 }
2645 }
2646 queue.submit([encoder.finish()]);
2647 if let Some(fx) = &mut self.effects {
2648 fx.tick_idle_frame();
2649 }
2650 if let Some(canvas) = &mut self.canvas_engine {
2651 canvas.tick_frame_reclaim();
2652 }
2653 }
2654
2655 #[allow(clippy::too_many_arguments)]
2659 pub fn render_to_view_dirty(
2660 &mut self,
2661 device: &wgpu::Device,
2662 queue: &wgpu::Queue,
2663 ops: &[DrawOp<'_>],
2664 viewport: Region,
2665 scale_factor: f32,
2666 target_view: &wgpu::TextureView,
2667 phys_width: u32,
2668 phys_height: u32,
2669 dirty_regions: &[Region],
2670 clear_color: wgpu::Color,
2671 ) {
2672 let _ = self.render_to_view_dirty_with_copy(
2673 device,
2674 queue,
2675 ops,
2676 viewport,
2677 scale_factor,
2678 target_view,
2679 phys_width,
2680 phys_height,
2681 dirty_regions,
2682 clear_color,
2683 None,
2684 );
2685 }
2686
2687 #[allow(clippy::too_many_arguments)]
2692 pub fn render_to_view_dirty_with_copy(
2693 &mut self,
2694 device: &wgpu::Device,
2695 queue: &wgpu::Queue,
2696 ops: &[DrawOp<'_>],
2697 viewport: Region,
2698 scale_factor: f32,
2699 target_view: &wgpu::TextureView,
2700 phys_width: u32,
2701 phys_height: u32,
2702 dirty_regions: &[Region],
2703 clear_color: wgpu::Color,
2704 post_copy: Option<(&wgpu::Texture, &wgpu::Texture)>,
2705 ) -> bool {
2706 let pw = phys_width.max(1);
2707 let ph = phys_height.max(1);
2708 let submit_copy_only = |src_tex: &wgpu::Texture, dst_tex: &wgpu::Texture| {
2709 let mut copy_enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
2710 label: Some("velox_wgpu_persistent_copy_encoder"),
2711 });
2712 copy_enc.copy_texture_to_texture(
2713 src_tex.as_image_copy(),
2714 dst_tex.as_image_copy(),
2715 wgpu::Extent3d {
2716 width: pw,
2717 height: ph,
2718 depth_or_array_layers: 1,
2719 },
2720 );
2721 queue.submit([copy_enc.finish()]);
2722 };
2723
2724 if dirty_regions.is_empty() {
2725 self.render_to_view(
2726 device,
2727 queue,
2728 ops,
2729 viewport,
2730 scale_factor,
2731 target_view,
2732 pw,
2733 ph,
2734 clear_color,
2735 );
2736 if let Some((src_tex, dst_tex)) = post_copy {
2737 submit_copy_only(src_tex, dst_tex);
2738 }
2739 return false;
2740 }
2741 if crate::renderers::software::ops_have_layers_or_blend(ops) && !viewport.is_empty() {
2742 self.render_to_view_multi_pass(
2744 device,
2745 queue,
2746 ops,
2747 viewport,
2748 scale_factor,
2749 target_view,
2750 pw,
2751 ph,
2752 clear_color,
2753 Some(dirty_regions),
2754 );
2755 if let Some((src_tex, dst_tex)) = post_copy {
2756 submit_copy_only(src_tex, dst_tex);
2757 }
2758 return false;
2759 }
2760 let opaque_background = ops.first().is_some_and(|op| {
2763 matches!(op.payload, DrawPayload::Quad { rounded: 0, border_width: 0, .. })
2764 && op.clip_radius == 0
2765 && crate::renderers::software::opaque_core_rect(op).intersect(viewport) == viewport
2766 });
2767 if !opaque_background
2768 || ops.iter().any(|op| matches!(op.payload, DrawPayload::SceneCanvas(_)))
2769 {
2770 self.render_to_view(
2771 device,
2772 queue,
2773 ops,
2774 viewport,
2775 scale_factor,
2776 target_view,
2777 pw,
2778 ph,
2779 clear_color,
2780 );
2781 if let Some((src_tex, dst_tex)) = post_copy {
2782 submit_copy_only(src_tex, dst_tex);
2783 }
2784 return false;
2785 }
2786
2787 let sf = scale_factor.clamp(0.5, 4.0);
2788
2789 let mut du_x0 = i16::MAX;
2791 let mut du_y0 = i16::MAX;
2792 let mut du_x1 = i16::MIN;
2793 let mut du_y1 = i16::MIN;
2794 let mut phys_x0 = u32::MAX;
2795 let mut phys_y0 = u32::MAX;
2796 let mut phys_x1 = 0u32;
2797 let mut phys_y1 = 0u32;
2798 for &d in dirty_regions {
2799 let c = d.intersect(viewport);
2800 if !c.is_empty() {
2801 du_x0 = du_x0.min(c.x);
2802 du_y0 = du_y0.min(c.y);
2803 du_x1 = du_x1.max(c.right());
2804 du_y1 = du_y1.max(c.bottom());
2805 let (sx, sy, sw, sh) = Self::dirty_region_to_phys_scissor(d, viewport, sf, pw, ph);
2806 if sw > 0 && sh > 0 {
2807 phys_x0 = phys_x0.min(sx);
2808 phys_y0 = phys_y0.min(sy);
2809 phys_x1 = phys_x1.max(sx.saturating_add(sw));
2810 phys_y1 = phys_y1.max(sy.saturating_add(sh));
2811 }
2812 }
2813 }
2814 if du_x0 >= du_x1 || du_y0 >= du_y1 || phys_x0 >= phys_x1 || phys_y0 >= phys_y1 {
2815 if let Some((src_tex, dst_tex)) = post_copy {
2816 submit_copy_only(src_tex, dst_tex);
2817 }
2818 return true;
2819 }
2820 let dirty_union = Region::new(
2821 du_x0.saturating_sub(2),
2822 du_y0.saturating_sub(2),
2823 du_x1.saturating_sub(du_x0).saturating_add(4),
2824 du_y1.saturating_sub(du_y0).saturating_add(4),
2825 )
2826 .intersect(viewport);
2827 let dirty_phys_union = Region::new(
2828 phys_x0.min(i16::MAX as u32) as i16,
2829 phys_y0.min(i16::MAX as u32) as i16,
2830 phys_x1.saturating_sub(phys_x0).min(i16::MAX as u32) as i16,
2831 phys_y1.saturating_sub(phys_y0).min(i16::MAX as u32) as i16,
2832 );
2833
2834 let mut bind_group_dirty = false;
2835 for _attempt in 0..4 {
2836 match self.try_encode_ops_filtered(
2837 device,
2838 queue,
2839 ops,
2840 viewport,
2841 sf,
2842 pw,
2843 ph,
2844 Some((dirty_union, dirty_phys_union)),
2845 ) {
2846 Ok(()) => break,
2847 Err(need) => {
2848 let (dirty, can_retry) = self.handle_atlas_grow(device, need);
2849 if dirty {
2850 bind_group_dirty = true;
2851 }
2852 if !can_retry {
2853 break;
2854 }
2855 }
2856 }
2857 }
2858 if let Some(slug) = &mut self.ui_slug_engine {
2859 slug.sync_and_finalize(device, queue);
2860 }
2861 if self.primitives.len() > self.instance_capacity {
2862 self.instance_capacity = self.primitives.len().next_power_of_two();
2863 self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
2864 self.instance_buf_dirty_all = true;
2865 bind_group_dirty = true;
2866 }
2867 if bind_group_dirty {
2868 self.rebuild_bind_group(device);
2869 }
2870
2871 let slot0 = AlignedViewportSlot {
2872 uniform: ViewportUniform {
2873 size: [pw as f32, ph as f32],
2874 is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
2875 _pad: 0.0,
2876 },
2877 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
2878 };
2879 queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
2880 self.sync_instance_buffer(queue);
2881
2882 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
2883 label: Some("velox_wgpu_dirty_scissor_encoder"),
2884 });
2885 {
2886 let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2887 label: Some("velox_wgpu_dirty_scissor_pass"),
2888 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2889 view: target_view,
2890 depth_slice: None,
2891 resolve_target: None,
2892 ops: wgpu::Operations {
2893 load: wgpu::LoadOp::Load,
2894 store: wgpu::StoreOp::Store,
2895 },
2896 })],
2897 depth_stencil_attachment: None,
2898 occlusion_query_set: None,
2899 timestamp_writes: None,
2900 multiview_mask: None,
2901 });
2902 if !self.uploaded_primitives.is_empty() || !self.ui_slug_segments.is_empty() {
2903 for &d in dirty_regions {
2904 let (sx, sy, sw, sh) =
2905 Self::dirty_region_to_phys_scissor(d, viewport, sf, pw, ph);
2906 if sw > 0 && sh > 0 {
2907 rpass.set_scissor_rect(sx, sy, sw, sh);
2908 if self.ui_slug_segments.is_empty() {
2909 rpass.set_pipeline(&self.pipeline);
2910 rpass.set_bind_group(0, &self.bind_group, &[0]);
2911 rpass.draw(0..6, 0..(self.uploaded_primitives.len() as u32));
2912 } else {
2913 for &(p_start, p_end, s_start, s_end) in &self.ui_slug_segments {
2914 if p_end > p_start {
2915 rpass.set_pipeline(&self.pipeline);
2916 rpass.set_bind_group(0, &self.bind_group, &[0]);
2917 rpass.draw(0..6, p_start..p_end);
2918 }
2919 if s_end > s_start {
2920 if let Some(slug) = &self.ui_slug_engine {
2921 slug.draw_range(&mut rpass, s_start, s_end);
2922 }
2923 }
2924 }
2925 }
2926 }
2927 }
2928 }
2929 }
2930 if let Some((src_tex, dst_tex)) = post_copy {
2932 encoder.copy_texture_to_texture(
2933 src_tex.as_image_copy(),
2934 dst_tex.as_image_copy(),
2935 wgpu::Extent3d {
2936 width: pw,
2937 height: ph,
2938 depth_or_array_layers: 1,
2939 },
2940 );
2941 }
2942 queue.submit([encoder.finish()]);
2943 if let Some(fx) = &mut self.effects {
2944 fx.tick_idle_frame();
2945 }
2946 if let Some(canvas) = &mut self.canvas_engine {
2947 canvas.tick_frame_reclaim();
2948 }
2949 true
2950 }
2951
2952 #[allow(clippy::too_many_arguments)]
2953 fn render_to_view_multi_pass(
2954 &mut self,
2955 device: &wgpu::Device,
2956 queue: &wgpu::Queue,
2957 ops: &[DrawOp<'_>],
2958 viewport: Region,
2959 scale_factor: f32,
2960 target_view: &wgpu::TextureView,
2961 phys_width: u32,
2962 phys_height: u32,
2963 clear_color: wgpu::Color,
2964 dirty_regions: Option<&[Region]>,
2965 ) {
2966 let pw = phys_width.max(1);
2967 let ph = phys_height.max(1);
2968 let sf = scale_factor.clamp(0.5, 4.0);
2969 let use_ttf = crate::display::ttf_atlas::has_system_font();
2970 let is_srgb = self.target_is_srgb;
2971
2972 self.poll_warmed_subengines();
2973 if self.effects.is_none() {
2974 let raw_cache = self.pipeline_cache.as_deref().map(|c| c.wgpu_cache());
2975 self.effects = Some(GpuEffectsEngine::new(
2976 device,
2977 queue,
2978 self.target_format,
2979 raw_cache,
2980 ));
2981 if let Some(c) = &self.pipeline_cache {
2982 c.persist();
2983 }
2984 }
2985
2986 let mut bind_group_dirty = false;
2987 for _attempt in 0..4 {
2988 match self.try_plan_multi_pass(
2989 device,
2990 queue,
2991 ops,
2992 viewport,
2993 sf,
2994 use_ttf,
2995 pw,
2996 ph,
2997 clear_color,
2998 is_srgb,
2999 dirty_regions,
3000 ) {
3001 Ok(()) => break,
3002 Err(need) => {
3003 let (dirty, can_retry) = self.handle_atlas_grow(device, need);
3004 if dirty {
3005 bind_group_dirty = true;
3006 }
3007 if !can_retry {
3008 break;
3009 }
3010 }
3011 }
3012 }
3013
3014 if let Some(slug) = &mut self.ui_slug_engine {
3015 slug.sync_and_finalize(device, queue);
3016 }
3017
3018 if self.primitives.len() > self.instance_capacity {
3019 self.instance_capacity = self.primitives.len().next_power_of_two();
3020 self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
3021 self.instance_buf_dirty_all = true;
3022 bind_group_dirty = true;
3023 }
3024 if self.viewport_slots.len() > self.viewport_capacity {
3025 self.viewport_capacity = self.viewport_slots.len().next_power_of_two();
3026 self.viewport_buf = Self::create_viewport_buffer(device, self.viewport_capacity);
3027 bind_group_dirty = true;
3028 }
3029 if bind_group_dirty {
3030 self.rebuild_bind_group(device);
3031 }
3032
3033 if !self.viewport_slots.is_empty() {
3034 queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&self.viewport_slots));
3035 }
3036 self.sync_instance_buffer(queue);
3037
3038 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
3039 label: Some("velox_wgpu_multi_pass_encoder"),
3040 });
3041 let raw_cache = self.pipeline_cache.as_deref().map(|c| c.wgpu_cache());
3042 let had_canvas = self.canvas_engine.is_some();
3043 if let Some(ref mut fx) = self.effects {
3044 fx.execute_steps(
3045 device,
3046 queue,
3047 &mut encoder,
3048 &self.pipeline,
3049 &self.bind_group,
3050 &self.linear_sampler,
3051 &self.external_textures,
3052 ops,
3053 &mut self.canvas_engine,
3054 &mut self.ui_slug_engine,
3055 raw_cache,
3056 self.target_format,
3057 target_view,
3058 );
3059 }
3060 if !had_canvas && self.canvas_engine.is_some() {
3061 if let Some(c) = &self.pipeline_cache {
3062 c.persist();
3063 }
3064 }
3065 queue.submit([encoder.finish()]);
3066 if let Some(fx) = &mut self.effects {
3067 fx.end_frame_reclaim();
3068 }
3069 if let Some(canvas) = &mut self.canvas_engine {
3070 canvas.tick_frame_reclaim();
3071 }
3072 }
3073
3074 #[allow(clippy::too_many_arguments)]
3075 fn try_plan_multi_pass(
3076 &mut self,
3077 device: &wgpu::Device,
3078 queue: &wgpu::Queue,
3079 ops: &[DrawOp<'_>],
3080 viewport: Region,
3081 sf: f32,
3082 use_ttf: bool,
3083 pw: u32,
3084 ph: u32,
3085 clear_color: wgpu::Color,
3086 is_srgb: bool,
3087 dirty_regions: Option<&[Region]>,
3088 ) -> Result<(), AtlasGrowNeed> {
3089 struct LayerFrame<'a> {
3090 tex_idx: usize,
3091 active_w: u32,
3092 active_h: u32,
3093 origin_x: f32,
3094 origin_y: f32,
3095 viewport_slot: u32,
3096 cleared: bool,
3097 clear_col: wgpu::Color,
3098 batch_start: u32,
3099 spec: Option<&'a LayerSpec<'a>>,
3100 body_phys: Region,
3101 buf_rect: Region,
3102 parent_clip_phys: Region,
3103 }
3104
3105 self.primitives.clear();
3106 self.viewport_slots.clear();
3107 if let Some(slug) = &mut self.ui_slug_engine {
3108 slug.begin_frame();
3109 }
3110 let mut fx = self.effects.take().expect("effects engine initialized");
3111 fx.begin_frame();
3112
3113 let root_idx = fx.pool.acquire(device, pw, ph);
3114 let root_tex_sz = (fx.pool.get(root_idx).width, fx.pool.get(root_idx).height);
3115 let root_vp_slot = 0u32;
3116 self.viewport_slots.push(AlignedViewportSlot {
3117 uniform: ViewportUniform {
3118 size: [root_tex_sz.0 as f32, root_tex_sz.1 as f32],
3119 is_srgb: if is_srgb { 1.0 } else { 0.0 },
3120 _pad: 0.0,
3121 },
3122 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
3123 });
3124
3125 let mut stack: Vec<LayerFrame<'_>> = Vec::with_capacity(8);
3126 stack.push(LayerFrame {
3127 tex_idx: root_idx,
3128 active_w: pw,
3129 active_h: ph,
3130 origin_x: 0.0,
3131 origin_y: 0.0,
3132 viewport_slot: root_vp_slot,
3133 cleared: false,
3134 clear_col: clear_color,
3135 batch_start: 0,
3136 spec: None,
3137 body_phys: Region::new(0, 0, pw as i16, ph as i16),
3138 buf_rect: Region::new(0, 0, pw as i16, ph as i16),
3139 parent_clip_phys: Region::new(0, 0, pw as i16, ph as i16),
3140 });
3141
3142 let flush_top = |stack: &mut [LayerFrame<'_>], fx: &mut GpuEffectsEngine, prim_len: u32| {
3143 let Some(top) = stack.last_mut() else {
3144 return;
3145 };
3146 if !top.cleared || prim_len > top.batch_start {
3147 let clear = if !top.cleared {
3148 top.cleared = true;
3149 Some(top.clear_col)
3150 } else {
3151 None
3152 };
3153 fx.steps.push(GpuPassStep::DrawBatch {
3154 target_idx: top.tex_idx,
3155 clear,
3156 viewport_slot: top.viewport_slot,
3157 prim_start: top.batch_start,
3158 prim_end: prim_len,
3159 });
3160 top.batch_start = prim_len;
3161 }
3162 };
3163
3164 let result: Result<(), AtlasGrowNeed> = (|| {
3165 for (op_idx, op) in ops.iter().enumerate() {
3166 match op.payload {
3167 DrawPayload::PushLayer(spec) => {
3168 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
3169 let parent = stack.last().unwrap();
3170 let parent_idx = parent.tex_idx;
3171 let parent_aw = parent.active_w;
3172 let parent_ah = parent.active_h;
3173 let parent_ox = parent.origin_x;
3174 let parent_oy = parent.origin_y;
3175 let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
3176
3177 let body_phys = snap_bounds_region_scaled(spec.bounds, sf);
3178 let parent_clip_phys = snap_clip_region_scaled(op.clip, sf);
3179
3180 if !spec.backdrop_filter.is_empty() && !body_phys.is_empty() {
3182 let bd = spec.backdrop_filter;
3183 let blur_px = (bd.blur_radius as f32) * sf;
3184 let pad = (blur_px * 2.0).ceil() as i16;
3185 let local_body = Region::new(
3186 body_phys.x.saturating_sub(parent_ox as i16),
3187 body_phys.y.saturating_sub(parent_oy as i16),
3188 body_phys.w,
3189 body_phys.h,
3190 );
3191 let raw_sample = Region::new(
3192 local_body.x.saturating_sub(pad),
3193 local_body.y.saturating_sub(pad),
3194 local_body.w.saturating_add(pad.saturating_mul(2)),
3195 local_body.h.saturating_add(pad.saturating_mul(2)),
3196 );
3197 let (sx, sy, sw, sh) = clamp_rect_u32(raw_sample, parent_aw, parent_ah);
3198 if sw > 0 && sh > 0 {
3199 let bd_cache_key = super::layer_pool::BackdropCacheKey {
3203 sx,
3204 sy,
3205 sw,
3206 sh,
3207 blur_px_q4: (blur_px * 4.0).round().clamp(0.0, u16::MAX as f32) as u16,
3208 is_srgb,
3209 };
3210 let underlay_hash_opt = if stack.len() == 1 && blur_px >= 0.5 {
3211 let sample_logical = Region::new(
3212 ((sx as f32) / sf).floor().max(0.0) as i16,
3213 ((sy as f32) / sf).floor().max(0.0) as i16,
3214 ((sw as f32) / sf).ceil().max(1.0) as i16,
3215 ((sh as f32) / sf).ceil().max(1.0) as i16,
3216 );
3217 compute_backdrop_underlay_hash(&ops[..op_idx], sample_logical, clear_color)
3218 } else {
3219 None
3220 };
3221 let can_reuse_backdrop = underlay_hash_opt.is_some()
3222 && dirty_regions.is_some_and(|dirty| {
3223 !dirty.is_empty()
3224 && !dirty_intersects_phys_rect(dirty, sx, sy, sw, sh, sf)
3225 });
3226 let (bd_blurred, reused_cached_blur) = if can_reuse_backdrop {
3227 let uh = underlay_hash_opt.unwrap();
3228 if let Some(hit_idx) = fx.pool.lookup_backdrop(bd_cache_key, uh) {
3229 (hit_idx, true)
3230 } else {
3231 let bd_raw = fx.pool.acquire(device, sw, sh);
3232 fx.steps.push(GpuPassStep::CopyRect {
3233 src_idx: parent_idx,
3234 src_origin: (sx, sy),
3235 dst_idx: bd_raw,
3236 dst_origin: (0, 0),
3237 size: (sw, sh),
3238 });
3239 let b = fx.plan_kawase_blur(device, bd_raw, sw, sh, blur_px, is_srgb);
3240 if b != bd_raw {
3241 fx.pool.release(bd_raw);
3242 }
3243 (b, false)
3244 }
3245 } else {
3246 let bd_raw = fx.pool.acquire(device, sw, sh);
3247 fx.steps.push(GpuPassStep::CopyRect {
3248 src_idx: parent_idx,
3249 src_origin: (sx, sy),
3250 dst_idx: bd_raw,
3251 dst_origin: (0, 0),
3252 size: (sw, sh),
3253 });
3254 let b = if blur_px >= 0.5 {
3255 let blurred = fx.plan_kawase_blur(device, bd_raw, sw, sh, blur_px, is_srgb);
3256 if blurred != bd_raw {
3257 fx.pool.release(bd_raw);
3258 }
3259 blurred
3260 } else {
3261 bd_raw
3262 };
3263 (b, false)
3264 };
3265
3266 let dst_rect_bd = [
3267 local_body.x as f32,
3268 local_body.y as f32,
3269 local_body.w as f32,
3270 local_body.h as f32,
3271 ];
3272 let clip_rect_bd = [
3273 parent_clip_phys.x as f32 - parent_ox,
3274 parent_clip_phys.y as f32 - parent_oy,
3275 parent_clip_phys.right() as f32 - parent_ox,
3276 parent_clip_phys.bottom() as f32 - parent_oy,
3277 ];
3278 let (snap_idx, snap_ox, snap_oy, snap_tw, snap_th) = fx
3279 .acquire_subrect_snapshot(
3280 device,
3281 parent_idx,
3282 parent_aw,
3283 parent_ah,
3284 dst_rect_bd,
3285 clip_rect_bd,
3286 );
3287
3288 let bd_tex_sz = (fx.pool.get(bd_blurred).width, fx.pool.get(bd_blurred).height);
3289 let mut u = EffectUniform::default();
3290 u.tex_sizes = [
3291 parent_tex_sz.0 as f32,
3292 parent_tex_sz.1 as f32,
3293 bd_tex_sz.0 as f32,
3294 bd_tex_sz.1 as f32,
3295 ];
3296 u.dst_rect = dst_rect_bd;
3297 u.src_rect = [sx as f32, sy as f32, sw as f32, sh as f32];
3298 u.clip_rect = clip_rect_bd;
3299 u.body_rect = u.dst_rect;
3300 u.radii = [
3301 (spec.clip_radii.tl as f32) * sf,
3302 (spec.clip_radii.tr as f32) * sf,
3303 (spec.clip_radii.br as f32) * sf,
3304 (spec.clip_radii.bl as f32) * sf,
3305 ];
3306 u.params = [
3307 (spec.opacity as f32) * (1.0 / 255.0),
3308 0.0,
3309 EFFECT_KIND_BACKDROP,
3310 0.0,
3311 ];
3312 u.set_color_matrix(bd.color_matrix);
3313 u.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
3314 u.flags[2] = (bd.noise_amount as f32) * (1.0 / 255.0) * 0.12;
3315 u.flags[3] = if is_srgb { 1.0 } else { 0.0 };
3316 u.tint = color_to_f32(bd.tint);
3317 u.extra = [snap_ox, snap_oy, snap_tw, snap_th];
3318
3319 let slot = fx.push_slot(u);
3320 let mask_path = spec.clip_path.map(|p| {
3321 (
3322 std::string::String::from(p.as_str()),
3323 local_body.w.max(1) as u32,
3324 local_body.h.max(1) as u32,
3325 )
3326 });
3327 fx.steps.push(GpuPassStep::Effect {
3328 dst_idx: parent_idx,
3329 clear_dst: false,
3330 dont_care_scissor: None,
3331 src_idx: bd_blurred,
3332 dst_snap_idx: snap_idx,
3333 mask_path,
3334 effect_slot: slot,
3335 use_hw_blend: false,
3336 });
3337 if !reused_cached_blur {
3338 if let Some(uh) = underlay_hash_opt {
3339 fx.pool.pin_backdrop(bd_blurred, bd_cache_key, uh);
3340 } else {
3341 fx.pool.release(bd_blurred);
3342 }
3343 } else {
3344 fx.pool.release(bd_blurred);
3345 }
3346 fx.pool.release(snap_idx);
3347 }
3348 }
3349
3350 let (fl, ft, fr, fb) = spec.filter.outset();
3352 let pl = ((fl as f32) * sf).ceil() as i16;
3353 let pt = ((ft as f32) * sf).ceil() as i16;
3354 let pr = ((fr as f32) * sf).ceil() as i16;
3355 let pb = ((fb as f32) * sf).ceil() as i16;
3356 let buf_rect = Region::new(
3357 body_phys.x.saturating_sub(pl),
3358 body_phys.y.saturating_sub(pt),
3359 body_phys.w.saturating_add(pl).saturating_add(pr).max(1),
3360 body_phys.h.saturating_add(pt).saturating_add(pb).max(1),
3361 );
3362 let lw = buf_rect.w.max(1) as u32;
3363 let lh = buf_rect.h.max(1) as u32;
3364 let layer_tex = fx.pool.acquire(device, lw, lh);
3365 let ltex_sz = (fx.pool.get(layer_tex).width, fx.pool.get(layer_tex).height);
3366 let vp_slot = self.viewport_slots.len() as u32;
3367 self.viewport_slots.push(AlignedViewportSlot {
3368 uniform: ViewportUniform {
3369 size: [ltex_sz.0 as f32, ltex_sz.1 as f32],
3370 is_srgb: if is_srgb { 1.0 } else { 0.0 },
3371 _pad: 0.0,
3372 },
3373 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
3374 });
3375
3376 stack.push(LayerFrame {
3377 tex_idx: layer_tex,
3378 active_w: lw,
3379 active_h: lh,
3380 origin_x: buf_rect.x as f32,
3381 origin_y: buf_rect.y as f32,
3382 viewport_slot: vp_slot,
3383 cleared: false,
3384 clear_col: wgpu::Color::TRANSPARENT,
3385 batch_start: self.primitives.len() as u32,
3386 spec: Some(spec),
3387 body_phys,
3388 buf_rect,
3389 parent_clip_phys,
3390 });
3391 }
3392
3393 DrawPayload::PopLayer => {
3394 if stack.len() <= 1 {
3395 continue;
3396 }
3397 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
3398 let layer = stack.pop().unwrap();
3399 if let Some(parent_mut) = stack.last_mut() {
3400 parent_mut.batch_start = self.primitives.len() as u32;
3401 }
3402 let Some(spec) = layer.spec else {
3403 continue;
3404 };
3405 let parent = stack.last().unwrap();
3406 let parent_idx = parent.tex_idx;
3407 let parent_aw = parent.active_w;
3408 let parent_ah = parent.active_h;
3409 let parent_ox = parent.origin_x;
3410 let parent_oy = parent.origin_y;
3411 let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
3412
3413 let local_buf = [
3414 layer.buf_rect.x as f32 - parent_ox,
3415 layer.buf_rect.y as f32 - parent_oy,
3416 layer.buf_rect.w as f32,
3417 layer.buf_rect.h as f32,
3418 ];
3419 let local_body = [
3420 layer.body_phys.x as f32 - parent_ox,
3421 layer.body_phys.y as f32 - parent_oy,
3422 layer.body_phys.w as f32,
3423 layer.body_phys.h as f32,
3424 ];
3425 let clip_f = [
3426 layer.parent_clip_phys.x as f32 - parent_ox,
3427 layer.parent_clip_phys.y as f32 - parent_oy,
3428 layer.parent_clip_phys.right() as f32 - parent_ox,
3429 layer.parent_clip_phys.bottom() as f32 - parent_oy,
3430 ];
3431
3432 let dst_rect = if let Some(mut t) = spec.transform {
3434 if !t.is_identity() {
3435 t.e *= sf;
3436 t.f *= sf;
3437 let cx = local_body[0] + local_body[2] * 0.5;
3438 let cy = local_body[1] + local_body[3] * 0.5;
3439 let xreg = t.centered_at(cx, cy).transform_region(Region::new(
3440 local_buf[0] as i16,
3441 local_buf[1] as i16,
3442 local_buf[2] as i16,
3443 local_buf[3] as i16,
3444 ));
3445 [xreg.x as f32, xreg.y as f32, xreg.w as f32, xreg.h as f32]
3446 } else {
3447 local_buf
3448 }
3449 } else {
3450 local_buf
3451 };
3452
3453 if let Some(ds) = spec.filter.drop_shadow {
3455 if ds.is_active() {
3456 let sh_raw = fx.pool.acquire(device, layer.active_w, layer.active_h);
3457 let lsz = (fx.pool.get(layer.tex_idx).width, fx.pool.get(layer.tex_idx).height);
3458 let sh_sz = (fx.pool.get(sh_raw).width, fx.pool.get(sh_raw).height);
3459 let mut eu = EffectUniform::default();
3460 eu.tex_sizes = [sh_sz.0 as f32, sh_sz.1 as f32, lsz.0 as f32, lsz.1 as f32];
3461 eu.dst_rect = [0.0, 0.0, layer.active_w as f32, layer.active_h as f32];
3462 eu.src_rect = eu.dst_rect;
3463 eu.body_rect = [
3464 (layer.body_phys.x - layer.buf_rect.x) as f32,
3465 (layer.body_phys.y - layer.buf_rect.y) as f32,
3466 layer.body_phys.w as f32,
3467 layer.body_phys.h as f32,
3468 ];
3469 eu.params = [1.0, 0.0, EFFECT_KIND_SHADOW_EXTRACT, 0.0];
3470 eu.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
3471 eu.flags[3] = if is_srgb { 1.0 } else { 0.0 };
3472 eu.tint = color_to_f32(ds.color);
3473 let eslot = fx.push_slot(eu);
3474 let sh_mask = spec.clip_path.map(|p| {
3475 (
3476 std::string::String::from(p.as_str()),
3477 layer.body_phys.w.max(1) as u32,
3478 layer.body_phys.h.max(1) as u32,
3479 )
3480 });
3481 fx.steps.push(GpuPassStep::Effect {
3482 dst_idx: sh_raw,
3483 clear_dst: true,
3484 dont_care_scissor: None,
3485 src_idx: layer.tex_idx,
3486 dst_snap_idx: layer.tex_idx,
3487 mask_path: sh_mask,
3488 effect_slot: eslot,
3489 use_hw_blend: false,
3490 });
3491
3492 let ds_blur = (ds.blur as f32) * sf;
3493 let sh_final = if ds_blur >= 0.5 {
3494 let b = fx.plan_kawase_blur(
3495 device,
3496 sh_raw,
3497 layer.active_w,
3498 layer.active_h,
3499 ds_blur,
3500 is_srgb,
3501 );
3502 if b != sh_raw {
3503 fx.pool.release(sh_raw);
3504 }
3505 b
3506 } else {
3507 sh_raw
3508 };
3509
3510 let sh_tex_sz = (fx.pool.get(sh_final).width, fx.pool.get(sh_final).height);
3511 let ox = (ds.offset_x as f32) * sf;
3512 let oy = (ds.offset_y as f32) * sf;
3513 let sh_dst_rect = [
3514 dst_rect[0] + ox,
3515 dst_rect[1] + oy,
3516 dst_rect[2],
3517 dst_rect[3],
3518 ];
3519 let sh_hw_blend = spec.blend_mode.is_normal();
3520 let (sh_snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if sh_hw_blend {
3521 (None, 0.0, 0.0, 1.0, 1.0)
3522 } else {
3523 let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
3524 device,
3525 parent_idx,
3526 parent_aw,
3527 parent_ah,
3528 sh_dst_rect,
3529 clip_f,
3530 );
3531 (Some(sidx), sx0, sy0, stw, sth)
3532 };
3533
3534 let mut cu = EffectUniform::default();
3535 cu.tex_sizes = [
3536 parent_tex_sz.0 as f32,
3537 parent_tex_sz.1 as f32,
3538 sh_tex_sz.0 as f32,
3539 sh_tex_sz.1 as f32,
3540 ];
3541 cu.dst_rect = sh_dst_rect;
3542 cu.src_rect = local_buf;
3543 cu.clip_rect = clip_f;
3544 cu.body_rect = local_body;
3545 cu.params = [
3546 (spec.opacity as f32) * (1.0 / 255.0),
3547 if sh_hw_blend {
3548 -1.0
3549 } else {
3550 spec.blend_mode as u8 as f32
3551 },
3552 EFFECT_KIND_COMPOSITE,
3553 0.0,
3554 ];
3555 cu.set_color_matrix(None);
3556 cu.set_transform(spec.transform, sf);
3557 cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
3558 cu.extra[0] += ox;
3559 cu.extra[1] += oy;
3560 cu.extra[2] = snap_tw;
3561 cu.extra[3] = snap_th;
3562 let cslot = fx.push_slot(cu);
3563 fx.steps.push(GpuPassStep::Effect {
3564 dst_idx: parent_idx,
3565 clear_dst: false,
3566 dont_care_scissor: None,
3567 src_idx: sh_final,
3568 dst_snap_idx: sh_snap_opt.unwrap_or(sh_final),
3569 mask_path: None,
3570 effect_slot: cslot,
3571 use_hw_blend: sh_hw_blend,
3572 });
3573 fx.pool.release(sh_final);
3574 if let Some(sidx) = sh_snap_opt {
3575 fx.pool.release(sidx);
3576 }
3577 }
3578 }
3579
3580 let blur_px = (spec.filter.blur_radius as f32) * sf;
3582 let src_final = if blur_px >= 0.5 {
3583 let b = fx.plan_kawase_blur(
3584 device,
3585 layer.tex_idx,
3586 layer.active_w,
3587 layer.active_h,
3588 blur_px,
3589 is_srgb,
3590 );
3591 if b != layer.tex_idx {
3592 fx.pool.release(layer.tex_idx);
3593 }
3594 b
3595 } else {
3596 layer.tex_idx
3597 };
3598
3599 let use_hw_blend = spec.blend_mode.is_normal();
3601 let (snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if use_hw_blend {
3602 (None, 0.0, 0.0, 1.0, 1.0)
3603 } else {
3604 let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
3605 device,
3606 parent_idx,
3607 parent_aw,
3608 parent_ah,
3609 dst_rect,
3610 clip_f,
3611 );
3612 (Some(sidx), sx0, sy0, stw, sth)
3613 };
3614 let src_tex_sz = (fx.pool.get(src_final).width, fx.pool.get(src_final).height);
3615
3616 let mut cu = EffectUniform::default();
3617 cu.tex_sizes = [
3618 parent_tex_sz.0 as f32,
3619 parent_tex_sz.1 as f32,
3620 src_tex_sz.0 as f32,
3621 src_tex_sz.1 as f32,
3622 ];
3623 cu.dst_rect = dst_rect;
3624 cu.src_rect = local_buf;
3625 cu.clip_rect = clip_f;
3626 cu.body_rect = local_body;
3627 cu.radii = [
3628 (spec.clip_radii.tl as f32) * sf,
3629 (spec.clip_radii.tr as f32) * sf,
3630 (spec.clip_radii.br as f32) * sf,
3631 (spec.clip_radii.bl as f32) * sf,
3632 ];
3633 cu.params = [
3634 (spec.opacity as f32) * (1.0 / 255.0),
3635 if use_hw_blend {
3636 -1.0
3637 } else {
3638 spec.blend_mode as u8 as f32
3639 },
3640 EFFECT_KIND_COMPOSITE,
3641 0.0,
3642 ];
3643 cu.set_color_matrix(spec.filter.color_matrix);
3644 cu.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
3645 cu.flags[3] = if is_srgb { 1.0 } else { 0.0 };
3646 cu.set_transform(spec.transform, sf);
3647 cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
3648 cu.extra[2] = snap_tw;
3649 cu.extra[3] = snap_th;
3650 let cslot = fx.push_slot(cu);
3651
3652 let mask_path = spec.clip_path.map(|p| {
3653 (
3654 std::string::String::from(p.as_str()),
3655 layer.body_phys.w.max(1) as u32,
3656 layer.body_phys.h.max(1) as u32,
3657 )
3658 });
3659 fx.steps.push(GpuPassStep::Effect {
3660 dst_idx: parent_idx,
3661 clear_dst: false,
3662 dont_care_scissor: None,
3663 src_idx: src_final,
3664 dst_snap_idx: snap_opt.unwrap_or(src_final),
3665 mask_path,
3666 effect_slot: cslot,
3667 use_hw_blend,
3668 });
3669 fx.pool.release(src_final);
3670 if let Some(sidx) = snap_opt {
3671 fx.pool.release(sidx);
3672 }
3673 }
3674
3675 DrawPayload::StyledQuad(sq) if !sq.blend_mode.is_normal() => {
3677 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
3678 let parent = stack.last().unwrap();
3679 let parent_idx = parent.tex_idx;
3680 let parent_aw = parent.active_w;
3681 let parent_ah = parent.active_h;
3682 let parent_ox = parent.origin_x;
3683 let parent_oy = parent.origin_y;
3684 let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
3685
3686 let body_phys = snap_bounds_region_scaled(op.bounds, sf);
3687 let buf_rect = if let Some(mut t) = sq.transform {
3688 if !t.is_identity() {
3689 t.e *= sf;
3690 t.f *= sf;
3691 let cx = body_phys.x as f32 + body_phys.w as f32 * 0.5;
3692 let cy = body_phys.y as f32 + body_phys.h as f32 * 0.5;
3693 t.centered_at(cx, cy).transform_region(body_phys)
3694 } else {
3695 body_phys
3696 }
3697 } else {
3698 body_phys
3699 };
3700 let lw = buf_rect.w.max(1) as u32;
3701 let lh = buf_rect.h.max(1) as u32;
3702 let tmp_tex = fx.pool.acquire(device, lw, lh);
3703 let tmp_sz = (fx.pool.get(tmp_tex).width, fx.pool.get(tmp_tex).height);
3704 let vp_slot = self.viewport_slots.len() as u32;
3705 self.viewport_slots.push(AlignedViewportSlot {
3706 uniform: ViewportUniform {
3707 size: [tmp_sz.0 as f32, tmp_sz.1 as f32],
3708 is_srgb: if is_srgb { 1.0 } else { 0.0 },
3709 _pad: 0.0,
3710 },
3711 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
3712 });
3713
3714 let normal_sq = StyledQuad {
3715 blend_mode: BlendMode::SrcOver,
3716 ..*sq
3717 };
3718 let tmp_op = DrawOp {
3719 payload: DrawPayload::StyledQuad(&normal_sq),
3720 ..*op
3721 };
3722 let pstart = self.primitives.len() as u32;
3723 let slug_before = self
3724 .ui_slug_engine
3725 .as_ref()
3726 .map(|s| s.instance_count())
3727 .unwrap_or(0);
3728 self.encode_single_op(
3729 device,
3730 queue,
3731 &tmp_op,
3732 op.clip,
3733 viewport,
3734 sf,
3735 use_ttf,
3736 buf_rect.x as f32,
3737 buf_rect.y as f32,
3738 tmp_sz.0,
3739 tmp_sz.1,
3740 )?;
3741 let pend = self.primitives.len() as u32;
3742 let slug_after = self
3743 .ui_slug_engine
3744 .as_ref()
3745 .map(|s| s.instance_count())
3746 .unwrap_or(0);
3747 fx.steps.push(GpuPassStep::DrawBatch {
3748 target_idx: tmp_tex,
3749 clear: Some(wgpu::Color::TRANSPARENT),
3750 viewport_slot: vp_slot,
3751 prim_start: pstart,
3752 prim_end: pend,
3753 });
3754 if slug_after > slug_before {
3755 fx.steps.push(GpuPassStep::DrawSlugBatch {
3756 target_idx: tmp_tex,
3757 clear: None,
3758 slug_start: slug_before,
3759 slug_end: slug_after,
3760 });
3761 }
3762 if let Some(top) = stack.last_mut() {
3763 top.batch_start = pend;
3764 }
3765
3766 let clip_phys = snap_clip_region_scaled(op.clip, sf);
3767 let local_buf = [
3768 buf_rect.x as f32 - parent_ox,
3769 buf_rect.y as f32 - parent_oy,
3770 buf_rect.w as f32,
3771 buf_rect.h as f32,
3772 ];
3773 let clip_f = [
3774 clip_phys.x as f32 - parent_ox,
3775 clip_phys.y as f32 - parent_oy,
3776 clip_phys.right() as f32 - parent_ox,
3777 clip_phys.bottom() as f32 - parent_oy,
3778 ];
3779 let (snap_idx, snap_ox, snap_oy, snap_tw, snap_th) = fx
3780 .acquire_subrect_snapshot(
3781 device,
3782 parent_idx,
3783 parent_aw,
3784 parent_ah,
3785 local_buf,
3786 clip_f,
3787 );
3788 let mut cu = EffectUniform::default();
3789 cu.tex_sizes = [
3790 parent_tex_sz.0 as f32,
3791 parent_tex_sz.1 as f32,
3792 tmp_sz.0 as f32,
3793 tmp_sz.1 as f32,
3794 ];
3795 cu.dst_rect = local_buf;
3796 cu.src_rect = local_buf;
3797 cu.clip_rect = clip_f;
3798 cu.body_rect = local_buf;
3799 cu.params = [1.0, sq.blend_mode as u8 as f32, EFFECT_KIND_COMPOSITE, 0.0];
3800 cu.set_color_matrix(None);
3801 cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
3802 cu.inv_xform = [1.0, 0.0, 0.0, 1.0];
3803 cu.extra = [0.0, 0.0, snap_tw, snap_th];
3804 let cslot = fx.push_slot(cu);
3805 fx.steps.push(GpuPassStep::Effect {
3806 dst_idx: parent_idx,
3807 clear_dst: false,
3808 dont_care_scissor: None,
3809 src_idx: tmp_tex,
3810 dst_snap_idx: snap_idx,
3811 mask_path: None,
3812 effect_slot: cslot,
3813 use_hw_blend: false,
3814 });
3815 fx.pool.release(tmp_tex);
3816 fx.pool.release(snap_idx);
3817 }
3818
3819 DrawPayload::ExternalTexture(ext) => {
3821 let raw_clip = viewport.intersect(op.clip).intersect(op.bounds);
3822 if raw_clip.is_empty() {
3823 continue;
3824 }
3825 if self.external_textures.contains_key(&ext.id) {
3826 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
3827 let parent = stack.last().unwrap();
3828 let parent_idx = parent.tex_idx;
3829 let parent_aw = parent.active_w;
3830 let parent_ah = parent.active_h;
3831 let parent_ox = parent.origin_x;
3832 let parent_oy = parent.origin_y;
3833 let parent_tex_sz =
3834 (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
3835
3836 let body_phys = snap_bounds_region_scaled(op.bounds, sf);
3837 let clip_phys = snap_clip_region_scaled(raw_clip, sf);
3838 let local_body = [
3839 body_phys.x as f32 - parent_ox,
3840 body_phys.y as f32 - parent_oy,
3841 body_phys.w as f32,
3842 body_phys.h as f32,
3843 ];
3844 let clip_f = [
3845 clip_phys.x as f32 - parent_ox,
3846 clip_phys.y as f32 - parent_oy,
3847 clip_phys.right() as f32 - parent_ox,
3848 clip_phys.bottom() as f32 - parent_oy,
3849 ];
3850
3851 let use_hw_blend = ext.blend_mode.is_normal();
3852 let (snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if use_hw_blend {
3853 (None, 0.0, 0.0, 1.0, 1.0)
3854 } else {
3855 let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
3856 device,
3857 parent_idx,
3858 parent_aw,
3859 parent_ah,
3860 local_body,
3861 clip_f,
3862 );
3863 (Some(sidx), sx0, sy0, stw, sth)
3864 };
3865
3866 let mut eu = EffectUniform::default();
3867 eu.tex_sizes = [
3868 parent_tex_sz.0 as f32,
3869 parent_tex_sz.1 as f32,
3870 1.0,
3871 1.0,
3872 ];
3873 eu.dst_rect = local_body;
3874 eu.src_rect = ext.uv_rect;
3875 eu.clip_rect = clip_f;
3876 eu.body_rect = local_body;
3877 eu.radii = [
3878 (ext.radii.tl as f32) * sf,
3879 (ext.radii.tr as f32) * sf,
3880 (ext.radii.br as f32) * sf,
3881 (ext.radii.bl as f32) * sf,
3882 ];
3883 eu.params = [
3884 (ext.opacity as f32) * (1.0 / 255.0),
3885 if use_hw_blend {
3886 -1.0
3887 } else {
3888 ext.blend_mode as u8 as f32
3889 },
3890 EFFECT_KIND_EXTERNAL_TEX,
3891 0.0,
3892 ];
3893 eu.flags = [
3894 if ext.premultiplied { 1.0 } else { 0.0 },
3895 0.0,
3896 0.0,
3897 if is_srgb { 1.0 } else { 0.0 },
3898 ];
3899 eu.inv_xform = [1.0, 0.0, 0.0, 1.0];
3900 eu.extra = [snap_ox, snap_oy, snap_tw, snap_th];
3901 let eslot = fx.push_slot(eu);
3902
3903 fx.steps.push(GpuPassStep::DrawExternal {
3904 dst_idx: parent_idx,
3905 dst_snap_idx: snap_opt.unwrap_or(root_idx),
3906 tex_id: ext.id,
3907 effect_slot: eslot,
3908 use_hw_blend,
3909 });
3910 if let Some(sidx) = snap_opt {
3911 fx.pool.release(sidx);
3912 }
3913 } else if ext.fallback_bg.a() > 0 {
3914 let fallback_sq = StyledQuad {
3915 paint: Paint::Solid(ext.fallback_bg),
3916 border_color: Color::TRANSPARENT,
3917 border_width: 0,
3918 radii: ext.radii,
3919 opacity: ext.opacity,
3920 blend_mode: BlendMode::SrcOver,
3921 transform: None,
3922 };
3923 let tmp_op = DrawOp {
3924 payload: DrawPayload::StyledQuad(&fallback_sq),
3925 ..*op
3926 };
3927 let (ox, oy, tw, th) = {
3928 let top = stack.last().unwrap();
3929 let t = fx.pool.get(top.tex_idx);
3930 (top.origin_x, top.origin_y, t.width, t.height)
3931 };
3932 self.encode_single_op(
3933 device, queue, &tmp_op, raw_clip, viewport, sf, use_ttf, ox, oy, tw, th,
3934 )?;
3935 }
3936 }
3937
3938 DrawPayload::SceneCanvas(spec) => {
3940 let raw_clip = viewport.intersect(op.clip).intersect(op.bounds);
3941 if raw_clip.is_empty() {
3942 continue;
3943 }
3944 let (parent_idx, ox, oy) = {
3945 let top = stack.last().unwrap();
3946 (top.tex_idx, top.origin_x, top.origin_y)
3947 };
3948 let raw_b = snap_bounds(op.bounds, sf);
3949 let raw_c = snap_clip(raw_clip, sf);
3950 let bounds_phys = [raw_b[0] - ox, raw_b[1] - oy, raw_b[2], raw_b[3]];
3951 let clip_phys = [raw_c[0] - ox, raw_c[1] - oy, raw_c[2] - ox, raw_c[3] - oy];
3952 let raw_sc = snap_clip_region_scaled(raw_clip, sf);
3953 let scissor = Region::new(
3954 raw_sc.x.saturating_sub(ox.round() as i16),
3955 raw_sc.y.saturating_sub(oy.round() as i16),
3956 raw_sc.w,
3957 raw_sc.h,
3958 );
3959 if spec.bg.a() > 0 && spec.opacity > 0 {
3960 let bg = spec.bg.scale_alpha(spec.opacity);
3961 self.primitives.push(make_quad_primitive(
3962 bounds_phys,
3963 clip_phys,
3964 (op.clip_radius as f32) * sf,
3965 0.0,
3966 0.0,
3967 false,
3968 bg,
3969 Color::TRANSPARENT,
3970 Color::TRANSPARENT,
3971 ));
3972 }
3973 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
3974 fx.steps.push(GpuPassStep::DrawSceneCanvas {
3975 target_idx: parent_idx,
3976 op_idx,
3977 bounds_phys,
3978 clip_phys,
3979 scissor,
3980 sf,
3981 is_srgb,
3982 });
3983 self.encode_canvas_overlay_primitives(
3984 queue,
3985 spec,
3986 bounds_phys,
3987 clip_phys,
3988 (op.clip_radius as f32) * sf,
3989 sf,
3990 )?;
3991 }
3992
3993 _ => {
3994 let raw_clip = match op.payload {
3995 DrawPayload::StyledQuad(sq) if sq.transform.is_some() => {
3996 viewport.intersect(op.clip)
3997 }
3998 _ => viewport.intersect(op.clip).intersect(op.bounds),
3999 };
4000 if raw_clip.is_empty() {
4001 continue;
4002 }
4003 let (ox, oy, tw, th) = {
4004 let top = stack.last().unwrap();
4005 let t = fx.pool.get(top.tex_idx);
4006 (top.origin_x, top.origin_y, t.width, t.height)
4007 };
4008 let prim_before = self.primitives.len() as u32;
4009 let slug_before = self
4010 .ui_slug_engine
4011 .as_ref()
4012 .map(|s| s.instance_count())
4013 .unwrap_or(0);
4014 self.encode_single_op(
4015 device, queue, op, raw_clip, viewport, sf, use_ttf, ox, oy, tw, th,
4016 )?;
4017 let slug_after = self
4018 .ui_slug_engine
4019 .as_ref()
4020 .map(|s| s.instance_count())
4021 .unwrap_or(0);
4022 if slug_after > slug_before {
4023 flush_top(&mut stack, &mut fx, prim_before);
4024 let top = stack.last_mut().unwrap();
4025 let clear = if !top.cleared {
4026 top.cleared = true;
4027 Some(top.clear_col)
4028 } else {
4029 None
4030 };
4031 fx.steps.push(GpuPassStep::DrawSlugBatch {
4032 target_idx: top.tex_idx,
4033 clear,
4034 slug_start: slug_before,
4035 slug_end: slug_after,
4036 });
4037 }
4038 }
4039 }
4040 }
4041
4042 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
4044 let mut blit_u = EffectUniform::default();
4045 blit_u.tex_sizes = [pw as f32, ph as f32, root_tex_sz.0 as f32, root_tex_sz.1 as f32];
4046 blit_u.dst_rect = [0.0, 0.0, pw as f32, ph as f32];
4047 blit_u.src_rect = [0.0, 0.0, pw as f32, ph as f32];
4048 blit_u.params = [1.0, 0.0, EFFECT_KIND_BLIT, 0.0];
4049 let blit_slot = fx.push_slot(blit_u);
4050 fx.steps.push(GpuPassStep::BlitToTarget {
4051 src_idx: root_idx,
4052 effect_slot: blit_slot,
4053 });
4054 Ok(())
4055 })();
4056
4057 self.effects = Some(fx);
4058 result
4059 }
4060
4061 #[allow(clippy::too_many_arguments)]
4065 fn render_to_view_with_scene_canvas(
4066 &mut self,
4067 device: &wgpu::Device,
4068 queue: &wgpu::Queue,
4069 ops: &[DrawOp<'_>],
4070 viewport: Region,
4071 scale_factor: f32,
4072 target_view: &wgpu::TextureView,
4073 phys_width: u32,
4074 phys_height: u32,
4075 clear_color: wgpu::Color,
4076 ) {
4077 enum InterleavedStep {
4078 UiBatch(u32, u32),
4079 UiSlugBatch(u32, u32),
4080 Canvas {
4081 op_idx: usize,
4082 bounds_phys: [f32; 4],
4083 clip_phys: [f32; 4],
4084 scissor: Region,
4085 },
4086 }
4087
4088 let sf = scale_factor.clamp(0.5, 4.0);
4089 let pw = phys_width.max(1);
4090 let ph = phys_height.max(1);
4091 let use_ttf = crate::display::ttf_atlas::has_system_font();
4092 let mut steps: Vec<InterleavedStep> = Vec::with_capacity(8);
4093
4094 let mut bind_group_dirty = false;
4095 for _attempt in 0..4 {
4096 self.primitives.clear();
4097 steps.clear();
4098 if let Some(slug) = &mut self.ui_slug_engine {
4099 slug.begin_frame();
4100 }
4101 let mut batch_start = 0u32;
4102 let mut err_need: Option<AtlasGrowNeed> = None;
4103
4104 for (op_idx, op) in ops.iter().enumerate() {
4105 let raw_clip = match op.payload {
4106 DrawPayload::StyledQuad(sq) if sq.transform.is_some() => {
4107 viewport.intersect(op.clip)
4108 }
4109 _ => viewport.intersect(op.clip).intersect(op.bounds),
4110 };
4111 if raw_clip.is_empty() {
4112 continue;
4113 }
4114 if let DrawPayload::SceneCanvas(spec) = op.payload {
4115 let bounds_phys = snap_bounds(op.bounds, sf);
4116 let clip_phys = snap_clip(raw_clip, sf);
4117 let scissor = snap_clip_region_scaled(raw_clip, sf);
4118
4119 if spec.bg.a() > 0 && spec.opacity > 0 {
4121 let bg = spec.bg.scale_alpha(spec.opacity);
4122 self.primitives.push(make_quad_primitive(
4123 bounds_phys,
4124 clip_phys,
4125 (op.clip_radius as f32) * sf,
4126 0.0,
4127 0.0,
4128 false,
4129 bg,
4130 Color::TRANSPARENT,
4131 Color::TRANSPARENT,
4132 ));
4133 }
4134 let batch_end = self.primitives.len() as u32;
4135 if batch_end > batch_start {
4136 steps.push(InterleavedStep::UiBatch(batch_start, batch_end));
4137 batch_start = batch_end;
4138 }
4139
4140 steps.push(InterleavedStep::Canvas {
4142 op_idx,
4143 bounds_phys,
4144 clip_phys,
4145 scissor,
4146 });
4147
4148 if let Err(need) = self.encode_canvas_overlay_primitives(
4150 queue,
4151 spec,
4152 bounds_phys,
4153 clip_phys,
4154 (op.clip_radius as f32) * sf,
4155 sf,
4156 ) {
4157 err_need = Some(need);
4158 break;
4159 }
4160 } else {
4161 let prim_before = self.primitives.len() as u32;
4162 let slug_before = self
4163 .ui_slug_engine
4164 .as_ref()
4165 .map(|s| s.instance_count())
4166 .unwrap_or(0);
4167 if let Err(need) = self.encode_single_op(
4168 device, queue, op, raw_clip, viewport, sf, use_ttf, 0.0, 0.0, pw, ph,
4169 ) {
4170 err_need = Some(need);
4171 break;
4172 }
4173 let slug_after = self
4174 .ui_slug_engine
4175 .as_ref()
4176 .map(|s| s.instance_count())
4177 .unwrap_or(0);
4178 if slug_after > slug_before {
4179 if prim_before > batch_start {
4180 steps.push(InterleavedStep::UiBatch(batch_start, prim_before));
4181 }
4182 steps.push(InterleavedStep::UiSlugBatch(slug_before, slug_after));
4183 batch_start = prim_before;
4184 }
4185 }
4186 }
4187
4188 if let Some(need) = err_need {
4189 let (dirty, can_retry) = self.handle_atlas_grow(device, need);
4190 if dirty {
4191 bind_group_dirty = true;
4192 }
4193 if !can_retry {
4194 break;
4195 }
4196 } else {
4197 let final_end = self.primitives.len() as u32;
4198 if final_end > batch_start {
4199 steps.push(InterleavedStep::UiBatch(batch_start, final_end));
4200 }
4201 break;
4202 }
4203 }
4204 if let Some(slug) = &mut self.ui_slug_engine {
4205 slug.sync_and_finalize(device, queue);
4206 }
4207
4208 if self.primitives.len() > self.instance_capacity {
4209 self.instance_capacity = self.primitives.len().next_power_of_two();
4210 self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
4211 self.instance_buf_dirty_all = true;
4212 bind_group_dirty = true;
4213 }
4214 if bind_group_dirty {
4215 self.rebuild_bind_group(device);
4216 }
4217
4218 let slot0 = AlignedViewportSlot {
4219 uniform: ViewportUniform {
4220 size: [pw as f32, ph as f32],
4221 is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
4222 _pad: 0.0,
4223 },
4224 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
4225 };
4226 queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
4227 self.sync_instance_buffer(queue);
4228
4229 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
4230 label: Some("velox_wgpu_scene_canvas_encoder"),
4231 });
4232
4233 let mut cleared = false;
4234 let is_srgb = self.target_is_srgb;
4235 self.poll_warmed_subengines();
4236 let raw_cache = self.pipeline_cache.as_deref().map(|c| c.wgpu_cache());
4237 let had_canvas = self.canvas_engine.is_some();
4238 let mut canvas_eng = self.canvas_engine.take().unwrap_or_else(|| {
4239 super::canvas_pipeline::CanvasGpuEngine::new(device, self.target_format, raw_cache)
4240 });
4241 if !had_canvas {
4242 if let Some(c) = &self.pipeline_cache {
4243 c.persist();
4244 }
4245 }
4246
4247 for step in &steps {
4248 match *step {
4249 InterleavedStep::UiBatch(start, end) => {
4250 let load = if !cleared {
4251 cleared = true;
4252 wgpu::LoadOp::Clear(clear_color)
4253 } else {
4254 wgpu::LoadOp::Load
4255 };
4256 let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4257 label: Some("velox_canvas_ui_batch"),
4258 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
4259 view: target_view,
4260 depth_slice: None,
4261 resolve_target: None,
4262 ops: wgpu::Operations {
4263 load,
4264 store: wgpu::StoreOp::Store,
4265 },
4266 })],
4267 depth_stencil_attachment: None,
4268 occlusion_query_set: None,
4269 timestamp_writes: None,
4270 multiview_mask: None,
4271 });
4272 if end > start {
4273 rpass.set_pipeline(&self.pipeline);
4274 rpass.set_bind_group(0, &self.bind_group, &[0]);
4275 rpass.draw(0..6, start..end);
4276 }
4277 }
4278 InterleavedStep::UiSlugBatch(start, end) => {
4279 let load = if !cleared {
4280 cleared = true;
4281 wgpu::LoadOp::Clear(clear_color)
4282 } else {
4283 wgpu::LoadOp::Load
4284 };
4285 let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4286 label: Some("velox_canvas_ui_slug_batch"),
4287 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
4288 view: target_view,
4289 depth_slice: None,
4290 resolve_target: None,
4291 ops: wgpu::Operations {
4292 load,
4293 store: wgpu::StoreOp::Store,
4294 },
4295 })],
4296 depth_stencil_attachment: None,
4297 occlusion_query_set: None,
4298 timestamp_writes: None,
4299 multiview_mask: None,
4300 });
4301 if let Some(slug) = &self.ui_slug_engine {
4302 slug.draw_range(&mut rpass, start, end);
4303 }
4304 }
4305 InterleavedStep::Canvas {
4306 op_idx,
4307 bounds_phys,
4308 clip_phys,
4309 scissor,
4310 } => {
4311 if !cleared {
4312 cleared = true;
4313 let _clear_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
4314 label: Some("velox_canvas_clear"),
4315 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
4316 view: target_view,
4317 depth_slice: None,
4318 resolve_target: None,
4319 ops: wgpu::Operations {
4320 load: wgpu::LoadOp::Clear(clear_color),
4321 store: wgpu::StoreOp::Store,
4322 },
4323 })],
4324 depth_stencil_attachment: None,
4325 occlusion_query_set: None,
4326 timestamp_writes: None,
4327 multiview_mask: None,
4328 });
4329 }
4330 if let DrawPayload::SceneCanvas(spec) = ops[op_idx].payload {
4331 let slug_eng = self.ui_slug_engine.get_or_insert_with(|| {
4332 super::slug_glyph::SlugTextEngine::new(
4333 device,
4334 self.target_format,
4335 raw_cache,
4336 )
4337 });
4338 canvas_eng.render_canvas(
4339 device,
4340 queue,
4341 &mut encoder,
4342 target_view,
4343 pw,
4344 ph,
4345 bounds_phys,
4346 clip_phys,
4347 scissor,
4348 sf,
4349 is_srgb,
4350 spec,
4351 slug_eng,
4352 );
4353 }
4354 }
4355 }
4356 }
4357
4358 canvas_eng.tick_frame_reclaim();
4359 self.canvas_engine = Some(canvas_eng);
4360 queue.submit([encoder.finish()]);
4361 if let Some(fx) = &mut self.effects {
4362 fx.tick_idle_frame();
4363 }
4364 }
4365
4366 fn encode_canvas_overlay_primitives(
4368 &mut self,
4369 queue: &wgpu::Queue,
4370 spec: &crate::canvas_scene::SceneCanvasSpec<'_>,
4371 bounds_phys: [f32; 4],
4372 clip_phys: [f32; 4],
4373 clip_radius_px: f32,
4374 sf: f32,
4375 ) -> Result<(), AtlasGrowNeed> {
4376 let vp_zoom = spec.viewport.zoom * sf;
4377 let vp_ox = bounds_phys[0] + spec.viewport.offset_x * sf;
4378 let vp_oy = bounds_phys[1] + spec.viewport.offset_y * sf;
4379
4380 if !crate::display::ttf_atlas::has_system_font() {
4383 for lbl in spec.labels {
4384 if lbl.text.is_empty() {
4385 continue;
4386 }
4387 let target_px = (lbl.font_px * sf).clamp(6.0, 48.0);
4388 let col_f32 = color_to_f32(lbl.color.scale_alpha(spec.opacity));
4389 let center_x = lbl.wx * vp_zoom + vp_ox;
4390 let center_y = lbl.wy * vp_zoom + vp_oy;
4391
4392 let use_fast_lock = spec.zooming || lbl.text.is_ascii();
4394 if use_fast_lock && lbl.text.is_ascii() {
4395 let (large_32, base_px, q4_exact) = if spec.zooming {
4396 let large = target_px > 20.0;
4397 (large, if large { 32.0 } else { 16.0 }, 0u16)
4398 } else {
4399 let q4 = (target_px * 4.0).round().clamp(24.0, 192.0) as u16;
4400 (false, target_px, q4)
4401 };
4402 let ratio = if spec.zooming {
4403 target_px / base_px
4404 } else {
4405 1.0
4406 };
4407 let mut total_adv = 0.0f32;
4408 let mut cached_entries: [Option<super::atlas::GlyphAtlasEntry>; 16] = [None; 16];
4409 let bytes = lbl.text.as_bytes();
4410 let count = bytes.len().min(16);
4411 for i in 0..count {
4412 let b = bytes[i];
4413 let entry = if spec.zooming {
4414 self.glyph_atlas.get_ascii_fast(queue, b, large_32)
4415 } else {
4416 self.glyph_atlas.get_or_insert(queue, b as char, q4_exact, true)
4417 };
4418 let Some(e) = entry else {
4419 return Err(AtlasGrowNeed {
4420 glyph_full: true,
4421 sprite_need: None,
4422 ramp_full: false,
4423 });
4424 };
4425 total_adv += (e.advance.max(4) as f32) * ratio;
4426 cached_entries[i] = Some(e);
4427 }
4428 let mut pen_x = center_x - total_adv * 0.5;
4429 let baseline_y = center_y + target_px * 0.34;
4430 for i in 0..count {
4431 if let Some(e) = cached_entries[i] {
4432 if e.width > 0 && e.height > 0 {
4433 let gw = (e.width as f32) * ratio;
4434 let gh = (e.height as f32) * ratio;
4435 let gx = pen_x + (e.xmin as f32) * ratio;
4436 let gy = baseline_y - gh - (e.ymin as f32) * ratio;
4437 if gx + gw >= clip_phys[0]
4438 && gx <= clip_phys[2]
4439 && gy + gh >= clip_phys[1]
4440 && gy <= clip_phys[3]
4441 {
4442 self.primitives.push(GpuPrimitive {
4443 bounds: [gx, gy, gw, gh],
4444 clip: clip_phys,
4445 uv: e.uv,
4446 color0: col_f32,
4447 color1: [0.0; 4],
4448 border_color: [0.0; 4],
4449 params: [0.0, 0.0, KIND_GLYPH, 0.0],
4450 extra: [clip_radius_px, 0.0, 0.0, 0.0],
4451 radii: [0.0; 4],
4452 grad_a: [0.0; 4],
4453 grad_b: [0.0; 4],
4454 xform: IDENTITY_XFORM,
4455 });
4456 }
4457 }
4458 pen_x += (e.advance.max(4) as f32) * ratio;
4459 }
4460 }
4461 }
4462 }
4463 }
4464
4465 if let Some([mx0, my0, mx1, my1]) = spec.marquee {
4467 let x0 = bounds_phys[0] + mx0.min(mx1) * sf;
4468 let y0 = bounds_phys[1] + my0.min(my1) * sf;
4469 let w = (mx1 - mx0).abs() * sf;
4470 let h = (my1 - my0).abs() * sf;
4471 if w > 1.0 && h > 1.0 {
4472 self.primitives.push(make_quad_primitive(
4473 [x0, y0, w, h],
4474 clip_phys,
4475 clip_radius_px,
4476 2.0 * sf,
4477 1.5 * sf,
4478 false,
4479 spec.marquee_color.scale_alpha(52),
4480 Color::TRANSPARENT,
4481 spec.marquee_color.scale_alpha(220),
4482 ));
4483 }
4484 }
4485 Ok(())
4486 }
4487}