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,
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#[repr(C)]
73#[derive(Copy, Clone, Debug)]
74struct AlignedViewportSlot {
75 uniform: ViewportUniform,
76 _pad: [u8; 256 - core::mem::size_of::<ViewportUniform>()],
77}
78
79impl Default for AlignedViewportSlot {
80 fn default() -> Self {
81 Self {
82 uniform: ViewportUniform::default(),
83 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
84 }
85 }
86}
87
88const _: () = assert!(core::mem::size_of::<AlignedViewportSlot>() == 256);
89const INIT_VIEWPORT_SLOTS: usize = 8;
90
91struct AtlasGrowNeed {
93 glyph_full: bool,
94 sprite_need: Option<(u32, u32)>,
95 ramp_full: bool,
96}
97
98pub(crate) struct ExternalTextureEntry {
100 pub(crate) view: wgpu::TextureView,
101 pub(crate) sampler: Option<wgpu::Sampler>,
102}
103
104pub struct WgpuRenderer {
106 pipeline: wgpu::RenderPipeline,
107 bind_group_layout: wgpu::BindGroupLayout,
108 bind_group: wgpu::BindGroup,
109 viewport_buf: wgpu::Buffer,
110 viewport_capacity: usize,
111 viewport_slots: Vec<AlignedViewportSlot>,
112 instance_buf: wgpu::Buffer,
113 instance_capacity: usize,
114 sampler: wgpu::Sampler,
115 linear_sampler: wgpu::Sampler,
116 glyph_atlas: GlyphAtlas,
117 sprite_atlas: SpriteAtlas,
118 ramp_atlas: GradientRampAtlas,
119 effects: Option<GpuEffectsEngine>,
120 external_textures: HashMap<ExternalTextureId, ExternalTextureEntry>,
121 next_external_id: u32,
122 target_format: wgpu::TextureFormat,
123 primitives: Vec<GpuPrimitive>,
124 sprite_scratch: Vec<Rgba8888>,
125 #[cfg(not(target_endian = "little"))]
126 sprite_bytes_scratch: Vec<u8>,
127 text_layout_cache: HashMap<TextLayoutKey, Arc<CachedTextLayout>>,
128 text_layout_hits: u64,
129 target_is_srgb: bool,
130}
131
132impl WgpuRenderer {
133 pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
135 let trace = std::env::var_os("VELOX_STARTUP_TRACE").is_some();
136 let t0 = std::time::Instant::now();
137 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
138 label: Some("velox_wgpu_2d_shader"),
139 source: wgpu::ShaderSource::Wgsl(SDF_WGSL.into()),
140 });
141 let t_shader = t0.elapsed();
142
143 let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
144 label: Some("velox_wgpu_bgl"),
145 entries: &[
146 wgpu::BindGroupLayoutEntry {
147 binding: 0,
148 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
149 ty: wgpu::BindingType::Buffer {
150 ty: wgpu::BufferBindingType::Uniform,
151 has_dynamic_offset: true,
152 min_binding_size: wgpu::BufferSize::new(
153 core::mem::size_of::<ViewportUniform>() as u64,
154 ),
155 },
156 count: None,
157 },
158 wgpu::BindGroupLayoutEntry {
159 binding: 1,
160 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
161 ty: wgpu::BindingType::Buffer {
162 ty: wgpu::BufferBindingType::Storage { read_only: true },
163 has_dynamic_offset: false,
164 min_binding_size: None,
165 },
166 count: None,
167 },
168 wgpu::BindGroupLayoutEntry {
169 binding: 2,
170 visibility: wgpu::ShaderStages::FRAGMENT,
171 ty: wgpu::BindingType::Texture {
172 sample_type: wgpu::TextureSampleType::Float { filterable: true },
173 view_dimension: wgpu::TextureViewDimension::D2,
174 multisampled: false,
175 },
176 count: None,
177 },
178 wgpu::BindGroupLayoutEntry {
179 binding: 3,
180 visibility: wgpu::ShaderStages::FRAGMENT,
181 ty: wgpu::BindingType::Texture {
182 sample_type: wgpu::TextureSampleType::Float { filterable: true },
183 view_dimension: wgpu::TextureViewDimension::D2,
184 multisampled: false,
185 },
186 count: None,
187 },
188 wgpu::BindGroupLayoutEntry {
189 binding: 4,
190 visibility: wgpu::ShaderStages::FRAGMENT,
191 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
192 count: None,
193 },
194 wgpu::BindGroupLayoutEntry {
195 binding: 5,
196 visibility: wgpu::ShaderStages::FRAGMENT,
197 ty: wgpu::BindingType::Texture {
198 sample_type: wgpu::TextureSampleType::Float { filterable: true },
199 view_dimension: wgpu::TextureViewDimension::D2,
200 multisampled: false,
201 },
202 count: None,
203 },
204 wgpu::BindGroupLayoutEntry {
205 binding: 6,
206 visibility: wgpu::ShaderStages::FRAGMENT,
207 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
208 count: None,
209 },
210 ],
211 });
212
213 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
214 label: Some("velox_wgpu_pipeline_layout"),
215 bind_group_layouts: &[Some(&bind_group_layout)],
216 immediate_size: 0,
217 });
218
219 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
220 label: Some("velox_wgpu_2d_pipeline"),
221 layout: Some(&pipeline_layout),
222 vertex: wgpu::VertexState {
223 module: &shader,
224 entry_point: Some("vs_main"),
225 compilation_options: wgpu::PipelineCompilationOptions::default(),
226 buffers: &[],
227 },
228 primitive: wgpu::PrimitiveState {
229 topology: wgpu::PrimitiveTopology::TriangleList,
230 strip_index_format: None,
231 front_face: wgpu::FrontFace::Ccw,
232 cull_mode: None,
233 unclipped_depth: false,
234 polygon_mode: wgpu::PolygonMode::Fill,
235 conservative: false,
236 },
237 depth_stencil: None,
238 multisample: wgpu::MultisampleState::default(),
239 fragment: Some(wgpu::FragmentState {
240 module: &shader,
241 entry_point: Some("fs_main"),
242 compilation_options: wgpu::PipelineCompilationOptions::default(),
243 targets: &[Some(wgpu::ColorTargetState {
244 format: target_format,
245 blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
246 write_mask: wgpu::ColorWrites::ALL,
247 })],
248 }),
249 multiview_mask: None,
250 cache: None,
251 });
252 let t_pso = t0.elapsed();
253 if trace {
254 std::println!(
255 "[VELOX_STARTUP_TRACE] pipeline detail: create_shader_module={:.1}ms, create_render_pipeline=+{:.1}ms",
256 t_shader.as_secs_f64() * 1000.0,
257 (t_pso - t_shader).as_secs_f64() * 1000.0,
258 );
259 }
260
261 let viewport_buf = Self::create_viewport_buffer(device, INIT_VIEWPORT_SLOTS);
262 let instance_buf = Self::create_instance_buffer(device, INITIAL_INSTANCE_CAPACITY);
263 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
264 label: Some("velox_atlas_sampler"),
265 address_mode_u: wgpu::AddressMode::ClampToEdge,
266 address_mode_v: wgpu::AddressMode::ClampToEdge,
267 address_mode_w: wgpu::AddressMode::ClampToEdge,
268 mag_filter: wgpu::FilterMode::Nearest,
269 min_filter: wgpu::FilterMode::Nearest,
270 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
271 ..Default::default()
272 });
273 let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
274 label: Some("velox_linear_sampler"),
275 address_mode_u: wgpu::AddressMode::ClampToEdge,
276 address_mode_v: wgpu::AddressMode::ClampToEdge,
277 address_mode_w: wgpu::AddressMode::ClampToEdge,
278 mag_filter: wgpu::FilterMode::Linear,
279 min_filter: wgpu::FilterMode::Linear,
280 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
281 ..Default::default()
282 });
283
284 let glyph_atlas = GlyphAtlas::new(device, GLYPH_ATLAS_INIT_SIZE);
285 let sprite_atlas = SpriteAtlas::new(device, 1);
286 let ramp_atlas = GradientRampAtlas::new(device);
287 let bind_group = Self::create_bind_group(
288 device,
289 &bind_group_layout,
290 &viewport_buf,
291 &instance_buf,
292 &glyph_atlas.view,
293 &sprite_atlas.view,
294 &sampler,
295 &ramp_atlas.view,
296 &linear_sampler,
297 );
298
299 Self {
300 pipeline,
301 bind_group_layout,
302 bind_group,
303 viewport_buf,
304 viewport_capacity: INIT_VIEWPORT_SLOTS,
305 viewport_slots: Vec::with_capacity(INIT_VIEWPORT_SLOTS),
306 instance_buf,
307 instance_capacity: INITIAL_INSTANCE_CAPACITY,
308 sampler,
309 linear_sampler,
310 glyph_atlas,
311 sprite_atlas,
312 ramp_atlas,
313 effects: None,
314 external_textures: HashMap::new(),
315 next_external_id: 1,
316 target_format,
317 primitives: Vec::with_capacity(INITIAL_INSTANCE_CAPACITY),
318 sprite_scratch: Vec::new(),
319 #[cfg(not(target_endian = "little"))]
320 sprite_bytes_scratch: Vec::new(),
321 text_layout_cache: HashMap::with_capacity(64),
322 text_layout_hits: 0,
323 target_is_srgb: target_format.is_srgb(),
324 }
325 }
326
327 fn create_viewport_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
328 device.create_buffer(&wgpu::BufferDescriptor {
329 label: Some("velox_wgpu_viewport"),
330 size: (capacity.max(1) * core::mem::size_of::<AlignedViewportSlot>()) as u64,
331 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
332 mapped_at_creation: false,
333 })
334 }
335
336 fn create_instance_buffer(device: &wgpu::Device, capacity: usize) -> wgpu::Buffer {
337 device.create_buffer(&wgpu::BufferDescriptor {
338 label: Some("velox_wgpu_instances"),
339 size: (capacity.max(1) * core::mem::size_of::<GpuPrimitive>()) as u64,
340 usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
341 mapped_at_creation: false,
342 })
343 }
344
345 #[allow(clippy::too_many_arguments)]
346 fn create_bind_group(
347 device: &wgpu::Device,
348 layout: &wgpu::BindGroupLayout,
349 viewport_buf: &wgpu::Buffer,
350 instance_buf: &wgpu::Buffer,
351 glyph_view: &wgpu::TextureView,
352 sprite_view: &wgpu::TextureView,
353 sampler: &wgpu::Sampler,
354 ramp_view: &wgpu::TextureView,
355 linear_sampler: &wgpu::Sampler,
356 ) -> wgpu::BindGroup {
357 device.create_bind_group(&wgpu::BindGroupDescriptor {
358 label: Some("velox_wgpu_bg"),
359 layout,
360 entries: &[
361 wgpu::BindGroupEntry {
362 binding: 0,
363 resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
364 buffer: viewport_buf,
365 offset: 0,
366 size: wgpu::BufferSize::new(core::mem::size_of::<ViewportUniform>() as u64),
367 }),
368 },
369 wgpu::BindGroupEntry {
370 binding: 1,
371 resource: instance_buf.as_entire_binding(),
372 },
373 wgpu::BindGroupEntry {
374 binding: 2,
375 resource: wgpu::BindingResource::TextureView(glyph_view),
376 },
377 wgpu::BindGroupEntry {
378 binding: 3,
379 resource: wgpu::BindingResource::TextureView(sprite_view),
380 },
381 wgpu::BindGroupEntry {
382 binding: 4,
383 resource: wgpu::BindingResource::Sampler(sampler),
384 },
385 wgpu::BindGroupEntry {
386 binding: 5,
387 resource: wgpu::BindingResource::TextureView(ramp_view),
388 },
389 wgpu::BindGroupEntry {
390 binding: 6,
391 resource: wgpu::BindingResource::Sampler(linear_sampler),
392 },
393 ],
394 })
395 }
396
397 #[inline]
399 pub fn last_primitive_count(&self) -> usize {
400 self.primitives.len()
401 }
402
403 #[inline]
405 pub const fn atlas_sizes(&self) -> (u32, u32) {
406 (self.glyph_atlas.width, self.sprite_atlas.width)
407 }
408
409 #[inline]
411 pub const fn sprite_cache_hits(&self) -> u64 {
412 self.sprite_atlas.cache_hits
413 }
414
415 #[inline]
417 pub const fn text_layout_cache_hits(&self) -> u64 {
418 self.text_layout_hits
419 }
420
421 #[inline]
423 pub fn text_layout_cache_len(&self) -> usize {
424 self.text_layout_cache.len()
425 }
426
427 pub fn register_external_texture(
430 &mut self,
431 view: wgpu::TextureView,
432 sampler: Option<wgpu::Sampler>,
433 ) -> ExternalTextureId {
434 let mut id = self.next_external_id;
435 while id == 0 || self.external_textures.contains_key(&ExternalTextureId(id)) {
436 id = id.wrapping_add(1);
437 }
438 self.next_external_id = id.wrapping_add(1).max(1);
439 let tex_id = ExternalTextureId(id);
440 self.external_textures
441 .insert(tex_id, ExternalTextureEntry { view, sampler });
442 tex_id
443 }
444
445 pub fn register_external_texture_with_id(
447 &mut self,
448 id: ExternalTextureId,
449 view: wgpu::TextureView,
450 sampler: Option<wgpu::Sampler>,
451 ) {
452 self.external_textures
453 .insert(id, ExternalTextureEntry { view, sampler });
454 }
455
456 pub fn update_external_texture(&mut self, id: ExternalTextureId, view: wgpu::TextureView) -> bool {
458 if let Some(entry) = self.external_textures.get_mut(&id) {
459 entry.view = view;
460 true
461 } else {
462 false
463 }
464 }
465
466 pub fn unregister_external_texture(&mut self, id: ExternalTextureId) -> bool {
468 self.external_textures.remove(&id).is_some()
469 }
470
471 #[inline]
473 pub fn external_texture_count(&self) -> usize {
474 self.external_textures.len()
475 }
476
477 fn rebuild_bind_group(&mut self, device: &wgpu::Device) {
478 self.bind_group = Self::create_bind_group(
479 device,
480 &self.bind_group_layout,
481 &self.viewport_buf,
482 &self.instance_buf,
483 &self.glyph_atlas.view,
484 &self.sprite_atlas.view,
485 &self.sampler,
486 &self.ramp_atlas.view,
487 &self.linear_sampler,
488 );
489 }
490
491 #[inline]
492 fn sprite_cache_hash(sprite: SpriteSource<'_>, rel_x: i16, rel_y: i16, sb_w: i16, sb_h: i16) -> u64 {
493 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
494 let mix = |h: &mut u64, v: u64| {
495 *h ^= v;
496 *h = h.wrapping_mul(0x0100_0000_01b3);
497 };
498 mix(&mut h, ((rel_x as u16 as u64) << 16) | (rel_y as u16 as u64));
499 mix(&mut h, ((sb_w as u16 as u64) << 16) | (sb_h as u16 as u64));
500 match sprite {
501 SpriteSource::Bitmap {
502 bytes,
503 format,
504 tint,
505 } => {
506 mix(&mut h, 1);
507 mix(&mut h, bytes.as_ptr() as usize as u64);
508 mix(&mut h, bytes.len() as u64);
509 mix(&mut h, format as u64);
510 mix(&mut h, tint.0 as u64);
511 }
512 SpriteSource::Shader { state_hash, .. } => {
513 mix(&mut h, 2);
514 mix(&mut h, state_hash as u64);
515 }
516 SpriteSource::Svg {
517 source,
518 is_path_only,
519 tint,
520 stroke_width_x10,
521 } => {
522 mix(&mut h, 3);
523 mix(&mut h, if is_path_only { 1 } else { 0 });
524 mix(&mut h, stroke_width_x10 as u64);
525 mix(&mut h, tint.0 as u64);
526 let s = source.as_str().as_bytes();
527 mix(&mut h, s.len() as u64);
528 for &b in s {
529 mix(&mut h, b as u64);
530 }
531 }
532 SpriteSource::Arc { .. } => {}
533 }
534 h
535 }
536
537 #[allow(clippy::too_many_arguments)]
539 fn encode_single_op(
540 &mut self,
541 queue: &wgpu::Queue,
542 op: &DrawOp<'_>,
543 eff_clip: Region,
544 viewport: Region,
545 sf: f32,
546 use_ttf: bool,
547 origin_x: f32,
548 origin_y: f32,
549 ) -> Result<(), AtlasGrowNeed> {
550 let mut sb_f = snap_bounds(op.bounds, sf);
551 let clip_region = if op.clip_radius > 0 { op.clip } else { eff_clip };
552 let mut sc_f = snap_clip(clip_region, sf);
553 if (op.bounds.w == 1 && eff_clip.w == 1) || (op.bounds.h == 1 && eff_clip.h == 1) {
554 let vp_clip_f = snap_clip(viewport, sf);
555 if op.bounds.w == 1 && eff_clip.w == 1 {
556 sc_f[2] = sc_f[2].max(sb_f[0] + sb_f[2]).min(vp_clip_f[2]);
557 }
558 if op.bounds.h == 1 && eff_clip.h == 1 {
559 sc_f[3] = sc_f[3].max(sb_f[1] + sb_f[3]).min(vp_clip_f[3]);
560 }
561 }
562 let clip_radius_px = (op.clip_radius as f32) * sf;
563 let shifted_sb = [sb_f[0] - origin_x, sb_f[1] - origin_y, sb_f[2], sb_f[3]];
564 let shifted_sc = [
565 sc_f[0] - origin_x,
566 sc_f[1] - origin_y,
567 sc_f[2] - origin_x,
568 sc_f[3] - origin_y,
569 ];
570
571 match op.payload {
572 DrawPayload::Quad {
573 bg,
574 bg_grad,
575 border_color,
576 rounded,
577 border_width,
578 } => {
579 let raw_bw = border_width & 0x7F;
580 let bw = if raw_bw == 0 {
581 0.0
582 } else {
583 ((raw_bw as f32) * sf).round().max(1.0)
584 };
585 let horiz = (border_width & 0x80) != 0;
586 let r = (rounded as f32) * sf;
587 let is_shadow = border_color.a() == 0 && raw_bw > 0;
588 if is_shadow {
589 if bg.a() > 0 {
590 self.primitives.push(make_shadow_primitive(
591 shifted_sb,
592 shifted_sc,
593 clip_radius_px,
594 r,
595 (raw_bw as f32) * sf,
596 bg,
597 ));
598 }
599 } else if bg.a() > 0 || bg_grad.a() > 0 || (bw > 0.0 && border_color.a() > 0) {
600 self.primitives.push(make_quad_primitive(
601 shifted_sb,
602 shifted_sc,
603 clip_radius_px,
604 r,
605 bw,
606 horiz,
607 bg,
608 bg_grad,
609 border_color,
610 ));
611 }
612 }
613 DrawPayload::StyledQuad(sq) => {
614 let ramp_v = match sq.paint {
615 Paint::Solid(_) => None,
616 Paint::LinearGradient { stops, space, .. }
617 | Paint::RadialGradient { stops, space, .. }
618 | Paint::ConicGradient { stops, space, .. } => {
619 let Some(v) = self.ramp_atlas.get_or_insert(queue, stops, space, sq.opacity)
620 else {
621 return Err(AtlasGrowNeed {
622 glyph_full: false,
623 sprite_need: None,
624 ramp_full: true,
625 });
626 };
627 Some(v)
628 }
629 };
630 if let Some(prim) = make_styled_quad_primitive(
631 shifted_sb,
632 shifted_sc,
633 clip_radius_px,
634 sq,
635 sf,
636 ramp_v,
637 ) {
638 self.primitives.push(prim);
639 }
640 }
641 DrawPayload::TextRun {
642 text,
643 color,
644 font_size,
645 text_flags,
646 } => {
647 if text.is_empty() || color.a() == 0 {
648 return Ok(());
649 }
650 let sb = Region::new(
651 sb_f[0] as i16,
652 sb_f[1] as i16,
653 sb_f[2] as i16,
654 sb_f[3] as i16,
655 );
656 let sc = Region::new(
657 sc_f[0] as i16,
658 sc_f[1] as i16,
659 (sc_f[2] - sc_f[0]).max(0.0) as i16,
660 (sc_f[3] - sc_f[1]).max(0.0) as i16,
661 );
662 let (adj_bounds, adj_sc, adj_flags, logical_fs, fs_q4) = compute_scaled_text_box(
663 op.bounds,
664 op.clip,
665 viewport,
666 sb,
667 sc,
668 text.as_str(),
669 font_size,
670 text_flags,
671 sf,
672 );
673 let adj_sc_f = [
674 adj_sc.x as f32 - origin_x,
675 adj_sc.y as f32 - origin_y,
676 adj_sc.right() as f32 - origin_x,
677 adj_sc.bottom() as f32 - origin_y,
678 ];
679 let prim_before = self.primitives.len();
680 if !self.encode_text_run(
681 queue,
682 adj_bounds,
683 adj_sc,
684 adj_sc_f,
685 clip_radius_px,
686 text.as_str(),
687 color,
688 logical_fs,
689 fs_q4,
690 adj_flags,
691 use_ttf,
692 ) {
693 return Err(AtlasGrowNeed {
694 glyph_full: true,
695 sprite_need: None,
696 ramp_full: false,
697 });
698 }
699 if origin_x != 0.0 || origin_y != 0.0 {
700 for p in &mut self.primitives[prim_before..] {
701 p.bounds[0] -= origin_x;
702 p.bounds[1] -= origin_y;
703 }
704 }
705 }
706 DrawPayload::Sprite(SpriteSource::Arc {
707 thickness,
708 start_deg10,
709 sweep_deg10,
710 fill_sweep_deg10,
711 track_color,
712 fill_color,
713 }) => {
714 self.primitives.push(make_arc_primitive(
715 shifted_sb,
716 shifted_sc,
717 clip_radius_px,
718 ((thickness.max(1) as f32) * sf).max(1.5),
719 start_deg10,
720 sweep_deg10,
721 fill_sweep_deg10,
722 track_color,
723 fill_color,
724 ));
725 }
726 DrawPayload::Sprite(sprite) => {
727 sb_f[0] = sb_f[0].round();
728 sb_f[1] = sb_f[1].round();
729 let sb = Region::new(
730 sb_f[0] as i16,
731 sb_f[1] as i16,
732 sb_f[2] as i16,
733 sb_f[3] as i16,
734 );
735 let sc = Region::new(
736 sc_f[0] as i16,
737 sc_f[1] as i16,
738 (sc_f[2] - sc_f[0]).max(0.0) as i16,
739 (sc_f[3] - sc_f[1]).max(0.0) as i16,
740 );
741 let eff = sc.intersect(sb);
742 if eff.is_empty() {
743 return Ok(());
744 }
745 let w = eff.w.max(1) as usize;
746 let h = eff.h.max(1) as usize;
747 let cache_key = SpriteCacheKey {
748 w: w as u32,
749 h: h as u32,
750 hash: Self::sprite_cache_hash(
751 sprite,
752 eff.x.saturating_sub(sb.x),
753 eff.y.saturating_sub(sb.y),
754 sb.w,
755 sb.h,
756 ),
757 };
758
759 let uv = if let Some(cached_uv) = self.sprite_atlas.lookup(cache_key) {
760 cached_uv
761 } else {
762 let len = w * h;
763 if self.sprite_scratch.len() < len {
764 self.sprite_scratch.resize(len, Rgba8888(0));
765 }
766 let slice = &mut self.sprite_scratch[..len];
767 slice.fill(Rgba8888(0));
768 rasterize_sprite_source(sb, eff, sprite, eff.x, eff.y, w, slice);
769
770 #[cfg(target_endian = "little")]
771 let rgba_bytes: &[u8] = pod_as_bytes(slice);
772 #[cfg(not(target_endian = "little"))]
773 let rgba_bytes: &[u8] = {
774 self.sprite_bytes_scratch.clear();
775 self.sprite_bytes_scratch.reserve(len * 4);
776 for px in slice.iter() {
777 self.sprite_bytes_scratch
778 .extend_from_slice(&px.to_rgba_bytes());
779 }
780 &self.sprite_bytes_scratch
781 };
782
783 let Some(uv) = self
784 .sprite_atlas
785 .insert_and_upload(queue, cache_key, rgba_bytes)
786 else {
787 return Err(AtlasGrowNeed {
788 glyph_full: false,
789 sprite_need: Some((w as u32, h as u32)),
790 ramp_full: false,
791 });
792 };
793 uv
794 };
795
796 self.primitives.push(GpuPrimitive {
797 bounds: [
798 eff.x as f32 - origin_x,
799 eff.y as f32 - origin_y,
800 w as f32,
801 h as f32,
802 ],
803 clip: shifted_sc,
804 uv,
805 color0: [1.0; 4],
806 color1: [0.0; 4],
807 border_color: [0.0; 4],
808 params: [0.0, 0.0, KIND_SPRITE, 0.0],
809 extra: [clip_radius_px, 0.0, 0.0, 0.0],
810 radii: [0.0; 4],
811 grad_a: [0.0; 4],
812 grad_b: [0.0; 4],
813 xform: IDENTITY_XFORM,
814 });
815 }
816 DrawPayload::RichText(rt) => {
817 let sb = snap_bounds_region_scaled(op.bounds, sf);
818 let sc = Region::new(
819 sc_f[0] as i16,
820 sc_f[1] as i16,
821 (sc_f[2] - sc_f[0]).max(0.0) as i16,
822 (sc_f[3] - sc_f[1]).max(0.0) as i16,
823 );
824 let eff = sc.intersect(sb);
825 if eff.is_empty() {
826 return Ok(());
827 }
828 let w = eff.w.max(1) as usize;
829 let h = eff.h.max(1) as usize;
830 let mut kh: u32 = 0x5254_4558;
831 rt.mix_hash(&mut kh);
832 let hash = ((kh as u64) << 32)
833 | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
834 | (eff.y.saturating_sub(sb.y) as u16 as u64))
835 ^ ((sf * 16.0).round() as u64);
836 let cache_key = SpriteCacheKey {
837 w: w as u32,
838 h: h as u32,
839 hash,
840 };
841 let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
842 cached
843 } else {
844 let len = w * h;
845 if self.sprite_scratch.len() < len {
846 self.sprite_scratch.resize(len, Rgba8888(0));
847 }
848 let slice = &mut self.sprite_scratch[..len];
849 slice.fill(Rgba8888(0));
850 crate::renderers::software::rasterize_rich_text(
851 rt, sb, eff, sf, eff.x, eff.y, w, slice,
852 );
853 let rgba_bytes = pod_as_bytes(slice);
854 let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
855 else {
856 return Err(AtlasGrowNeed {
857 glyph_full: false,
858 sprite_need: Some((w as u32, h as u32)),
859 ramp_full: false,
860 });
861 };
862 u
863 };
864 self.primitives.push(GpuPrimitive {
865 bounds: [
866 eff.x as f32 - origin_x,
867 eff.y as f32 - origin_y,
868 w as f32,
869 h as f32,
870 ],
871 clip: shifted_sc,
872 uv,
873 color0: [1.0; 4],
874 color1: [0.0; 4],
875 border_color: [0.0; 4],
876 params: [0.0, 0.0, KIND_SPRITE, 0.0],
877 extra: [clip_radius_px, 0.0, 0.0, 0.0],
878 radii: [0.0; 4],
879 grad_a: [0.0; 4],
880 grad_b: [0.0; 4],
881 xform: IDENTITY_XFORM,
882 });
883 }
884 DrawPayload::DecodedImage(img) => {
885 let sb = snap_bounds_region_scaled(op.bounds, sf);
886 let sc = Region::new(
887 sc_f[0] as i16,
888 sc_f[1] as i16,
889 (sc_f[2] - sc_f[0]).max(0.0) as i16,
890 (sc_f[3] - sc_f[1]).max(0.0) as i16,
891 );
892 let eff = sc.intersect(sb);
893 if eff.is_empty() {
894 return Ok(());
895 }
896 let w = eff.w.max(1) as usize;
897 let h = eff.h.max(1) as usize;
898 let cache_rev = crate::image_pipeline::get_cached_image(img.id)
899 .map(|p| p.revision)
900 .unwrap_or(0);
901 let mut kh: u32 = 0x4449_4D47 ^ (cache_rev as u32);
902 img.mix_hash(&mut kh);
903 let hash = ((kh as u64) << 32)
904 | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
905 | (eff.y.saturating_sub(sb.y) as u16 as u64))
906 ^ ((sf * 16.0).round() as u64);
907 let cache_key = SpriteCacheKey {
908 w: w as u32,
909 h: h as u32,
910 hash,
911 };
912 let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
913 cached
914 } else {
915 let len = w * h;
916 if self.sprite_scratch.len() < len {
917 self.sprite_scratch.resize(len, Rgba8888(0));
918 }
919 let slice = &mut self.sprite_scratch[..len];
920 slice.fill(Rgba8888(0));
921 crate::renderers::software::rasterize_decoded_image(
922 img, sb, eff, sf, eff.x, eff.y, w, slice,
923 );
924 let rgba_bytes = pod_as_bytes(slice);
925 let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
926 else {
927 return Err(AtlasGrowNeed {
928 glyph_full: false,
929 sprite_need: Some((w as u32, h as u32)),
930 ramp_full: false,
931 });
932 };
933 u
934 };
935 self.primitives.push(GpuPrimitive {
936 bounds: [
937 eff.x as f32 - origin_x,
938 eff.y as f32 - origin_y,
939 w as f32,
940 h as f32,
941 ],
942 clip: shifted_sc,
943 uv,
944 color0: [1.0; 4],
945 color1: [0.0; 4],
946 border_color: [0.0; 4],
947 params: [0.0, 0.0, KIND_SPRITE, 0.0],
948 extra: [clip_radius_px, 0.0, 0.0, 0.0],
949 radii: [0.0; 4],
950 grad_a: [0.0; 4],
951 grad_b: [0.0; 4],
952 xform: IDENTITY_XFORM,
953 });
954 }
955 DrawPayload::Vector(vec_spec) => {
956 let sb = snap_bounds_region_scaled(op.bounds, sf);
957 let sc = Region::new(
958 sc_f[0] as i16,
959 sc_f[1] as i16,
960 (sc_f[2] - sc_f[0]).max(0.0) as i16,
961 (sc_f[3] - sc_f[1]).max(0.0) as i16,
962 );
963 let eff = sc.intersect(sb);
964 if eff.is_empty() {
965 return Ok(());
966 }
967 let w = eff.w.max(1) as usize;
968 let h = eff.h.max(1) as usize;
969 let mut kh: u32 = 0x5645_4354;
970 vec_spec.mix_hash(&mut kh);
971 let hash = ((kh as u64) << 32)
972 | (((eff.x.saturating_sub(sb.x) as u16 as u64) << 16)
973 | (eff.y.saturating_sub(sb.y) as u16 as u64))
974 ^ ((sf * 16.0).round() as u64);
975 let cache_key = SpriteCacheKey {
976 w: w as u32,
977 h: h as u32,
978 hash,
979 };
980 let uv = if let Some(cached) = self.sprite_atlas.lookup(cache_key) {
981 cached
982 } else {
983 let len = w * h;
984 if self.sprite_scratch.len() < len {
985 self.sprite_scratch.resize(len, Rgba8888(0));
986 }
987 let slice = &mut self.sprite_scratch[..len];
988 slice.fill(Rgba8888(0));
989 crate::vector_canvas::rasterize_vector_spec(
990 vec_spec, sb, eff, sf, eff.x, eff.y, w, slice,
991 );
992 let rgba_bytes = pod_as_bytes(slice);
993 let Some(u) = self.sprite_atlas.insert_and_upload(queue, cache_key, rgba_bytes)
994 else {
995 return Err(AtlasGrowNeed {
996 glyph_full: false,
997 sprite_need: Some((w as u32, h as u32)),
998 ramp_full: false,
999 });
1000 };
1001 u
1002 };
1003 self.primitives.push(GpuPrimitive {
1004 bounds: [
1005 eff.x as f32 - origin_x,
1006 eff.y as f32 - origin_y,
1007 w as f32,
1008 h as f32,
1009 ],
1010 clip: shifted_sc,
1011 uv,
1012 color0: [1.0; 4],
1013 color1: [0.0; 4],
1014 border_color: [0.0; 4],
1015 params: [0.0, 0.0, KIND_SPRITE, 0.0],
1016 extra: [clip_radius_px, 0.0, 0.0, 0.0],
1017 radii: [0.0; 4],
1018 grad_a: [0.0; 4],
1019 grad_b: [0.0; 4],
1020 xform: IDENTITY_XFORM,
1021 });
1022 }
1023 DrawPayload::PushLayer(_)
1024 | DrawPayload::PopLayer
1025 | DrawPayload::ExternalTexture(_) => {}
1026 }
1027 Ok(())
1028 }
1029
1030 fn try_encode_ops(
1032 &mut self,
1033 queue: &wgpu::Queue,
1034 ops: &[DrawOp<'_>],
1035 viewport: Region,
1036 scale_factor: f32,
1037 ) -> Result<(), AtlasGrowNeed> {
1038 self.primitives.clear();
1039 if viewport.is_empty() {
1040 return Ok(());
1041 }
1042
1043 let sf = scale_factor.clamp(0.5, 4.0);
1044 let use_ttf = crate::display::ttf_atlas::has_system_font();
1045
1046 for (idx, op) in ops.iter().enumerate() {
1047 let raw_clip = match op.payload {
1048 DrawPayload::StyledQuad(sq) if sq.transform.is_some() => viewport.intersect(op.clip),
1049 _ => viewport.intersect(op.clip).intersect(op.bounds),
1050 };
1051 if raw_clip.is_empty() {
1052 continue;
1053 }
1054 let eff_clip = compute_unoccluded_clip(raw_clip, &ops[(idx + 1)..]);
1055 if eff_clip.is_empty() {
1056 continue;
1057 }
1058 self.encode_single_op(queue, op, eff_clip, viewport, sf, use_ttf, 0.0, 0.0)?;
1059 }
1060 Ok(())
1061 }
1062
1063 fn get_or_build_text_layout(
1064 &mut self,
1065 text: &str,
1066 logical_font_size: u8,
1067 font_size_q4: u16,
1068 max_width: i16,
1069 text_flags: u8,
1070 use_ttf: bool,
1071 ) -> Arc<CachedTextLayout> {
1072 let logical_fs = logical_font_size.max(8);
1073 let q4 = font_size_q4.clamp(32, 1020);
1074 let key = TextLayoutKey {
1075 text_hash: hash_layout_text(text),
1076 text_len: text.len() as u32,
1077 logical_font_size: logical_fs,
1078 font_size_q4: q4,
1079 max_width,
1080 text_flags,
1081 use_ttf,
1082 };
1083 if let Some(hit) = self.text_layout_cache.get(&key) {
1084 if hit.text.as_str() == text {
1085 self.text_layout_hits = self.text_layout_hits.wrapping_add(1);
1086 return Arc::clone(hit);
1087 }
1088 }
1089
1090 let render_fs = (q4 as f32) * 0.25;
1091 let fs_u8 = ((q4 + 2) >> 2).clamp(8, 255) as u8;
1092 let scale_ratio = render_fs / (logical_fs as f32);
1093 let is_ellipsis = (text_flags & 0x04) != 0;
1094 let is_nowrap = (text_flags & 0x08) != 0;
1095 let lines = if use_ttf {
1096 let logical_max_w = ((max_width as f32) / scale_ratio)
1097 .round()
1098 .clamp(1.0, i16::MAX as f32) as i16;
1099 split_text_lines(text, logical_fs, logical_max_w, is_nowrap || is_ellipsis)
1100 } else {
1101 split_text_lines(text, fs_u8, max_width, is_nowrap || is_ellipsis)
1102 };
1103 let line_count = lines.len();
1104 let char_h = if use_ttf {
1105 (render_fs.round() as i16).max(8)
1106 } else {
1107 (fs_u8 as i16).max(8)
1108 };
1109 let line_step = if use_ttf {
1110 ((render_fs * 1.25).round() as i16).max(char_h)
1111 } else {
1112 ((fs_u8 as i16) * 5 / 4).max(char_h)
1113 };
1114 let ascent = if use_ttf {
1115 crate::display::ttf_atlas::get_font_ascent_f32(render_fs) as i16
1116 } else {
1117 char_h
1118 };
1119 let dot_w = measure_char_advance('.', fs_u8);
1120 let dot_adv_f = if use_ttf {
1121 crate::display::ttf_atlas::measure_ttf_char_advance_f32('.', logical_fs)
1122 .map(|a| a * scale_ratio)
1123 .unwrap_or(dot_w as f32)
1124 } else {
1125 dot_w as f32
1126 };
1127 let total_h = if line_count == 0 {
1128 0
1129 } else {
1130 char_h.saturating_add(line_step.saturating_mul((line_count as i16) - 1))
1131 };
1132
1133 let mut glyphs = Vec::with_capacity(text.len().min(128));
1134 for (line_idx, &(b_start, b_end, raw_line_w_orig)) in lines.as_slice().iter().enumerate() {
1135 let line_str = &text[b_start..b_end];
1136 let raw_line_w = if use_ttf {
1137 (crate::display::measure_line_width_f32(line_str, logical_fs) * scale_ratio).ceil()
1138 as i16
1139 } else {
1140 raw_line_w_orig
1141 };
1142 let need_ellipsis = is_ellipsis && raw_line_w > max_width && max_width > dot_w * 3;
1143 let eff_w = if need_ellipsis {
1144 max_width
1145 } else {
1146 raw_line_w.min(max_width)
1147 };
1148 let start_rel_x = align_offset_x(max_width, eff_w, text_flags);
1149 let rel_y = if use_ttf {
1150 ascent.saturating_add((line_idx as i16).saturating_mul(line_step))
1151 } else {
1152 (line_idx as i16).saturating_mul(line_step)
1153 };
1154
1155 if use_ttf {
1156 let mut pen_x = start_rel_x as f32;
1157 let max_x_before_dots_f = (max_width as f32) - dot_adv_f * 3.0;
1158 let mut prev_ch: Option<char> = None;
1159 for ch in line_str.chars() {
1160 if let Some(p) = prev_ch {
1161 pen_x += crate::display::ttf_atlas::measure_ttf_kerning_f32(
1162 p, ch, logical_fs,
1163 ) * scale_ratio;
1164 }
1165 let adv_f =
1166 crate::display::ttf_atlas::measure_ttf_char_advance_f32(ch, logical_fs)
1167 .map(|a| a * scale_ratio)
1168 .unwrap_or_else(|| {
1169 (measure_char_advance(ch, logical_fs) as f32) * scale_ratio
1170 });
1171 if need_ellipsis && pen_x + adv_f > max_x_before_dots_f + 0.01 {
1172 for _ in 0..3 {
1173 glyphs.push(ShapedGlyphPos {
1174 ch: '.',
1175 rel_x: pen_x.round() as i16,
1176 rel_y,
1177 });
1178 pen_x += dot_adv_f;
1179 }
1180 break;
1181 }
1182 if ch != ' ' {
1183 glyphs.push(ShapedGlyphPos {
1184 ch,
1185 rel_x: pen_x.round() as i16,
1186 rel_y,
1187 });
1188 }
1189 pen_x += adv_f;
1190 prev_ch = Some(ch);
1191 }
1192 } else {
1193 let mut rel_x = start_rel_x;
1194 let max_x_before_dots = max_width.saturating_sub(dot_w * 3);
1195 let mut prev_ch: Option<char> = None;
1196 for ch in line_str.chars() {
1197 if let Some(p) = prev_ch {
1198 rel_x = rel_x.saturating_add(measure_char_kerning(p, ch, fs_u8));
1199 }
1200 let adv = measure_char_advance(ch, fs_u8);
1201 if need_ellipsis && rel_x.saturating_add(adv) > max_x_before_dots {
1202 for _ in 0..3 {
1203 glyphs.push(ShapedGlyphPos {
1204 ch: '.',
1205 rel_x,
1206 rel_y,
1207 });
1208 rel_x = rel_x.saturating_add(dot_w);
1209 }
1210 break;
1211 }
1212 if ch != ' ' {
1213 glyphs.push(ShapedGlyphPos { ch, rel_x, rel_y });
1214 }
1215 rel_x = rel_x.saturating_add(adv);
1216 prev_ch = Some(ch);
1217 }
1218 }
1219 }
1220
1221 let built = Arc::new(CachedTextLayout {
1222 text: String::from(text),
1223 total_h,
1224 glyphs,
1225 });
1226 if self.text_layout_cache.len() >= MAX_TEXT_LAYOUT_CACHE_ENTRIES {
1227 self.text_layout_cache.clear();
1228 }
1229 self.text_layout_cache.insert(key, Arc::clone(&built));
1230 built
1231 }
1232
1233 #[allow(clippy::too_many_arguments)]
1234 fn encode_text_run(
1235 &mut self,
1236 queue: &wgpu::Queue,
1237 bounds: Region,
1238 clip: Region,
1239 clip_f32: [f32; 4],
1240 clip_radius_px: f32,
1241 text: &str,
1242 color: Color,
1243 logical_font_size: u8,
1244 font_size_q4: u16,
1245 text_flags: u8,
1246 use_ttf: bool,
1247 ) -> bool {
1248 let layout = self.get_or_build_text_layout(
1249 text,
1250 logical_font_size,
1251 font_size_q4,
1252 bounds.w,
1253 text_flags,
1254 use_ttf,
1255 );
1256 if layout.glyphs.is_empty() {
1257 return true;
1258 }
1259 let top_y = bounds
1260 .y
1261 .saturating_add(bounds.h.saturating_sub(layout.total_h).max(0) >> 1);
1262 let col_f32 = color_to_f32(color);
1263
1264 for g in &layout.glyphs {
1265 let Some(entry) = self
1266 .glyph_atlas
1267 .get_or_insert(queue, g.ch, font_size_q4, use_ttf)
1268 else {
1269 return false;
1270 };
1271 if entry.width > 0 && entry.height > 0 {
1272 let gx = bounds
1273 .x
1274 .saturating_add(g.rel_x)
1275 .saturating_add(entry.xmin);
1276 let gy = if use_ttf {
1277 top_y
1278 .saturating_add(g.rel_y)
1279 .saturating_sub(entry.height)
1280 .saturating_sub(entry.ymin)
1281 } else {
1282 top_y.saturating_add(g.rel_y)
1283 };
1284 let greg = Region::new(gx, gy, entry.width, entry.height);
1285 if !clip.intersect(greg).is_empty() {
1286 self.primitives.push(GpuPrimitive {
1287 bounds: [
1288 gx as f32,
1289 gy as f32,
1290 entry.width as f32,
1291 entry.height as f32,
1292 ],
1293 clip: clip_f32,
1294 uv: entry.uv,
1295 color0: col_f32,
1296 color1: [0.0; 4],
1297 border_color: [0.0; 4],
1298 params: [0.0, 0.0, KIND_GLYPH, 0.0],
1299 extra: [clip_radius_px, 0.0, 0.0, 0.0],
1300 radii: [0.0; 4],
1301 grad_a: [0.0; 4],
1302 grad_b: [0.0; 4],
1303 xform: IDENTITY_XFORM,
1304 });
1305 }
1306 }
1307 }
1308 true
1309 }
1310
1311 fn handle_atlas_grow(&mut self, device: &wgpu::Device, need: AtlasGrowNeed) -> (bool, bool) {
1312 let mut dirty = false;
1313 let mut can_retry = true;
1314 if need.glyph_full && self.glyph_atlas.reset_or_grow(device) {
1315 dirty = true;
1316 }
1317 if need.ramp_full && self.ramp_atlas.reset_or_grow(device) {
1318 dirty = true;
1319 }
1320 if let Some((sw, sh)) = need.sprite_need {
1321 let (recreated, retry) = self.sprite_atlas.reset_or_grow(device, sw, sh);
1322 if recreated {
1323 dirty = true;
1324 }
1325 if !retry {
1326 can_retry = false;
1327 }
1328 }
1329 (dirty, can_retry)
1330 }
1331
1332 #[allow(clippy::too_many_arguments)]
1336 pub fn render_to_view(
1337 &mut self,
1338 device: &wgpu::Device,
1339 queue: &wgpu::Queue,
1340 ops: &[DrawOp<'_>],
1341 viewport: Region,
1342 scale_factor: f32,
1343 target_view: &wgpu::TextureView,
1344 phys_width: u32,
1345 phys_height: u32,
1346 clear_color: wgpu::Color,
1347 ) {
1348 if ops_have_layers_or_blend(ops) && !viewport.is_empty() {
1349 self.render_to_view_multi_pass(
1350 device,
1351 queue,
1352 ops,
1353 viewport,
1354 scale_factor,
1355 target_view,
1356 phys_width,
1357 phys_height,
1358 clear_color,
1359 );
1360 return;
1361 }
1362
1363 let mut bind_group_dirty = false;
1364 for _attempt in 0..4 {
1365 match self.try_encode_ops(queue, ops, viewport, scale_factor) {
1366 Ok(()) => break,
1367 Err(need) => {
1368 let (dirty, can_retry) = self.handle_atlas_grow(device, need);
1369 if dirty {
1370 bind_group_dirty = true;
1371 }
1372 if !can_retry {
1373 break;
1374 }
1375 }
1376 }
1377 }
1378
1379 if self.primitives.len() > self.instance_capacity {
1380 self.instance_capacity = self.primitives.len().next_power_of_two();
1381 self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
1382 bind_group_dirty = true;
1383 }
1384 if bind_group_dirty {
1385 self.rebuild_bind_group(device);
1386 }
1387
1388 let slot0 = AlignedViewportSlot {
1389 uniform: ViewportUniform {
1390 size: [phys_width.max(1) as f32, phys_height.max(1) as f32],
1391 is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
1392 _pad: 0.0,
1393 },
1394 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1395 };
1396 queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
1397
1398 if !self.primitives.is_empty() {
1399 queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
1400 }
1401
1402 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1403 label: Some("velox_wgpu_render_encoder"),
1404 });
1405 {
1406 let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1407 label: Some("velox_wgpu_render_pass"),
1408 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1409 view: target_view,
1410 depth_slice: None,
1411 resolve_target: None,
1412 ops: wgpu::Operations {
1413 load: wgpu::LoadOp::Clear(clear_color),
1414 store: wgpu::StoreOp::Store,
1415 },
1416 })],
1417 depth_stencil_attachment: None,
1418 occlusion_query_set: None,
1419 timestamp_writes: None,
1420 multiview_mask: None,
1421 });
1422 if !self.primitives.is_empty() {
1423 rpass.set_pipeline(&self.pipeline);
1424 rpass.set_bind_group(0, &self.bind_group, &[0]);
1425 rpass.draw(0..6, 0..(self.primitives.len() as u32));
1426 }
1427 }
1428 queue.submit([encoder.finish()]);
1429 }
1430
1431 #[allow(clippy::too_many_arguments)]
1435 pub fn render_to_view_dirty(
1436 &mut self,
1437 device: &wgpu::Device,
1438 queue: &wgpu::Queue,
1439 ops: &[DrawOp<'_>],
1440 viewport: Region,
1441 scale_factor: f32,
1442 target_view: &wgpu::TextureView,
1443 phys_width: u32,
1444 phys_height: u32,
1445 dirty_regions: &[Region],
1446 clear_color: wgpu::Color,
1447 ) {
1448 if dirty_regions.is_empty()
1449 || crate::renderers::software::ops_have_layers_or_blend(ops)
1450 {
1451 self.render_to_view(
1452 device,
1453 queue,
1454 ops,
1455 viewport,
1456 scale_factor,
1457 target_view,
1458 phys_width,
1459 phys_height,
1460 clear_color,
1461 );
1462 return;
1463 }
1464 let sf = scale_factor.clamp(0.5, 4.0);
1465 let pw = phys_width.max(1);
1466 let ph = phys_height.max(1);
1467
1468 let mut bind_group_dirty = false;
1469 for _attempt in 0..4 {
1470 match self.try_encode_ops(queue, ops, viewport, sf) {
1471 Ok(()) => break,
1472 Err(need) => {
1473 let (dirty, can_retry) = self.handle_atlas_grow(device, need);
1474 if dirty {
1475 bind_group_dirty = true;
1476 }
1477 if !can_retry {
1478 break;
1479 }
1480 }
1481 }
1482 }
1483 if self.primitives.len() > self.instance_capacity {
1484 self.instance_capacity = self.primitives.len().next_power_of_two();
1485 self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
1486 bind_group_dirty = true;
1487 }
1488 if bind_group_dirty {
1489 self.rebuild_bind_group(device);
1490 }
1491
1492 let slot0 = AlignedViewportSlot {
1493 uniform: ViewportUniform {
1494 size: [pw as f32, ph as f32],
1495 is_srgb: if self.target_is_srgb { 1.0 } else { 0.0 },
1496 _pad: 0.0,
1497 },
1498 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1499 };
1500 queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&[slot0]));
1501 if !self.primitives.is_empty() {
1502 queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
1503 }
1504
1505 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1506 label: Some("velox_wgpu_dirty_scissor_encoder"),
1507 });
1508 {
1509 let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1510 label: Some("velox_wgpu_dirty_scissor_pass"),
1511 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1512 view: target_view,
1513 depth_slice: None,
1514 resolve_target: None,
1515 ops: wgpu::Operations {
1516 load: wgpu::LoadOp::Load,
1517 store: wgpu::StoreOp::Store,
1518 },
1519 })],
1520 depth_stencil_attachment: None,
1521 occlusion_query_set: None,
1522 timestamp_writes: None,
1523 multiview_mask: None,
1524 });
1525 if !self.primitives.is_empty() {
1526 rpass.set_pipeline(&self.pipeline);
1527 rpass.set_bind_group(0, &self.bind_group, &[0]);
1528 for &d in dirty_regions {
1529 let pd = snap_clip_region_scaled(d.intersect(viewport), sf);
1530 let sx = (pd.x.max(0) as u32).min(pw);
1531 let sy = (pd.y.max(0) as u32).min(ph);
1532 let sw = (pd.w.max(0) as u32).min(pw.saturating_sub(sx));
1533 let sh = (pd.h.max(0) as u32).min(ph.saturating_sub(sy));
1534 if sw > 0 && sh > 0 {
1535 rpass.set_scissor_rect(sx, sy, sw, sh);
1536 rpass.draw(0..6, 0..(self.primitives.len() as u32));
1537 }
1538 }
1539 }
1540 }
1541 queue.submit([encoder.finish()]);
1542 }
1543
1544 #[allow(clippy::too_many_arguments)]
1545 fn render_to_view_multi_pass(
1546 &mut self,
1547 device: &wgpu::Device,
1548 queue: &wgpu::Queue,
1549 ops: &[DrawOp<'_>],
1550 viewport: Region,
1551 scale_factor: f32,
1552 target_view: &wgpu::TextureView,
1553 phys_width: u32,
1554 phys_height: u32,
1555 clear_color: wgpu::Color,
1556 ) {
1557 let pw = phys_width.max(1);
1558 let ph = phys_height.max(1);
1559 let sf = scale_factor.clamp(0.5, 4.0);
1560 let use_ttf = crate::display::ttf_atlas::has_system_font();
1561 let is_srgb = self.target_is_srgb;
1562
1563 if self.effects.is_none() {
1564 self.effects = Some(GpuEffectsEngine::new(device, queue, self.target_format));
1565 }
1566
1567 let mut bind_group_dirty = false;
1568 for _attempt in 0..4 {
1569 match self.try_plan_multi_pass(device, queue, ops, viewport, sf, use_ttf, pw, ph, clear_color, is_srgb) {
1570 Ok(()) => break,
1571 Err(need) => {
1572 let (dirty, can_retry) = self.handle_atlas_grow(device, need);
1573 if dirty {
1574 bind_group_dirty = true;
1575 }
1576 if !can_retry {
1577 break;
1578 }
1579 }
1580 }
1581 }
1582
1583 if self.primitives.len() > self.instance_capacity {
1584 self.instance_capacity = self.primitives.len().next_power_of_two();
1585 self.instance_buf = Self::create_instance_buffer(device, self.instance_capacity);
1586 bind_group_dirty = true;
1587 }
1588 if self.viewport_slots.len() > self.viewport_capacity {
1589 self.viewport_capacity = self.viewport_slots.len().next_power_of_two();
1590 self.viewport_buf = Self::create_viewport_buffer(device, self.viewport_capacity);
1591 bind_group_dirty = true;
1592 }
1593 if bind_group_dirty {
1594 self.rebuild_bind_group(device);
1595 }
1596
1597 if !self.viewport_slots.is_empty() {
1598 queue.write_buffer(&self.viewport_buf, 0, pod_as_bytes(&self.viewport_slots));
1599 }
1600 if !self.primitives.is_empty() {
1601 queue.write_buffer(&self.instance_buf, 0, pod_as_bytes(&self.primitives));
1602 }
1603
1604 let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
1605 label: Some("velox_wgpu_multi_pass_encoder"),
1606 });
1607 if let Some(ref mut fx) = self.effects {
1608 fx.execute_steps(
1609 device,
1610 queue,
1611 &mut encoder,
1612 &self.pipeline,
1613 &self.bind_group,
1614 &self.linear_sampler,
1615 &self.external_textures,
1616 target_view,
1617 );
1618 }
1619 queue.submit([encoder.finish()]);
1620 }
1621
1622 #[allow(clippy::too_many_arguments)]
1623 fn try_plan_multi_pass(
1624 &mut self,
1625 device: &wgpu::Device,
1626 queue: &wgpu::Queue,
1627 ops: &[DrawOp<'_>],
1628 viewport: Region,
1629 sf: f32,
1630 use_ttf: bool,
1631 pw: u32,
1632 ph: u32,
1633 clear_color: wgpu::Color,
1634 is_srgb: bool,
1635 ) -> Result<(), AtlasGrowNeed> {
1636 struct LayerFrame<'a> {
1637 tex_idx: usize,
1638 active_w: u32,
1639 active_h: u32,
1640 origin_x: f32,
1641 origin_y: f32,
1642 viewport_slot: u32,
1643 cleared: bool,
1644 clear_col: wgpu::Color,
1645 batch_start: u32,
1646 spec: Option<&'a LayerSpec<'a>>,
1647 body_phys: Region,
1648 buf_rect: Region,
1649 parent_clip_phys: Region,
1650 }
1651
1652 self.primitives.clear();
1653 self.viewport_slots.clear();
1654 let mut fx = self.effects.take().expect("effects engine initialized");
1655 fx.begin_frame();
1656
1657 let root_idx = fx.pool.acquire(device, pw, ph);
1658 let root_tex_sz = (fx.pool.get(root_idx).width, fx.pool.get(root_idx).height);
1659 let root_vp_slot = 0u32;
1660 self.viewport_slots.push(AlignedViewportSlot {
1661 uniform: ViewportUniform {
1662 size: [root_tex_sz.0 as f32, root_tex_sz.1 as f32],
1663 is_srgb: if is_srgb { 1.0 } else { 0.0 },
1664 _pad: 0.0,
1665 },
1666 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1667 });
1668
1669 let mut stack: Vec<LayerFrame<'_>> = Vec::with_capacity(8);
1670 stack.push(LayerFrame {
1671 tex_idx: root_idx,
1672 active_w: pw,
1673 active_h: ph,
1674 origin_x: 0.0,
1675 origin_y: 0.0,
1676 viewport_slot: root_vp_slot,
1677 cleared: false,
1678 clear_col: clear_color,
1679 batch_start: 0,
1680 spec: None,
1681 body_phys: Region::new(0, 0, pw as i16, ph as i16),
1682 buf_rect: Region::new(0, 0, pw as i16, ph as i16),
1683 parent_clip_phys: Region::new(0, 0, pw as i16, ph as i16),
1684 });
1685
1686 let flush_top = |stack: &mut [LayerFrame<'_>], fx: &mut GpuEffectsEngine, prim_len: u32| {
1687 let Some(top) = stack.last_mut() else {
1688 return;
1689 };
1690 if !top.cleared || prim_len > top.batch_start {
1691 let clear = if !top.cleared {
1692 top.cleared = true;
1693 Some(top.clear_col)
1694 } else {
1695 None
1696 };
1697 fx.steps.push(GpuPassStep::DrawBatch {
1698 target_idx: top.tex_idx,
1699 clear,
1700 viewport_slot: top.viewport_slot,
1701 prim_start: top.batch_start,
1702 prim_end: prim_len,
1703 });
1704 top.batch_start = prim_len;
1705 }
1706 };
1707
1708 let result: Result<(), AtlasGrowNeed> = (|| {
1709 for op in ops {
1710 match op.payload {
1711 DrawPayload::PushLayer(spec) => {
1712 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
1713 let parent = stack.last().unwrap();
1714 let parent_idx = parent.tex_idx;
1715 let parent_aw = parent.active_w;
1716 let parent_ah = parent.active_h;
1717 let parent_ox = parent.origin_x;
1718 let parent_oy = parent.origin_y;
1719 let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
1720
1721 let body_phys = snap_bounds_region_scaled(spec.bounds, sf);
1722 let parent_clip_phys = snap_clip_region_scaled(op.clip, sf);
1723
1724 if !spec.backdrop_filter.is_empty() && !body_phys.is_empty() {
1726 let bd = spec.backdrop_filter;
1727 let blur_px = (bd.blur_radius as f32) * sf;
1728 let pad = (blur_px * 2.0).ceil() as i16;
1729 let local_body = Region::new(
1730 body_phys.x.saturating_sub(parent_ox as i16),
1731 body_phys.y.saturating_sub(parent_oy as i16),
1732 body_phys.w,
1733 body_phys.h,
1734 );
1735 let raw_sample = Region::new(
1736 local_body.x.saturating_sub(pad),
1737 local_body.y.saturating_sub(pad),
1738 local_body.w.saturating_add(pad.saturating_mul(2)),
1739 local_body.h.saturating_add(pad.saturating_mul(2)),
1740 );
1741 let (sx, sy, sw, sh) = clamp_rect_u32(raw_sample, parent_aw, parent_ah);
1742 if sw > 0 && sh > 0 {
1743 let bd_raw = fx.pool.acquire(device, sw, sh);
1744 fx.steps.push(GpuPassStep::CopyRect {
1745 src_idx: parent_idx,
1746 src_origin: (sx, sy),
1747 dst_idx: bd_raw,
1748 dst_origin: (0, 0),
1749 size: (sw, sh),
1750 });
1751 let bd_blurred = if blur_px >= 0.5 {
1752 let b = fx.plan_kawase_blur(device, bd_raw, sw, sh, blur_px, is_srgb);
1753 if b != bd_raw {
1754 fx.pool.release(bd_raw);
1755 }
1756 b
1757 } else {
1758 bd_raw
1759 };
1760
1761 let dst_rect_bd = [
1762 local_body.x as f32,
1763 local_body.y as f32,
1764 local_body.w as f32,
1765 local_body.h as f32,
1766 ];
1767 let clip_rect_bd = [
1768 parent_clip_phys.x as f32 - parent_ox,
1769 parent_clip_phys.y as f32 - parent_oy,
1770 parent_clip_phys.right() as f32 - parent_ox,
1771 parent_clip_phys.bottom() as f32 - parent_oy,
1772 ];
1773 let (snap_idx, snap_ox, snap_oy, snap_tw, snap_th) = fx
1774 .acquire_subrect_snapshot(
1775 device,
1776 parent_idx,
1777 parent_aw,
1778 parent_ah,
1779 dst_rect_bd,
1780 clip_rect_bd,
1781 );
1782
1783 let bd_tex_sz = (fx.pool.get(bd_blurred).width, fx.pool.get(bd_blurred).height);
1784 let mut u = EffectUniform::default();
1785 u.tex_sizes = [
1786 parent_tex_sz.0 as f32,
1787 parent_tex_sz.1 as f32,
1788 bd_tex_sz.0 as f32,
1789 bd_tex_sz.1 as f32,
1790 ];
1791 u.dst_rect = dst_rect_bd;
1792 u.src_rect = [sx as f32, sy as f32, sw as f32, sh as f32];
1793 u.clip_rect = clip_rect_bd;
1794 u.body_rect = u.dst_rect;
1795 u.radii = [
1796 (spec.clip_radii.tl as f32) * sf,
1797 (spec.clip_radii.tr as f32) * sf,
1798 (spec.clip_radii.br as f32) * sf,
1799 (spec.clip_radii.bl as f32) * sf,
1800 ];
1801 u.params = [
1802 (spec.opacity as f32) * (1.0 / 255.0),
1803 0.0,
1804 EFFECT_KIND_BACKDROP,
1805 0.0,
1806 ];
1807 u.set_color_matrix(bd.color_matrix);
1808 u.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
1809 u.flags[2] = (bd.noise_amount as f32) * (1.0 / 255.0) * 0.12;
1810 u.flags[3] = if is_srgb { 1.0 } else { 0.0 };
1811 u.tint = color_to_f32(bd.tint);
1812 u.extra = [snap_ox, snap_oy, snap_tw, snap_th];
1813
1814 let slot = fx.push_slot(u);
1815 let mask_path = spec.clip_path.map(|p| {
1816 (
1817 std::string::String::from(p.as_str()),
1818 local_body.w.max(1) as u32,
1819 local_body.h.max(1) as u32,
1820 )
1821 });
1822 fx.steps.push(GpuPassStep::Effect {
1823 dst_idx: parent_idx,
1824 clear_dst: false,
1825 src_idx: bd_blurred,
1826 dst_snap_idx: snap_idx,
1827 mask_path,
1828 effect_slot: slot,
1829 use_hw_blend: false,
1830 });
1831 fx.pool.release(bd_blurred);
1832 fx.pool.release(snap_idx);
1833 }
1834 }
1835
1836 let (fl, ft, fr, fb) = spec.filter.outset();
1838 let pl = ((fl as f32) * sf).ceil() as i16;
1839 let pt = ((ft as f32) * sf).ceil() as i16;
1840 let pr = ((fr as f32) * sf).ceil() as i16;
1841 let pb = ((fb as f32) * sf).ceil() as i16;
1842 let buf_rect = Region::new(
1843 body_phys.x.saturating_sub(pl),
1844 body_phys.y.saturating_sub(pt),
1845 body_phys.w.saturating_add(pl).saturating_add(pr).max(1),
1846 body_phys.h.saturating_add(pt).saturating_add(pb).max(1),
1847 );
1848 let lw = buf_rect.w.max(1) as u32;
1849 let lh = buf_rect.h.max(1) as u32;
1850 let layer_tex = fx.pool.acquire(device, lw, lh);
1851 let ltex_sz = (fx.pool.get(layer_tex).width, fx.pool.get(layer_tex).height);
1852 let vp_slot = self.viewport_slots.len() as u32;
1853 self.viewport_slots.push(AlignedViewportSlot {
1854 uniform: ViewportUniform {
1855 size: [ltex_sz.0 as f32, ltex_sz.1 as f32],
1856 is_srgb: if is_srgb { 1.0 } else { 0.0 },
1857 _pad: 0.0,
1858 },
1859 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
1860 });
1861
1862 stack.push(LayerFrame {
1863 tex_idx: layer_tex,
1864 active_w: lw,
1865 active_h: lh,
1866 origin_x: buf_rect.x as f32,
1867 origin_y: buf_rect.y as f32,
1868 viewport_slot: vp_slot,
1869 cleared: false,
1870 clear_col: wgpu::Color::TRANSPARENT,
1871 batch_start: self.primitives.len() as u32,
1872 spec: Some(spec),
1873 body_phys,
1874 buf_rect,
1875 parent_clip_phys,
1876 });
1877 }
1878
1879 DrawPayload::PopLayer => {
1880 if stack.len() <= 1 {
1881 continue;
1882 }
1883 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
1884 let layer = stack.pop().unwrap();
1885 if let Some(parent_mut) = stack.last_mut() {
1886 parent_mut.batch_start = self.primitives.len() as u32;
1887 }
1888 let Some(spec) = layer.spec else {
1889 continue;
1890 };
1891 let parent = stack.last().unwrap();
1892 let parent_idx = parent.tex_idx;
1893 let parent_aw = parent.active_w;
1894 let parent_ah = parent.active_h;
1895 let parent_ox = parent.origin_x;
1896 let parent_oy = parent.origin_y;
1897 let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
1898
1899 let local_buf = [
1900 layer.buf_rect.x as f32 - parent_ox,
1901 layer.buf_rect.y as f32 - parent_oy,
1902 layer.buf_rect.w as f32,
1903 layer.buf_rect.h as f32,
1904 ];
1905 let local_body = [
1906 layer.body_phys.x as f32 - parent_ox,
1907 layer.body_phys.y as f32 - parent_oy,
1908 layer.body_phys.w as f32,
1909 layer.body_phys.h as f32,
1910 ];
1911 let clip_f = [
1912 layer.parent_clip_phys.x as f32 - parent_ox,
1913 layer.parent_clip_phys.y as f32 - parent_oy,
1914 layer.parent_clip_phys.right() as f32 - parent_ox,
1915 layer.parent_clip_phys.bottom() as f32 - parent_oy,
1916 ];
1917
1918 let dst_rect = if let Some(mut t) = spec.transform {
1920 if !t.is_identity() {
1921 t.e *= sf;
1922 t.f *= sf;
1923 let cx = local_body[0] + local_body[2] * 0.5;
1924 let cy = local_body[1] + local_body[3] * 0.5;
1925 let xreg = t.centered_at(cx, cy).transform_region(Region::new(
1926 local_buf[0] as i16,
1927 local_buf[1] as i16,
1928 local_buf[2] as i16,
1929 local_buf[3] as i16,
1930 ));
1931 [xreg.x as f32, xreg.y as f32, xreg.w as f32, xreg.h as f32]
1932 } else {
1933 local_buf
1934 }
1935 } else {
1936 local_buf
1937 };
1938
1939 if let Some(ds) = spec.filter.drop_shadow {
1941 if ds.is_active() {
1942 let sh_raw = fx.pool.acquire(device, layer.active_w, layer.active_h);
1943 let lsz = (fx.pool.get(layer.tex_idx).width, fx.pool.get(layer.tex_idx).height);
1944 let sh_sz = (fx.pool.get(sh_raw).width, fx.pool.get(sh_raw).height);
1945 let mut eu = EffectUniform::default();
1946 eu.tex_sizes = [sh_sz.0 as f32, sh_sz.1 as f32, lsz.0 as f32, lsz.1 as f32];
1947 eu.dst_rect = [0.0, 0.0, layer.active_w as f32, layer.active_h as f32];
1948 eu.src_rect = eu.dst_rect;
1949 eu.body_rect = [
1950 (layer.body_phys.x - layer.buf_rect.x) as f32,
1951 (layer.body_phys.y - layer.buf_rect.y) as f32,
1952 layer.body_phys.w as f32,
1953 layer.body_phys.h as f32,
1954 ];
1955 eu.params = [1.0, 0.0, EFFECT_KIND_SHADOW_EXTRACT, 0.0];
1956 eu.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
1957 eu.flags[3] = if is_srgb { 1.0 } else { 0.0 };
1958 eu.tint = color_to_f32(ds.color);
1959 let eslot = fx.push_slot(eu);
1960 let sh_mask = spec.clip_path.map(|p| {
1961 (
1962 std::string::String::from(p.as_str()),
1963 layer.body_phys.w.max(1) as u32,
1964 layer.body_phys.h.max(1) as u32,
1965 )
1966 });
1967 fx.steps.push(GpuPassStep::Effect {
1968 dst_idx: sh_raw,
1969 clear_dst: true,
1970 src_idx: layer.tex_idx,
1971 dst_snap_idx: layer.tex_idx,
1972 mask_path: sh_mask,
1973 effect_slot: eslot,
1974 use_hw_blend: false,
1975 });
1976
1977 let ds_blur = (ds.blur as f32) * sf;
1978 let sh_final = if ds_blur >= 0.5 {
1979 let b = fx.plan_kawase_blur(
1980 device,
1981 sh_raw,
1982 layer.active_w,
1983 layer.active_h,
1984 ds_blur,
1985 is_srgb,
1986 );
1987 if b != sh_raw {
1988 fx.pool.release(sh_raw);
1989 }
1990 b
1991 } else {
1992 sh_raw
1993 };
1994
1995 let sh_tex_sz = (fx.pool.get(sh_final).width, fx.pool.get(sh_final).height);
1996 let ox = (ds.offset_x as f32) * sf;
1997 let oy = (ds.offset_y as f32) * sf;
1998 let sh_dst_rect = [
1999 dst_rect[0] + ox,
2000 dst_rect[1] + oy,
2001 dst_rect[2],
2002 dst_rect[3],
2003 ];
2004 let sh_hw_blend = spec.blend_mode.is_normal();
2005 let (sh_snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if sh_hw_blend {
2006 (None, 0.0, 0.0, 1.0, 1.0)
2007 } else {
2008 let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
2009 device,
2010 parent_idx,
2011 parent_aw,
2012 parent_ah,
2013 sh_dst_rect,
2014 clip_f,
2015 );
2016 (Some(sidx), sx0, sy0, stw, sth)
2017 };
2018
2019 let mut cu = EffectUniform::default();
2020 cu.tex_sizes = [
2021 parent_tex_sz.0 as f32,
2022 parent_tex_sz.1 as f32,
2023 sh_tex_sz.0 as f32,
2024 sh_tex_sz.1 as f32,
2025 ];
2026 cu.dst_rect = sh_dst_rect;
2027 cu.src_rect = local_buf;
2028 cu.clip_rect = clip_f;
2029 cu.body_rect = local_body;
2030 cu.params = [
2031 (spec.opacity as f32) * (1.0 / 255.0),
2032 if sh_hw_blend {
2033 -1.0
2034 } else {
2035 spec.blend_mode as u8 as f32
2036 },
2037 EFFECT_KIND_COMPOSITE,
2038 0.0,
2039 ];
2040 cu.set_color_matrix(None);
2041 cu.set_transform(spec.transform, sf);
2042 cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
2043 cu.extra[0] += ox;
2044 cu.extra[1] += oy;
2045 cu.extra[2] = snap_tw;
2046 cu.extra[3] = snap_th;
2047 let cslot = fx.push_slot(cu);
2048 fx.steps.push(GpuPassStep::Effect {
2049 dst_idx: parent_idx,
2050 clear_dst: false,
2051 src_idx: sh_final,
2052 dst_snap_idx: sh_snap_opt.unwrap_or(sh_final),
2053 mask_path: None,
2054 effect_slot: cslot,
2055 use_hw_blend: sh_hw_blend,
2056 });
2057 fx.pool.release(sh_final);
2058 if let Some(sidx) = sh_snap_opt {
2059 fx.pool.release(sidx);
2060 }
2061 }
2062 }
2063
2064 let blur_px = (spec.filter.blur_radius as f32) * sf;
2066 let src_final = if blur_px >= 0.5 {
2067 let b = fx.plan_kawase_blur(
2068 device,
2069 layer.tex_idx,
2070 layer.active_w,
2071 layer.active_h,
2072 blur_px,
2073 is_srgb,
2074 );
2075 if b != layer.tex_idx {
2076 fx.pool.release(layer.tex_idx);
2077 }
2078 b
2079 } else {
2080 layer.tex_idx
2081 };
2082
2083 let use_hw_blend = spec.blend_mode.is_normal();
2085 let (snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if use_hw_blend {
2086 (None, 0.0, 0.0, 1.0, 1.0)
2087 } else {
2088 let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
2089 device,
2090 parent_idx,
2091 parent_aw,
2092 parent_ah,
2093 dst_rect,
2094 clip_f,
2095 );
2096 (Some(sidx), sx0, sy0, stw, sth)
2097 };
2098 let src_tex_sz = (fx.pool.get(src_final).width, fx.pool.get(src_final).height);
2099
2100 let mut cu = EffectUniform::default();
2101 cu.tex_sizes = [
2102 parent_tex_sz.0 as f32,
2103 parent_tex_sz.1 as f32,
2104 src_tex_sz.0 as f32,
2105 src_tex_sz.1 as f32,
2106 ];
2107 cu.dst_rect = dst_rect;
2108 cu.src_rect = local_buf;
2109 cu.clip_rect = clip_f;
2110 cu.body_rect = local_body;
2111 cu.radii = [
2112 (spec.clip_radii.tl as f32) * sf,
2113 (spec.clip_radii.tr as f32) * sf,
2114 (spec.clip_radii.br as f32) * sf,
2115 (spec.clip_radii.bl as f32) * sf,
2116 ];
2117 cu.params = [
2118 (spec.opacity as f32) * (1.0 / 255.0),
2119 if use_hw_blend {
2120 -1.0
2121 } else {
2122 spec.blend_mode as u8 as f32
2123 },
2124 EFFECT_KIND_COMPOSITE,
2125 0.0,
2126 ];
2127 cu.set_color_matrix(spec.filter.color_matrix);
2128 cu.flags[1] = if spec.clip_path.is_some() { 1.0 } else { 0.0 };
2129 cu.flags[3] = if is_srgb { 1.0 } else { 0.0 };
2130 cu.set_transform(spec.transform, sf);
2131 cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
2132 cu.extra[2] = snap_tw;
2133 cu.extra[3] = snap_th;
2134 let cslot = fx.push_slot(cu);
2135
2136 let mask_path = spec.clip_path.map(|p| {
2137 (
2138 std::string::String::from(p.as_str()),
2139 layer.body_phys.w.max(1) as u32,
2140 layer.body_phys.h.max(1) as u32,
2141 )
2142 });
2143 fx.steps.push(GpuPassStep::Effect {
2144 dst_idx: parent_idx,
2145 clear_dst: false,
2146 src_idx: src_final,
2147 dst_snap_idx: snap_opt.unwrap_or(src_final),
2148 mask_path,
2149 effect_slot: cslot,
2150 use_hw_blend,
2151 });
2152 fx.pool.release(src_final);
2153 if let Some(sidx) = snap_opt {
2154 fx.pool.release(sidx);
2155 }
2156 }
2157
2158 DrawPayload::StyledQuad(sq) if !sq.blend_mode.is_normal() => {
2160 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
2161 let parent = stack.last().unwrap();
2162 let parent_idx = parent.tex_idx;
2163 let parent_aw = parent.active_w;
2164 let parent_ah = parent.active_h;
2165 let parent_ox = parent.origin_x;
2166 let parent_oy = parent.origin_y;
2167 let parent_tex_sz = (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
2168
2169 let body_phys = snap_bounds_region_scaled(op.bounds, sf);
2170 let buf_rect = if let Some(mut t) = sq.transform {
2171 if !t.is_identity() {
2172 t.e *= sf;
2173 t.f *= sf;
2174 let cx = body_phys.x as f32 + body_phys.w as f32 * 0.5;
2175 let cy = body_phys.y as f32 + body_phys.h as f32 * 0.5;
2176 t.centered_at(cx, cy).transform_region(body_phys)
2177 } else {
2178 body_phys
2179 }
2180 } else {
2181 body_phys
2182 };
2183 let lw = buf_rect.w.max(1) as u32;
2184 let lh = buf_rect.h.max(1) as u32;
2185 let tmp_tex = fx.pool.acquire(device, lw, lh);
2186 let tmp_sz = (fx.pool.get(tmp_tex).width, fx.pool.get(tmp_tex).height);
2187 let vp_slot = self.viewport_slots.len() as u32;
2188 self.viewport_slots.push(AlignedViewportSlot {
2189 uniform: ViewportUniform {
2190 size: [tmp_sz.0 as f32, tmp_sz.1 as f32],
2191 is_srgb: if is_srgb { 1.0 } else { 0.0 },
2192 _pad: 0.0,
2193 },
2194 _pad: [0u8; 256 - core::mem::size_of::<ViewportUniform>()],
2195 });
2196
2197 let normal_sq = StyledQuad {
2198 blend_mode: BlendMode::SrcOver,
2199 ..*sq
2200 };
2201 let tmp_op = DrawOp {
2202 payload: DrawPayload::StyledQuad(&normal_sq),
2203 ..*op
2204 };
2205 let pstart = self.primitives.len() as u32;
2206 self.encode_single_op(
2207 queue,
2208 &tmp_op,
2209 op.clip,
2210 viewport,
2211 sf,
2212 use_ttf,
2213 buf_rect.x as f32,
2214 buf_rect.y as f32,
2215 )?;
2216 let pend = self.primitives.len() as u32;
2217 fx.steps.push(GpuPassStep::DrawBatch {
2218 target_idx: tmp_tex,
2219 clear: Some(wgpu::Color::TRANSPARENT),
2220 viewport_slot: vp_slot,
2221 prim_start: pstart,
2222 prim_end: pend,
2223 });
2224 if let Some(top) = stack.last_mut() {
2225 top.batch_start = pend;
2226 }
2227
2228 let clip_phys = snap_clip_region_scaled(op.clip, sf);
2229 let local_buf = [
2230 buf_rect.x as f32 - parent_ox,
2231 buf_rect.y as f32 - parent_oy,
2232 buf_rect.w as f32,
2233 buf_rect.h as f32,
2234 ];
2235 let clip_f = [
2236 clip_phys.x as f32 - parent_ox,
2237 clip_phys.y as f32 - parent_oy,
2238 clip_phys.right() as f32 - parent_ox,
2239 clip_phys.bottom() as f32 - parent_oy,
2240 ];
2241 let (snap_idx, snap_ox, snap_oy, snap_tw, snap_th) = fx
2242 .acquire_subrect_snapshot(
2243 device,
2244 parent_idx,
2245 parent_aw,
2246 parent_ah,
2247 local_buf,
2248 clip_f,
2249 );
2250 let mut cu = EffectUniform::default();
2251 cu.tex_sizes = [
2252 parent_tex_sz.0 as f32,
2253 parent_tex_sz.1 as f32,
2254 tmp_sz.0 as f32,
2255 tmp_sz.1 as f32,
2256 ];
2257 cu.dst_rect = local_buf;
2258 cu.src_rect = local_buf;
2259 cu.clip_rect = clip_f;
2260 cu.body_rect = local_buf;
2261 cu.params = [1.0, sq.blend_mode as u8 as f32, EFFECT_KIND_COMPOSITE, 0.0];
2262 cu.set_color_matrix(None);
2263 cu.tint = [snap_ox, snap_oy, 0.0, 0.0];
2264 cu.inv_xform = [1.0, 0.0, 0.0, 1.0];
2265 cu.extra = [0.0, 0.0, snap_tw, snap_th];
2266 let cslot = fx.push_slot(cu);
2267 fx.steps.push(GpuPassStep::Effect {
2268 dst_idx: parent_idx,
2269 clear_dst: false,
2270 src_idx: tmp_tex,
2271 dst_snap_idx: snap_idx,
2272 mask_path: None,
2273 effect_slot: cslot,
2274 use_hw_blend: false,
2275 });
2276 fx.pool.release(tmp_tex);
2277 fx.pool.release(snap_idx);
2278 }
2279
2280 DrawPayload::ExternalTexture(ext) => {
2282 let raw_clip = viewport.intersect(op.clip).intersect(op.bounds);
2283 if raw_clip.is_empty() {
2284 continue;
2285 }
2286 if self.external_textures.contains_key(&ext.id) {
2287 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
2288 let parent = stack.last().unwrap();
2289 let parent_idx = parent.tex_idx;
2290 let parent_aw = parent.active_w;
2291 let parent_ah = parent.active_h;
2292 let parent_ox = parent.origin_x;
2293 let parent_oy = parent.origin_y;
2294 let parent_tex_sz =
2295 (fx.pool.get(parent_idx).width, fx.pool.get(parent_idx).height);
2296
2297 let body_phys = snap_bounds_region_scaled(op.bounds, sf);
2298 let clip_phys = snap_clip_region_scaled(raw_clip, sf);
2299 let local_body = [
2300 body_phys.x as f32 - parent_ox,
2301 body_phys.y as f32 - parent_oy,
2302 body_phys.w as f32,
2303 body_phys.h as f32,
2304 ];
2305 let clip_f = [
2306 clip_phys.x as f32 - parent_ox,
2307 clip_phys.y as f32 - parent_oy,
2308 clip_phys.right() as f32 - parent_ox,
2309 clip_phys.bottom() as f32 - parent_oy,
2310 ];
2311
2312 let use_hw_blend = ext.blend_mode.is_normal();
2313 let (snap_opt, snap_ox, snap_oy, snap_tw, snap_th) = if use_hw_blend {
2314 (None, 0.0, 0.0, 1.0, 1.0)
2315 } else {
2316 let (sidx, sx0, sy0, stw, sth) = fx.acquire_subrect_snapshot(
2317 device,
2318 parent_idx,
2319 parent_aw,
2320 parent_ah,
2321 local_body,
2322 clip_f,
2323 );
2324 (Some(sidx), sx0, sy0, stw, sth)
2325 };
2326
2327 let mut eu = EffectUniform::default();
2328 eu.tex_sizes = [
2329 parent_tex_sz.0 as f32,
2330 parent_tex_sz.1 as f32,
2331 1.0,
2332 1.0,
2333 ];
2334 eu.dst_rect = local_body;
2335 eu.src_rect = ext.uv_rect;
2336 eu.clip_rect = clip_f;
2337 eu.body_rect = local_body;
2338 eu.radii = [
2339 (ext.radii.tl as f32) * sf,
2340 (ext.radii.tr as f32) * sf,
2341 (ext.radii.br as f32) * sf,
2342 (ext.radii.bl as f32) * sf,
2343 ];
2344 eu.params = [
2345 (ext.opacity as f32) * (1.0 / 255.0),
2346 if use_hw_blend {
2347 -1.0
2348 } else {
2349 ext.blend_mode as u8 as f32
2350 },
2351 EFFECT_KIND_EXTERNAL_TEX,
2352 0.0,
2353 ];
2354 eu.flags = [
2355 if ext.premultiplied { 1.0 } else { 0.0 },
2356 0.0,
2357 0.0,
2358 if is_srgb { 1.0 } else { 0.0 },
2359 ];
2360 eu.inv_xform = [1.0, 0.0, 0.0, 1.0];
2361 eu.extra = [snap_ox, snap_oy, snap_tw, snap_th];
2362 let eslot = fx.push_slot(eu);
2363
2364 fx.steps.push(GpuPassStep::DrawExternal {
2365 dst_idx: parent_idx,
2366 dst_snap_idx: snap_opt.unwrap_or(root_idx),
2367 tex_id: ext.id,
2368 effect_slot: eslot,
2369 use_hw_blend,
2370 });
2371 if let Some(sidx) = snap_opt {
2372 fx.pool.release(sidx);
2373 }
2374 } else if ext.fallback_bg.a() > 0 {
2375 let fallback_sq = StyledQuad {
2376 paint: Paint::Solid(ext.fallback_bg),
2377 border_color: Color::TRANSPARENT,
2378 border_width: 0,
2379 radii: ext.radii,
2380 opacity: ext.opacity,
2381 blend_mode: BlendMode::SrcOver,
2382 transform: None,
2383 };
2384 let tmp_op = DrawOp {
2385 payload: DrawPayload::StyledQuad(&fallback_sq),
2386 ..*op
2387 };
2388 let (ox, oy) = {
2389 let top = stack.last().unwrap();
2390 (top.origin_x, top.origin_y)
2391 };
2392 self.encode_single_op(
2393 queue, &tmp_op, raw_clip, viewport, sf, use_ttf, ox, oy,
2394 )?;
2395 }
2396 }
2397
2398 _ => {
2399 let raw_clip = match op.payload {
2400 DrawPayload::StyledQuad(sq) if sq.transform.is_some() => {
2401 viewport.intersect(op.clip)
2402 }
2403 _ => viewport.intersect(op.clip).intersect(op.bounds),
2404 };
2405 if raw_clip.is_empty() {
2406 continue;
2407 }
2408 let (ox, oy) = {
2409 let top = stack.last().unwrap();
2410 (top.origin_x, top.origin_y)
2411 };
2412 self.encode_single_op(queue, op, raw_clip, viewport, sf, use_ttf, ox, oy)?;
2413 }
2414 }
2415 }
2416
2417 flush_top(&mut stack, &mut fx, self.primitives.len() as u32);
2419 let mut blit_u = EffectUniform::default();
2420 blit_u.tex_sizes = [pw as f32, ph as f32, root_tex_sz.0 as f32, root_tex_sz.1 as f32];
2421 blit_u.dst_rect = [0.0, 0.0, pw as f32, ph as f32];
2422 blit_u.src_rect = [0.0, 0.0, pw as f32, ph as f32];
2423 blit_u.params = [1.0, 0.0, EFFECT_KIND_BLIT, 0.0];
2424 let blit_slot = fx.push_slot(blit_u);
2425 fx.steps.push(GpuPassStep::BlitToTarget {
2426 src_idx: root_idx,
2427 effect_slot: blit_slot,
2428 });
2429 Ok(())
2430 })();
2431
2432 self.effects = Some(fx);
2433 result
2434 }
2435}