1use wgpu;
5
6use teksilo_canvas::RenderFrame;
7use teksilo_canvas::geometry::Transform2D;
8
9use teksilo_canvas::live_image::LiveTextureStats;
10use teksilo_canvas::live_image::internal::{LivePass, LivePassMode, QuadDecision};
11
12use crate::blur::{BlurPipelines, BlurPool};
13use crate::device_health::DeviceHealth;
14use crate::image_manager::ImageManager;
15use crate::live_texture::WgpuBackend;
16use crate::path_atlas::PathAtlas;
17use crate::stream_buffer::StreamBuffers;
18use crate::text_contrast::TextContrast;
19use crate::vertex::{AnimQuadVertex, QuadVertex, RectVertex, SdfVertex, ShadowVertex};
20
21const MAX_ANIM_SLOTS: usize = 128;
26
27pub struct Renderer {
29 device: wgpu::Device,
30 queue: wgpu::Queue,
31 max_texture_dimension: u32,
37 rect_pipeline: wgpu::RenderPipeline,
38 sdf_pipeline: wgpu::RenderPipeline,
39 quad_pipeline: wgpu::RenderPipeline,
40 text_contrast: TextContrast,
42 shadow_pipeline: wgpu::RenderPipeline,
43 path_gradient_pipeline: wgpu::RenderPipeline,
50 anim_proc_pipeline: wgpu::RenderPipeline,
54 anim_sprite_pipeline: wgpu::RenderPipeline,
62 anim_uniform_buffer: wgpu::Buffer,
67 anim_uniform_bind_group: wgpu::BindGroup,
69 atlas_texture: Option<AtlasTexture>,
70 path_atlas: PathAtlas,
71 path_atlas_texture: Option<AtlasTexture>,
72 image_manager: ImageManager,
73 streams: StreamBuffers,
78 blur_pipelines: BlurPipelines,
82 blur_pool: BlurPool,
86 quad_bind_group_layout: wgpu::BindGroupLayout,
91 blur_composite_sampler: wgpu::Sampler,
95 live: LivePass<WgpuBackend>,
98 #[cfg(any(debug_assertions, feature = "live-image-timings"))]
100 live_timings: crate::live_timings::LiveTimingRings,
101 last_submission: Option<wgpu::SubmissionIndex>,
104}
105
106impl Drop for Renderer {
107 fn drop(&mut self) {
110 if let Some(submission) = self.last_submission.take() {
111 crate::gpu_reclaim::flag_device(self.live.backend().health(), &self.device, submission);
112 }
113 }
114}
115
116struct AtlasTexture {
117 texture: wgpu::Texture,
118 bind_group: wgpu::BindGroup,
119 width: u32,
120 height: u32,
121}
122
123struct ActiveTarget {
130 intermediate: Option<crate::blur::AcquiredTexture>,
133 viewport_w: u32,
135 viewport_h: u32,
136 opened: bool,
139 pending_composites: Vec<PendingComposite>,
143 clip_stack: Vec<[u32; 4]>,
150 blur_bounds: Option<teksilo_canvas::Rect>,
154 blur_radius_logical: Option<f32>,
155 used_w: Option<u32>,
156 used_h: Option<u32>,
157 bucket_w: Option<u32>,
158 bucket_h: Option<u32>,
159}
160
161impl ActiveTarget {
162 fn surface(viewport_w: u32, viewport_h: u32) -> Self {
163 Self {
164 intermediate: None,
165 viewport_w,
166 viewport_h,
167 opened: false,
168 pending_composites: Vec::new(),
169 clip_stack: Vec::new(),
170 blur_bounds: None,
171 blur_radius_logical: None,
172 used_w: None,
173 used_h: None,
174 bucket_w: None,
175 bucket_h: None,
176 }
177 }
178}
179
180struct PendingComposite {
184 blurred_texture: crate::blur::AcquiredTexture,
185 used_w: u32,
186 used_h: u32,
187 bucket_w: u32,
188 bucket_h: u32,
189 bounds: teksilo_canvas::Rect,
190}
191
192impl Renderer {
193 pub fn new(
198 device: wgpu::Device,
199 queue: wgpu::Queue,
200 surface_format: wgpu::TextureFormat,
201 ) -> Self {
202 let health = DeviceHealth::install(&device);
203 Self::with_device_health(device, queue, surface_format, health)
204 }
205
206 pub fn with_device_health(
212 device: wgpu::Device,
213 queue: wgpu::Queue,
214 surface_format: wgpu::TextureFormat,
215 health: DeviceHealth,
216 ) -> Self {
217 let device_max_texture_dimension = device.limits().max_texture_dimension_2d;
220 let rect_pipeline = create_rect_pipeline(&device, surface_format);
221 let sdf_pipeline = create_sdf_pipeline(&device, surface_format);
222 let quad_pipeline = create_quad_pipeline(&device, surface_format);
223 let path_gradient_pipeline = create_path_gradient_pipeline(
227 &device,
228 surface_format,
229 &quad_pipeline.get_bind_group_layout(0),
230 );
231 let shadow_pipeline = create_shadow_pipeline(&device, surface_format);
232 let (anim_proc_pipeline, anim_uniform_buffer, anim_uniform_bind_group, anim_uniform_layout) =
233 create_anim_proc_pipeline(&device, surface_format);
234 let quad_texture_layout = quad_pipeline.get_bind_group_layout(0);
238 let anim_sprite_pipeline = create_anim_sprite_pipeline(
239 &device,
240 surface_format,
241 &anim_uniform_layout,
242 &quad_texture_layout,
243 );
244
245 let quad_bind_group_layout = quad_pipeline.get_bind_group_layout(0);
246 let blur_pool = BlurPool::new(&device, surface_format);
247 let blur_pipelines =
248 BlurPipelines::new(&device, &blur_pool.bind_group_layout, surface_format);
249 let blur_composite_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
250 label: Some("blur_composite_sampler"),
251 address_mode_u: wgpu::AddressMode::ClampToEdge,
252 address_mode_v: wgpu::AddressMode::ClampToEdge,
253 address_mode_w: wgpu::AddressMode::ClampToEdge,
254 mag_filter: wgpu::FilterMode::Linear,
255 min_filter: wgpu::FilterMode::Linear,
256 mipmap_filter: wgpu::MipmapFilterMode::Nearest,
257 ..Default::default()
258 });
259
260 let live_textures = health.live_textures().clone();
261 let mut live = LivePass::new(WgpuBackend::new(
262 device.clone(),
263 queue.clone(),
264 quad_bind_group_layout.clone(),
265 health,
266 ));
267 live.join_device(&live_textures);
268
269 Self {
270 device,
271 queue,
272 max_texture_dimension: device_max_texture_dimension,
273 rect_pipeline,
274 sdf_pipeline,
275 quad_pipeline,
276 text_contrast: TextContrast::DEFAULT,
277 path_gradient_pipeline,
278 shadow_pipeline,
279 anim_proc_pipeline,
280 anim_sprite_pipeline,
281 anim_uniform_buffer,
282 anim_uniform_bind_group,
283 atlas_texture: None,
284 path_atlas: {
285 let mut atlas = PathAtlas::new(512, 512);
286 atlas.cap_max_size(device_max_texture_dimension);
287 atlas
288 },
289 path_atlas_texture: None,
290 image_manager: ImageManager::new(),
291 streams: StreamBuffers::new(),
292 blur_pipelines,
293 blur_pool,
294 quad_bind_group_layout,
295 blur_composite_sampler,
296 live,
297 #[cfg(any(debug_assertions, feature = "live-image-timings"))]
298 live_timings: crate::live_timings::LiveTimingRings::new(),
299 last_submission: None,
300 }
301 }
302
303 pub fn set_text_contrast(&mut self, text_contrast: TextContrast) {
306 self.text_contrast = text_contrast;
307 }
308
309 pub fn text_contrast(&self) -> TextContrast {
311 self.text_contrast
312 }
313
314 pub fn upload_atlas(&mut self, width: u32, height: u32, pixels: &[u8]) {
316 if width == 0 || height == 0 {
317 return;
318 }
319 if width > self.max_texture_dimension || height > self.max_texture_dimension {
327 eprintln!(
328 "teksilo-render: glyph atlas {width}x{height} exceeds this device's \
329 max texture dimension ({}); skipping upload",
330 self.max_texture_dimension
331 );
332 return;
333 }
334
335 let needs_recreate = self
336 .atlas_texture
337 .as_ref()
338 .is_none_or(|t| t.width != width || t.height != height);
339
340 if needs_recreate {
341 let texture = self.device.create_texture(&wgpu::TextureDescriptor {
342 label: Some("glyph_atlas"),
343 size: wgpu::Extent3d {
344 width,
345 height,
346 depth_or_array_layers: 1,
347 },
348 mip_level_count: 1,
349 sample_count: 1,
350 dimension: wgpu::TextureDimension::D2,
351 format: wgpu::TextureFormat::Rgba8UnormSrgb,
352 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
353 view_formats: &[],
354 });
355
356 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
357 let sampler = self.device.create_sampler(&wgpu::SamplerDescriptor {
369 mag_filter: wgpu::FilterMode::Linear,
370 min_filter: wgpu::FilterMode::Linear,
371 ..Default::default()
372 });
373
374 let bind_group_layout = self.quad_pipeline.get_bind_group_layout(0);
375 let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
376 label: Some("atlas_bind_group"),
377 layout: &bind_group_layout,
378 entries: &[
379 wgpu::BindGroupEntry {
380 binding: 0,
381 resource: wgpu::BindingResource::TextureView(&view),
382 },
383 wgpu::BindGroupEntry {
384 binding: 1,
385 resource: wgpu::BindingResource::Sampler(&sampler),
386 },
387 ],
388 });
389
390 self.atlas_texture = Some(AtlasTexture {
391 texture,
392 bind_group,
393 width,
394 height,
395 });
396 }
397
398 if let Some(atlas) = &self.atlas_texture {
399 self.queue.write_texture(
400 wgpu::TexelCopyTextureInfo {
401 texture: &atlas.texture,
402 mip_level: 0,
403 origin: wgpu::Origin3d::ZERO,
404 aspect: wgpu::TextureAspect::All,
405 },
406 pixels,
407 wgpu::TexelCopyBufferLayout {
408 offset: 0,
409 bytes_per_row: Some(width * 4),
410 rows_per_image: Some(height),
411 },
412 wgpu::Extent3d {
413 width,
414 height,
415 depth_or_array_layers: 1,
416 },
417 );
418 }
419 }
420
421 pub fn render(
427 &mut self,
428 frame: &RenderFrame,
429 view: &wgpu::TextureView,
430 scale_factor: f32,
431 viewport_width: u32,
432 viewport_height: u32,
433 clear_color: [f32; 4],
434 ) {
435 self.render_frame(
436 frame,
437 view,
438 scale_factor,
439 viewport_width,
440 viewport_height,
441 clear_color,
442 LivePassMode::Present,
443 );
444 }
445
446 pub fn render_capture(
452 &mut self,
453 frame: &RenderFrame,
454 view: &wgpu::TextureView,
455 scale_factor: f32,
456 viewport_width: u32,
457 viewport_height: u32,
458 clear_color: [f32; 4],
459 ) {
460 self.render_frame(
461 frame,
462 view,
463 scale_factor,
464 viewport_width,
465 viewport_height,
466 clear_color,
467 LivePassMode::Capture,
468 );
469 }
470
471 pub fn live_texture_stats(&self) -> LiveTextureStats {
473 self.live.stats()
474 }
475
476 #[cfg(any(debug_assertions, feature = "live-image-timings"))]
481 pub fn live_texture_timings(&self) -> crate::LiveImageTimings {
482 self.live_timings.timings()
483 }
484
485 #[doc(hidden)]
488 pub fn live_image_decisions(&self) -> &[QuadDecision] {
489 self.live.decisions()
490 }
491
492 #[doc(hidden)]
495 pub fn set_live_refresh_interval(&mut self, interval: std::time::Duration) {
496 self.live.set_refresh_interval(interval);
497 }
498
499 #[doc(hidden)]
501 pub fn live_refresh_interval(&self) -> std::time::Duration {
502 self.live.refresh_interval()
503 }
504
505 #[doc(hidden)]
509 pub fn set_live_max_dimension(&mut self, max: u32) {
510 self.live.backend_mut().set_max_dimension(max);
511 }
512
513 #[doc(hidden)]
514 pub fn set_live_band_bytes(&mut self, bytes: u64) {
515 self.live.set_band_bytes(bytes);
516 }
517
518 #[doc(hidden)]
519 pub fn set_live_staging_budget(&mut self, bytes: u64) {
520 self.live.set_staging_budget(bytes);
521 }
522
523 #[doc(hidden)]
524 pub fn set_live_park_budget(&mut self, bytes: u64) {
525 self.live.set_park_budget(bytes);
526 }
527
528 #[doc(hidden)]
529 pub fn fail_next_live_texture(&mut self) {
530 self.live.backend_mut().fail_next_create();
531 }
532
533 #[doc(hidden)]
537 pub fn live_staging_stats(&self) -> crate::live_staging::StagingStats {
538 self.live.backend().staging_stats()
539 }
540
541 #[doc(hidden)]
542 pub fn set_live_staging_idle_lifetime(&mut self, lifetime: std::time::Duration) {
543 self.live.backend_mut().set_staging_idle_lifetime(lifetime);
544 }
545
546 #[doc(hidden)]
547 pub fn fail_next_live_staging(&mut self) {
548 self.live.backend_mut().fail_next_staging();
549 }
550
551 #[doc(hidden)]
555 pub fn read_live_texture_level(
556 &self,
557 id: teksilo_canvas::live_image::LiveImageId,
558 level: u32,
559 ) -> Option<(u32, u32, Vec<u8>)> {
560 let texture = self.live.texture(id)?;
561 if level >= texture.levels() {
562 return None;
563 }
564 let (w, h) = texture.size();
565 let (lw, lh) = teksilo_canvas::live_image::internal::mip_level_size(w, h, level);
566 let pixels = crate::test_support::try_read_texture_level_rgba(
567 &self.device,
568 &self.queue,
569 &texture.texture,
570 level,
571 lw,
572 lh,
573 )
574 .ok()?;
575 Some((lw, lh, pixels))
576 }
577
578 #[doc(hidden)]
580 pub fn device_health(&self) -> &DeviceHealth {
581 self.live.backend().health()
582 }
583
584 #[allow(clippy::too_many_arguments)]
585 fn render_frame(
586 &mut self,
587 frame: &RenderFrame,
588 view: &wgpu::TextureView,
589 scale_factor: f32,
590 viewport_width: u32,
591 viewport_height: u32,
592 clear_color: [f32; 4],
593 mode: LivePassMode,
594 ) {
595 self.path_atlas.begin_frame();
597 self.blur_pool.begin_frame();
600 let blur_scopes = frame
601 .draw_order
602 .iter()
603 .filter(|c| matches!(c, teksilo_canvas::DrawCommand::BeginBlurredSubtree { .. }))
604 .count();
605 self.blur_pipelines.params.begin_frame(
606 &self.device,
607 u32::try_from(blur_scopes)
608 .unwrap_or(u32::MAX)
609 .saturating_mul(crate::blur::PARAM_SLOTS_PER_SCOPE),
610 );
611
612 for pending in &frame.pending_images {
614 if !self.image_manager.contains(&pending.name) {
615 let layout = self.quad_pipeline.get_bind_group_layout(0);
616 self.image_manager.register_image(
617 &pending.name,
618 pending.width,
619 pending.height,
620 &pending.pixels,
621 &self.device,
622 &self.queue,
623 &layout,
624 );
625 }
626 }
627
628 #[cfg(any(debug_assertions, feature = "live-image-timings"))]
631 let live_started = std::time::Instant::now();
632 self.live.prepare(&frame.live_images, mode);
633 #[cfg(any(debug_assertions, feature = "live-image-timings"))]
634 let live_prepared = live_started.elapsed();
635
636 let mut path_placements: Vec<Option<crate::path_atlas::PathPlacement>> =
648 vec![None; frame.paths.len()];
649 {
650 let mut ptf_stack: Vec<Transform2D> = vec![Transform2D::IDENTITY];
651 let mut ptf_current = Transform2D::IDENTITY;
652 let device_t = |t: &Transform2D| Transform2D {
653 m: [
654 t.m[0],
655 t.m[1],
656 t.m[2],
657 t.m[3],
658 t.m[4] * scale_factor,
659 t.m[5] * scale_factor,
660 ],
661 };
662 for cmd in &frame.draw_order {
663 match cmd {
664 teksilo_canvas::DrawCommand::SetTransform(t) => {
665 let stack_top = ptf_stack.last().copied().unwrap_or(Transform2D::IDENTITY);
666 ptf_current = device_t(t).then(&stack_top);
667 }
668 teksilo_canvas::DrawCommand::PushTransform(t) => {
669 let prev_top = ptf_stack.last().copied().unwrap_or(Transform2D::IDENTITY);
670 let new_top = device_t(t).then(&prev_top);
671 ptf_stack.push(new_top);
672 ptf_current = new_top;
673 }
674 teksilo_canvas::DrawCommand::PopTransform => {
675 if ptf_stack.len() > 1 {
676 ptf_stack.pop();
677 }
678 ptf_current = ptf_stack.last().copied().unwrap_or(Transform2D::IDENTITY);
679 }
680 teksilo_canvas::DrawCommand::Path(idx) => {
681 if let Some(entry) = frame.paths.get(*idx) {
682 let zoom = ptf_current.m[0].hypot(ptf_current.m[1]);
686 let snap = ptf_current == Transform2D::IDENTITY;
696 path_placements[*idx] = self.path_atlas.lookup_or_rasterize(
697 &entry.path,
698 &entry.stroke_style,
699 entry.fill_rule,
700 entry.bounds,
701 scale_factor,
702 zoom,
703 snap,
704 );
705 }
706 }
707 _ => {}
708 }
709 }
710 }
711
712 if self.path_atlas.is_dirty() {
714 let (pw, ph) = self.path_atlas.size();
715 self.upload_path_atlas(pw, ph, self.path_atlas.pixels().to_vec());
716 self.path_atlas.mark_clean();
717 }
718
719 let counts = stream_quad_counts(frame);
721 let StreamQuadCounts {
722 rect: rect_quads,
723 sdf: sdf_quads,
724 quad: quad_quads,
725 shadow: shadow_quads,
726 anim_proc: anim_proc_quads,
727 path_gradient: path_gradient_quads,
728 } = counts;
729 let max_quads = counts.max();
730
731 self.streams.rect.ensure_capacity(
732 &self.device,
733 (rect_quads * 4 * std::mem::size_of::<RectVertex>()) as u64,
734 );
735 self.streams.sdf.ensure_capacity(
736 &self.device,
737 (sdf_quads * 4 * std::mem::size_of::<SdfVertex>()) as u64,
738 );
739 self.streams.quad.ensure_capacity(
740 &self.device,
741 (quad_quads * 4 * std::mem::size_of::<QuadVertex>()) as u64,
742 );
743 self.streams.shadow.ensure_capacity(
744 &self.device,
745 (shadow_quads * 4 * std::mem::size_of::<ShadowVertex>()) as u64,
746 );
747 self.streams.anim_proc.ensure_capacity(
748 &self.device,
749 (anim_proc_quads * 4 * std::mem::size_of::<AnimQuadVertex>()) as u64,
750 );
751 self.streams.path_gradient.ensure_capacity(
752 &self.device,
753 (path_gradient_quads * 4 * std::mem::size_of::<crate::vertex::PathGradientVertex>())
754 as u64,
755 );
756 self.streams.index.ensure_capacity(
757 &self.device,
758 (max_quads * 6 * std::mem::size_of::<u32>()) as u64,
759 );
760 self.streams.reset();
761
762 if !frame.anim_params.is_empty() {
768 let n = frame.anim_params.len().min(MAX_ANIM_SLOTS);
769 debug_assert!(
770 frame.anim_params.len() <= MAX_ANIM_SLOTS,
771 "AnimParams exceeds MAX_ANIM_SLOTS ({}); tail will be dropped",
772 MAX_ANIM_SLOTS
773 );
774 let bytes: &[u8] = bytemuck::cast_slice(&frame.anim_params[..n]);
775 self.queue.write_buffer(&self.anim_uniform_buffer, 0, bytes);
776 }
777
778 let index_data: Vec<u32> = crate::vertex::generate_quad_indices(max_quads);
782 let index_binding = self
783 .streams
784 .index
785 .write(&self.queue, bytemuck::cast_slice(&index_data));
786
787 let mut encoder = self
788 .device
789 .create_command_encoder(&wgpu::CommandEncoderDescriptor {
790 label: Some("teksilo_render"),
791 });
792 #[cfg(any(debug_assertions, feature = "live-image-timings"))]
797 let mips_started = std::time::Instant::now();
798 self.live.backend_mut().encode(&mut encoder);
799 #[cfg(any(debug_assertions, feature = "live-image-timings"))]
800 self.live_timings.record(
801 (!frame.live_images.is_empty()).then(|| live_prepared + mips_started.elapsed()),
802 self.live.last_timings(),
803 );
804
805 let mut viewport_width = viewport_width;
809 let mut viewport_height = viewport_height;
810
811 {
812 let surface_clear_color = wgpu::Color {
813 r: clear_color[0] as f64,
814 g: clear_color[1] as f64,
815 b: clear_color[2] as f64,
816 a: clear_color[3] as f64,
817 };
818
819 let mut target_stack: Vec<ActiveTarget> =
830 vec![ActiveTarget::surface(viewport_width, viewport_height)];
831
832 let mut opacity_stack: Vec<f32> = vec![1.0];
834 let mut current_opacity: f32 = 1.0;
835
836 let mut blend_stack: Vec<teksilo_canvas::BlendMode> = Vec::new();
838 let mut current_blend = teksilo_canvas::BlendMode::Normal;
839 let _ = current_blend; let mut transform_stack: Vec<Transform2D> = vec![Transform2D::IDENTITY];
847 let mut current_transform = Transform2D::IDENTITY;
848
849 let mut rect_batch: Vec<RectVertex> = Vec::new();
854 let mut sdf_batch: Vec<SdfVertex> = Vec::new();
855 let mut quad_batch: Vec<QuadVertex> = Vec::new();
856 let text_params = self.text_contrast.packed();
857 let mut shadow_batch: Vec<ShadowVertex> = Vec::new();
858 let mut anim_proc_batch: Vec<AnimQuadVertex> = Vec::new();
859 let mut path_gradient_batch: Vec<crate::vertex::PathGradientVertex> = Vec::new();
860
861 #[derive(Clone, Copy, PartialEq, Eq)]
865 enum QuadSource {
866 GlyphAtlas,
867 PathAtlas,
868 }
869 let mut quad_source: Option<QuadSource> = None;
870
871 macro_rules! flush_stream {
879 ($pass:expr, $queue:expr, $stream:expr, $pipeline:expr,
880 $batch:expr, $index_binding:expr) => {
881 if !$batch.is_empty() {
882 let bytes: &[u8] = bytemuck::cast_slice(&$batch);
883 if let (Some((vb, v_off, v_len)), Some((ib, _, _))) =
884 ($stream.write($queue, bytes), $index_binding)
885 {
886 let quads = ($batch.len() / 4) as u32;
887 let index_count = quads * 6;
888 let index_bytes = (index_count as u64) * 4;
889 $pass.set_pipeline($pipeline);
890 $pass.set_vertex_buffer(0, vb.slice(v_off..v_off + v_len));
891 $pass.set_index_buffer(
892 ib.slice(0..index_bytes),
893 wgpu::IndexFormat::Uint32,
894 );
895 $pass.draw_indexed(0..index_count, 0, 0..1);
896 }
897 $batch.clear();
898 }
899 };
900 }
901
902 macro_rules! flush_all {
904 ($pass:expr, $queue:expr, $streams:expr,
905 $rp:expr, $sp:expr, $qp:expr, $pgp:expr, $shp:expr,
906 $rb:expr, $sb:expr, $qb:expr, $pgb:expr, $shb:expr,
907 $atlas:expr, $path_atlas:expr, $qs:expr, $index_binding:expr) => {
908 flush_stream!($pass, $queue, &$streams.rect, $rp, $rb, $index_binding);
909 flush_stream!($pass, $queue, &$streams.sdf, $sp, $sb, $index_binding);
910 if !$qb.is_empty() {
912 let bg = match $qs {
913 Some(QuadSource::PathAtlas) => {
914 $path_atlas.as_ref().map(|a: &AtlasTexture| &a.bind_group)
915 }
916 _ => $atlas.as_ref().map(|a: &AtlasTexture| &a.bind_group),
917 };
918 if let (Some(bind_group), Some((ib, _, _))) = (bg, $index_binding) {
919 let bytes: &[u8] = bytemuck::cast_slice(&$qb);
920 if let Some((vb, v_off, v_len)) = $streams.quad.write($queue, bytes) {
921 let quads = ($qb.len() / 4) as u32;
922 let index_count = quads * 6;
923 let index_bytes = (index_count as u64) * 4;
924 $pass.set_pipeline($qp);
925 $pass.set_bind_group(0, bind_group, &[]);
926 $pass.set_vertex_buffer(0, vb.slice(v_off..v_off + v_len));
927 $pass.set_index_buffer(
928 ib.slice(0..index_bytes),
929 wgpu::IndexFormat::Uint32,
930 );
931 $pass.draw_indexed(0..index_count, 0, 0..1);
932 }
933 }
934 $qb.clear();
935 }
936 if !$pgb.is_empty() {
942 if let (Some(bind_group), Some((ib, _, _))) = (
943 $path_atlas.as_ref().map(|a: &AtlasTexture| &a.bind_group),
944 $index_binding,
945 ) {
946 let bytes: &[u8] = bytemuck::cast_slice(&$pgb);
947 if let Some((vb, v_off, v_len)) =
948 $streams.path_gradient.write($queue, bytes)
949 {
950 let quads = ($pgb.len() / 4) as u32;
951 let index_count = quads * 6;
952 let index_bytes = (index_count as u64) * 4;
953 $pass.set_pipeline($pgp);
954 $pass.set_bind_group(0, bind_group, &[]);
955 $pass.set_vertex_buffer(0, vb.slice(v_off..v_off + v_len));
956 $pass.set_index_buffer(
957 ib.slice(0..index_bytes),
958 wgpu::IndexFormat::Uint32,
959 );
960 $pass.draw_indexed(0..index_count, 0, 0..1);
961 }
962 }
963 $pgb.clear();
964 }
965 flush_stream!($pass, $queue, &$streams.shadow, $shp, $shb, $index_binding);
966 if !anim_proc_batch.is_empty()
975 && let Some((ib, _, _)) = $index_binding
976 {
977 let bytes: &[u8] = bytemuck::cast_slice(&anim_proc_batch);
978 if let Some((vb, v_off, v_len)) = $streams.anim_proc.write($queue, bytes) {
979 let quads = (anim_proc_batch.len() / 4) as u32;
980 let index_count = quads * 6;
981 let index_bytes = (index_count as u64) * 4;
982 $pass.set_pipeline(&self.anim_proc_pipeline);
983 $pass.set_bind_group(0, &self.anim_uniform_bind_group, &[]);
984 $pass.set_vertex_buffer(0, vb.slice(v_off..v_off + v_len));
985 $pass.set_index_buffer(
986 ib.slice(0..index_bytes),
987 wgpu::IndexFormat::Uint32,
988 );
989 $pass.draw_indexed(0..index_count, 0, 0..1);
990 }
991 anim_proc_batch.clear();
992 }
993 };
994 }
995
996 let mut cmd_idx = 0;
1003 while cmd_idx <= frame.draw_order.len() {
1004 let (target_view, load_op): (&wgpu::TextureView, wgpu::LoadOp<wgpu::Color>) = {
1008 let t = target_stack
1009 .last_mut()
1010 .expect("surface target always present");
1011 let v: &wgpu::TextureView = match t.intermediate {
1012 Some(h) => self.blur_pool.view(h),
1013 None => view,
1014 };
1015 let lo = if t.opened {
1016 wgpu::LoadOp::Load
1017 } else if t.intermediate.is_none() {
1018 wgpu::LoadOp::Clear(surface_clear_color)
1019 } else {
1020 wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT)
1021 };
1022 t.opened = true;
1023 viewport_width = t.viewport_w;
1024 viewport_height = t.viewport_h;
1025 (v, lo)
1026 };
1027
1028 let composites_to_draw: Vec<PendingComposite> = std::mem::take(
1034 &mut target_stack
1035 .last_mut()
1036 .expect("target_stack always has the surface target")
1037 .pending_composites,
1038 );
1039
1040 {
1041 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
1042 label: Some("teksilo_segment_pass"),
1043 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
1044 view: target_view,
1045 resolve_target: None,
1046 ops: wgpu::Operations {
1047 load: load_op,
1048 store: wgpu::StoreOp::Store,
1049 },
1050 depth_slice: None,
1051 })],
1052 depth_stencil_attachment: None,
1053 timestamp_writes: None,
1054 occlusion_query_set: None,
1055 multiview_mask: None,
1056 });
1057
1058 if let Some(&[x, y, w, h]) = target_stack
1064 .last()
1065 .expect("target_stack always has the surface target")
1066 .clip_stack
1067 .last()
1068 {
1069 pass.set_scissor_rect(x, y, w, h);
1070 }
1071
1072 for pc in &composites_to_draw {
1074 composite_blur_quad(
1075 &self.device,
1076 &self.queue,
1077 &mut pass,
1078 &self.blur_pool,
1079 &self.quad_pipeline,
1080 &self.quad_bind_group_layout,
1081 &self.blur_composite_sampler,
1082 &self.streams.quad,
1083 index_binding,
1084 pc.blurred_texture,
1085 pc.used_w,
1086 pc.used_h,
1087 pc.bucket_w,
1088 pc.bucket_h,
1089 pc.bounds,
1090 scale_factor,
1091 viewport_width,
1092 viewport_height,
1093 );
1094 quad_source = None;
1099 }
1100
1101 let pass = &mut pass;
1102
1103 while cmd_idx < frame.draw_order.len() {
1106 let cmd = &frame.draw_order[cmd_idx];
1107 if matches!(
1108 cmd,
1109 teksilo_canvas::DrawCommand::BeginBlurredSubtree { .. }
1110 | teksilo_canvas::DrawCommand::EndBlurredSubtree
1111 ) {
1112 break;
1113 }
1114 match cmd {
1115 teksilo_canvas::DrawCommand::Decoration(idx) => {
1116 flush_all!(
1117 pass,
1118 &self.queue,
1119 self.streams,
1120 &self.rect_pipeline,
1121 &self.sdf_pipeline,
1122 &self.quad_pipeline,
1123 &self.path_gradient_pipeline,
1124 &self.shadow_pipeline,
1125 rect_batch,
1126 sdf_batch,
1127 quad_batch,
1128 path_gradient_batch,
1129 shadow_batch,
1130 self.atlas_texture,
1131 self.path_atlas_texture,
1132 quad_source,
1133 index_binding
1134 );
1135 quad_source = None;
1136 let Some(rect) = frame.decorations.get(*idx) else {
1137 continue;
1138 };
1139 let verts = RectVertex::from_decoration(rect, scale_factor);
1140 for v in &verts {
1141 let tp = apply_transform_pixel(v.position, ¤t_transform);
1142 rect_batch.push(RectVertex {
1143 position: pixel_to_ndc(tp, viewport_width, viewport_height),
1144 color: [
1145 v.color[0],
1146 v.color[1],
1147 v.color[2],
1148 v.color[3] * current_opacity,
1149 ],
1150 });
1151 }
1152 }
1153 teksilo_canvas::DrawCommand::CosmeticLine(idx) => {
1154 flush_all!(
1155 pass,
1156 &self.queue,
1157 self.streams,
1158 &self.rect_pipeline,
1159 &self.sdf_pipeline,
1160 &self.quad_pipeline,
1161 &self.path_gradient_pipeline,
1162 &self.shadow_pipeline,
1163 rect_batch,
1164 sdf_batch,
1165 quad_batch,
1166 path_gradient_batch,
1167 shadow_batch,
1168 self.atlas_texture,
1169 self.path_atlas_texture,
1170 quad_source,
1171 index_binding
1172 );
1173 quad_source = None;
1174 let Some(line) = frame.cosmetic_lines.get(*idx) else {
1175 continue;
1176 };
1177 let p0 = apply_transform_pixel(
1182 [line.from[0] * scale_factor, line.from[1] * scale_factor],
1183 ¤t_transform,
1184 );
1185 let p1 = apply_transform_pixel(
1186 [line.to[0] * scale_factor, line.to[1] * scale_factor],
1187 ¤t_transform,
1188 );
1189 let thickness = (line.width * scale_factor).max(1.0);
1190 let half = thickness * 0.5;
1191 let dx = p1[0] - p0[0];
1192 let dy = p1[1] - p0[1];
1193 let len = (dx * dx + dy * dy).sqrt();
1194 if len < 1e-3 {
1195 continue;
1196 }
1197 let nx = -dy / len;
1199 let ny = dx / len;
1200 let (mut a0, mut a1) = (p0, p1);
1203 if dy.abs() < 0.5 {
1204 let cy = ((p0[1] + p1[1]) * 0.5 - half).round() + half;
1205 a0 = [p0[0], cy];
1206 a1 = [p1[0], cy];
1207 } else if dx.abs() < 0.5 {
1208 let cx = ((p0[0] + p1[0]) * 0.5 - half).round() + half;
1209 a0 = [cx, p0[1]];
1210 a1 = [cx, p1[1]];
1211 }
1212 let lin = crate::vertex::srgb_to_linear_rgba(line.color);
1213 let color = [lin[0], lin[1], lin[2], lin[3] * current_opacity];
1214 let corners = [
1215 [a0[0] + nx * half, a0[1] + ny * half],
1216 [a1[0] + nx * half, a1[1] + ny * half],
1217 [a1[0] - nx * half, a1[1] - ny * half],
1218 [a0[0] - nx * half, a0[1] - ny * half],
1219 ];
1220 for pos in corners {
1221 rect_batch.push(RectVertex {
1222 position: pixel_to_ndc(
1223 pos,
1224 viewport_width,
1225 viewport_height,
1226 ),
1227 color,
1228 });
1229 }
1230 }
1231 teksilo_canvas::DrawCommand::Shape(idx) => {
1232 flush_all!(
1233 pass,
1234 &self.queue,
1235 self.streams,
1236 &self.rect_pipeline,
1237 &self.sdf_pipeline,
1238 &self.quad_pipeline,
1239 &self.path_gradient_pipeline,
1240 &self.shadow_pipeline,
1241 rect_batch,
1242 sdf_batch,
1243 quad_batch,
1244 path_gradient_batch,
1245 shadow_batch,
1246 self.atlas_texture,
1247 self.path_atlas_texture,
1248 quad_source,
1249 index_binding
1250 );
1251 quad_source = None;
1252 let Some(shape) = frame.shapes.get(*idx) else {
1253 continue;
1254 };
1255 let verts = if shape.stroke_space
1264 == teksilo_canvas::StrokeSpace::Device
1265 && shape.stroke_width > 0.0
1266 {
1267 let zoom = current_transform.m[0].hypot(current_transform.m[1]);
1272 SdfVertex::from_shape_quad_cosmetic(shape, scale_factor, zoom)
1273 } else {
1274 SdfVertex::from_shape_quad(shape, scale_factor)
1275 };
1276 for v in &verts {
1277 let tp = apply_transform_pixel(v.position, ¤t_transform);
1278 sdf_batch.push(SdfVertex {
1279 position: pixel_to_ndc(tp, viewport_width, viewport_height),
1280 color: [
1281 v.color[0],
1282 v.color[1],
1283 v.color[2],
1284 v.color[3] * current_opacity,
1285 ],
1286 ..*v
1287 });
1288 }
1289 }
1290 teksilo_canvas::DrawCommand::Glyph(idx) => {
1291 if quad_source != Some(QuadSource::GlyphAtlas) {
1294 flush_all!(
1295 pass,
1296 &self.queue,
1297 self.streams,
1298 &self.rect_pipeline,
1299 &self.sdf_pipeline,
1300 &self.quad_pipeline,
1301 &self.path_gradient_pipeline,
1302 &self.shadow_pipeline,
1303 rect_batch,
1304 sdf_batch,
1305 quad_batch,
1306 path_gradient_batch,
1307 shadow_batch,
1308 self.atlas_texture,
1309 self.path_atlas_texture,
1310 quad_source,
1311 index_binding
1312 );
1313 quad_source = Some(QuadSource::GlyphAtlas);
1314 }
1315 if let Some(atlas) = &self.atlas_texture {
1316 let Some(glyph) = frame.glyphs.get(*idx) else {
1317 continue;
1318 };
1319 let verts = QuadVertex::from_glyph_quad_transformed(
1322 glyph,
1323 scale_factor,
1324 atlas.width,
1325 atlas.height,
1326 ¤t_transform,
1327 );
1328 let text_params = if glyph.is_color { 0 } else { text_params };
1331 for v in &verts {
1332 quad_batch.push(QuadVertex {
1333 position: pixel_to_ndc(
1334 v.position,
1335 viewport_width,
1336 viewport_height,
1337 ),
1338 color: [
1339 v.color[0],
1340 v.color[1],
1341 v.color[2],
1342 v.color[3] * current_opacity,
1343 ],
1344 text_params,
1345 ..*v
1346 });
1347 }
1348 }
1349 }
1350 teksilo_canvas::DrawCommand::Shadow(idx) => {
1351 flush_all!(
1352 pass,
1353 &self.queue,
1354 self.streams,
1355 &self.rect_pipeline,
1356 &self.sdf_pipeline,
1357 &self.quad_pipeline,
1358 &self.path_gradient_pipeline,
1359 &self.shadow_pipeline,
1360 rect_batch,
1361 sdf_batch,
1362 quad_batch,
1363 path_gradient_batch,
1364 shadow_batch,
1365 self.atlas_texture,
1366 self.path_atlas_texture,
1367 quad_source,
1368 index_binding
1369 );
1370 quad_source = None;
1371 let Some(shadow) = frame.shadows.get(*idx) else {
1372 continue;
1373 };
1374 let verts = ShadowVertex::from_shadow_quad(shadow, scale_factor);
1375 for v in &verts {
1376 let tp = apply_transform_pixel(v.position, ¤t_transform);
1377 shadow_batch.push(ShadowVertex {
1378 position: pixel_to_ndc(tp, viewport_width, viewport_height),
1379 shadow_color: [
1380 v.shadow_color[0],
1381 v.shadow_color[1],
1382 v.shadow_color[2],
1383 v.shadow_color[3] * current_opacity,
1384 ],
1385 ..*v
1386 });
1387 }
1388 }
1389 teksilo_canvas::DrawCommand::Image(idx) => {
1390 flush_all!(
1392 pass,
1393 &self.queue,
1394 self.streams,
1395 &self.rect_pipeline,
1396 &self.sdf_pipeline,
1397 &self.quad_pipeline,
1398 &self.path_gradient_pipeline,
1399 &self.shadow_pipeline,
1400 rect_batch,
1401 sdf_batch,
1402 quad_batch,
1403 path_gradient_batch,
1404 shadow_batch,
1405 self.atlas_texture,
1406 self.path_atlas_texture,
1407 quad_source,
1408 index_binding
1409 );
1410 quad_source = None;
1411 let Some(image) = frame.images.get(*idx) else {
1412 continue;
1413 };
1414 self.draw_image(
1415 pass,
1416 image,
1417 scale_factor,
1418 viewport_width,
1419 viewport_height,
1420 current_opacity,
1421 ¤t_transform,
1422 index_binding,
1423 );
1424 }
1425 teksilo_canvas::DrawCommand::Path(idx) => {
1426 flush_all!(
1427 pass,
1428 &self.queue,
1429 self.streams,
1430 &self.rect_pipeline,
1431 &self.sdf_pipeline,
1432 &self.quad_pipeline,
1433 &self.path_gradient_pipeline,
1434 &self.shadow_pipeline,
1435 rect_batch,
1436 sdf_batch,
1437 quad_batch,
1438 path_gradient_batch,
1439 shadow_batch,
1440 self.atlas_texture,
1441 self.path_atlas_texture,
1442 quad_source,
1443 index_binding
1444 );
1445 quad_source = None;
1446 if let Some(Some(placement)) = path_placements.get(*idx) {
1447 let Some(entry) = frame.paths.get(*idx) else {
1448 continue;
1449 };
1450 let Some(path_atlas) = self.path_atlas_texture.as_ref() else {
1451 continue;
1452 };
1453 if matches!(entry.paint_data, teksilo_canvas::PaintData::Solid)
1454 {
1455 quad_source = Some(QuadSource::PathAtlas);
1463 let verts = path_quad_verts(
1464 entry,
1465 placement,
1466 path_atlas.width,
1467 path_atlas.height,
1468 current_opacity,
1469 ¤t_transform,
1470 );
1471 for v in &verts {
1472 quad_batch.push(QuadVertex {
1473 position: pixel_to_ndc(
1474 v.position,
1475 viewport_width,
1476 viewport_height,
1477 ),
1478 ..*v
1479 });
1480 }
1481 } else {
1482 let verts = path_gradient_quad_verts(
1489 entry,
1490 placement,
1491 scale_factor,
1492 path_atlas.width,
1493 path_atlas.height,
1494 current_opacity,
1495 ¤t_transform,
1496 );
1497 for v in &verts {
1498 path_gradient_batch.push(
1499 crate::vertex::PathGradientVertex {
1500 position: pixel_to_ndc(
1501 v.position,
1502 viewport_width,
1503 viewport_height,
1504 ),
1505 ..*v
1506 },
1507 );
1508 }
1509 }
1510 }
1511 }
1512 teksilo_canvas::DrawCommand::SetClip(rect) => {
1514 flush_all!(
1515 pass,
1516 &self.queue,
1517 self.streams,
1518 &self.rect_pipeline,
1519 &self.sdf_pipeline,
1520 &self.quad_pipeline,
1521 &self.path_gradient_pipeline,
1522 &self.shadow_pipeline,
1523 rect_batch,
1524 sdf_batch,
1525 quad_batch,
1526 path_gradient_batch,
1527 shadow_batch,
1528 self.atlas_texture,
1529 self.path_atlas_texture,
1530 quad_source,
1531 index_binding
1532 );
1533 quad_source = None;
1534 let device = |x: f32, y: f32| {
1560 apply_transform_pixel(
1561 [x * scale_factor, y * scale_factor],
1562 ¤t_transform,
1563 )
1564 };
1565 let p_tl = device(rect.x, rect.y);
1566 let p_tr = device(rect.x + rect.width, rect.y);
1567 let p_bl = device(rect.x, rect.y + rect.height);
1568 let p_br = device(rect.x + rect.width, rect.y + rect.height);
1569 let min_x = p_tl[0].min(p_tr[0]).min(p_bl[0]).min(p_br[0]);
1570 let min_y = p_tl[1].min(p_tr[1]).min(p_bl[1]).min(p_br[1]);
1571 let max_x = p_tl[0].max(p_tr[0]).max(p_bl[0]).max(p_br[0]);
1572 let max_y = p_tl[1].max(p_tr[1]).max(p_bl[1]).max(p_br[1]);
1573 let x0 = min_x.floor().max(0.0);
1578 let y0 = min_y.floor().max(0.0);
1579 let x1 = max_x.ceil().max(x0);
1580 let y1 = max_y.ceil().max(y0);
1581 let x = x0 as u32;
1582 let y = y0 as u32;
1583 let w = (x1 - x0) as u32;
1584 let h = (y1 - y0) as u32;
1585 let x = x.min(viewport_width);
1587 let y = y.min(viewport_height);
1588 let w = w.min(viewport_width.saturating_sub(x));
1589 let h = h.min(viewport_height.saturating_sub(y));
1590 let clip_stack = &mut target_stack
1591 .last_mut()
1592 .expect("target_stack always has the surface target")
1593 .clip_stack;
1594 let clipped = if let Some(&[cx, cy, cw, ch]) = clip_stack.last() {
1595 let ix = x.max(cx);
1596 let iy = y.max(cy);
1597 let ir = (x + w).min(cx + cw);
1598 let ib = (y + h).min(cy + ch);
1599 [ix, iy, ir.saturating_sub(ix), ib.saturating_sub(iy)]
1600 } else {
1601 [x, y, w, h]
1602 };
1603 clip_stack.push(clipped);
1604 pass.set_scissor_rect(
1605 clipped[0], clipped[1], clipped[2], clipped[3],
1606 );
1607 }
1608 teksilo_canvas::DrawCommand::ClearClip => {
1609 flush_all!(
1610 pass,
1611 &self.queue,
1612 self.streams,
1613 &self.rect_pipeline,
1614 &self.sdf_pipeline,
1615 &self.quad_pipeline,
1616 &self.path_gradient_pipeline,
1617 &self.shadow_pipeline,
1618 rect_batch,
1619 sdf_batch,
1620 quad_batch,
1621 path_gradient_batch,
1622 shadow_batch,
1623 self.atlas_texture,
1624 self.path_atlas_texture,
1625 quad_source,
1626 index_binding
1627 );
1628 quad_source = None;
1629 let clip_stack = &mut target_stack
1630 .last_mut()
1631 .expect("target_stack always has the surface target")
1632 .clip_stack;
1633 clip_stack.pop();
1634 if let Some(&[x, y, w, h]) = clip_stack.last() {
1635 pass.set_scissor_rect(x, y, w, h);
1636 } else {
1637 pass.set_scissor_rect(0, 0, viewport_width, viewport_height);
1638 }
1639 }
1640 teksilo_canvas::DrawCommand::SetOpacity(opacity) => {
1641 flush_all!(
1642 pass,
1643 &self.queue,
1644 self.streams,
1645 &self.rect_pipeline,
1646 &self.sdf_pipeline,
1647 &self.quad_pipeline,
1648 &self.path_gradient_pipeline,
1649 &self.shadow_pipeline,
1650 rect_batch,
1651 sdf_batch,
1652 quad_batch,
1653 path_gradient_batch,
1654 shadow_batch,
1655 self.atlas_texture,
1656 self.path_atlas_texture,
1657 quad_source,
1658 index_binding
1659 );
1660 quad_source = None;
1661 opacity_stack.push(current_opacity);
1662 current_opacity *= opacity;
1663 }
1664 teksilo_canvas::DrawCommand::RestoreOpacity => {
1665 flush_all!(
1666 pass,
1667 &self.queue,
1668 self.streams,
1669 &self.rect_pipeline,
1670 &self.sdf_pipeline,
1671 &self.quad_pipeline,
1672 &self.path_gradient_pipeline,
1673 &self.shadow_pipeline,
1674 rect_batch,
1675 sdf_batch,
1676 quad_batch,
1677 path_gradient_batch,
1678 shadow_batch,
1679 self.atlas_texture,
1680 self.path_atlas_texture,
1681 quad_source,
1682 index_binding
1683 );
1684 quad_source = None;
1685 current_opacity = opacity_stack.pop().unwrap_or(1.0);
1686 }
1687 teksilo_canvas::DrawCommand::Rasterized(_) => {}
1688 teksilo_canvas::DrawCommand::LiveImage(idx) => {
1689 flush_all!(
1692 pass,
1693 &self.queue,
1694 self.streams,
1695 &self.rect_pipeline,
1696 &self.sdf_pipeline,
1697 &self.quad_pipeline,
1698 &self.path_gradient_pipeline,
1699 &self.shadow_pipeline,
1700 rect_batch,
1701 sdf_batch,
1702 quad_batch,
1703 path_gradient_batch,
1704 shadow_batch,
1705 self.atlas_texture,
1706 self.path_atlas_texture,
1707 quad_source,
1708 index_binding
1709 );
1710 quad_source = None;
1711 self.draw_live_image(
1712 pass,
1713 frame,
1714 *idx,
1715 scale_factor,
1716 viewport_width,
1717 viewport_height,
1718 current_opacity,
1719 ¤t_transform,
1720 index_binding,
1721 );
1722 }
1723 teksilo_canvas::DrawCommand::AnimatedQuad(idx) => {
1724 let Some(draw) = frame.animated_quads.get(*idx) else {
1725 continue;
1726 };
1727 flush_all!(
1730 pass,
1731 &self.queue,
1732 self.streams,
1733 &self.rect_pipeline,
1734 &self.sdf_pipeline,
1735 &self.quad_pipeline,
1736 &self.path_gradient_pipeline,
1737 &self.shadow_pipeline,
1738 rect_batch,
1739 sdf_batch,
1740 quad_batch,
1741 path_gradient_batch,
1742 shadow_batch,
1743 self.atlas_texture,
1744 self.path_atlas_texture,
1745 quad_source,
1746 index_binding
1747 );
1748 quad_source = None;
1749 match &draw.class {
1750 teksilo_canvas::AnimatedQuadClass::Procedural => {
1751 let verts =
1752 AnimQuadVertex::from_animated_quad(draw, scale_factor);
1753 for v in &verts {
1754 let tp = apply_transform_pixel(
1755 v.position,
1756 ¤t_transform,
1757 );
1758 anim_proc_batch.push(AnimQuadVertex {
1759 position: pixel_to_ndc(
1760 tp,
1761 viewport_width,
1762 viewport_height,
1763 ),
1764 uv: v.uv,
1765 slot: v.slot,
1766 _pad: v._pad,
1767 });
1768 }
1769 }
1770 teksilo_canvas::AnimatedQuadClass::Sprite { image_name } => {
1771 let Some(atlas_bg) =
1777 self.image_manager.get_bind_group(image_name)
1778 else {
1779 continue;
1780 };
1781 let verts =
1782 AnimQuadVertex::from_animated_quad(draw, scale_factor);
1783 let mut ndc_verts = [AnimQuadVertex {
1784 position: [0.0; 2],
1785 uv: [0.0; 2],
1786 slot: 0,
1787 _pad: 0,
1788 };
1789 4];
1790 for (i, v) in verts.iter().enumerate() {
1791 let tp = apply_transform_pixel(
1792 v.position,
1793 ¤t_transform,
1794 );
1795 ndc_verts[i] = AnimQuadVertex {
1796 position: pixel_to_ndc(
1797 tp,
1798 viewport_width,
1799 viewport_height,
1800 ),
1801 uv: v.uv,
1802 slot: v.slot,
1803 _pad: v._pad,
1804 };
1805 }
1806 let bytes: &[u8] = bytemuck::cast_slice(&ndc_verts);
1807 if let (Some((vb, v_off, v_len)), Some((ib, _, _))) = (
1808 self.streams.anim_proc.write(&self.queue, bytes),
1809 index_binding,
1810 ) {
1811 let index_bytes: u64 = 6 * 4;
1812 pass.set_pipeline(&self.anim_sprite_pipeline);
1813 pass.set_bind_group(
1814 0,
1815 &self.anim_uniform_bind_group,
1816 &[],
1817 );
1818 pass.set_bind_group(1, atlas_bg, &[]);
1819 pass.set_vertex_buffer(
1820 0,
1821 vb.slice(v_off..v_off + v_len),
1822 );
1823 pass.set_index_buffer(
1824 ib.slice(0..index_bytes),
1825 wgpu::IndexFormat::Uint32,
1826 );
1827 pass.draw_indexed(0..6, 0, 0..1);
1828 }
1829 }
1830 }
1831 }
1832 teksilo_canvas::DrawCommand::SetBlendMode(mode) => {
1833 blend_stack.push(current_blend);
1834 current_blend = *mode;
1835 }
1836 teksilo_canvas::DrawCommand::RestoreBlendMode => {
1837 current_blend = blend_stack
1838 .pop()
1839 .unwrap_or(teksilo_canvas::BlendMode::Normal);
1840 }
1841 teksilo_canvas::DrawCommand::SetTransform(t) => {
1842 flush_all!(
1843 pass,
1844 &self.queue,
1845 self.streams,
1846 &self.rect_pipeline,
1847 &self.sdf_pipeline,
1848 &self.quad_pipeline,
1849 &self.path_gradient_pipeline,
1850 &self.shadow_pipeline,
1851 rect_batch,
1852 sdf_batch,
1853 quad_batch,
1854 path_gradient_batch,
1855 shadow_batch,
1856 self.atlas_texture,
1857 self.path_atlas_texture,
1858 quad_source,
1859 index_binding
1860 );
1861 quad_source = None;
1862 let device_t = Transform2D {
1868 m: [
1869 t.m[0],
1870 t.m[1],
1871 t.m[2],
1872 t.m[3],
1873 t.m[4] * scale_factor,
1874 t.m[5] * scale_factor,
1875 ],
1876 };
1877 let stack_top = transform_stack
1884 .last()
1885 .copied()
1886 .unwrap_or(Transform2D::IDENTITY);
1887 current_transform = device_t.then(&stack_top);
1888 }
1889 teksilo_canvas::DrawCommand::PushTransform(t) => {
1890 flush_all!(
1891 pass,
1892 &self.queue,
1893 self.streams,
1894 &self.rect_pipeline,
1895 &self.sdf_pipeline,
1896 &self.quad_pipeline,
1897 &self.path_gradient_pipeline,
1898 &self.shadow_pipeline,
1899 rect_batch,
1900 sdf_batch,
1901 quad_batch,
1902 path_gradient_batch,
1903 shadow_batch,
1904 self.atlas_texture,
1905 self.path_atlas_texture,
1906 quad_source,
1907 index_binding
1908 );
1909 quad_source = None;
1910 let device_t = Transform2D {
1913 m: [
1914 t.m[0],
1915 t.m[1],
1916 t.m[2],
1917 t.m[3],
1918 t.m[4] * scale_factor,
1919 t.m[5] * scale_factor,
1920 ],
1921 };
1922 let prev_top = transform_stack
1923 .last()
1924 .copied()
1925 .unwrap_or(Transform2D::IDENTITY);
1926 let new_top = device_t.then(&prev_top);
1927 transform_stack.push(new_top);
1928 current_transform = new_top;
1929 }
1930 teksilo_canvas::DrawCommand::PopTransform => {
1931 flush_all!(
1932 pass,
1933 &self.queue,
1934 self.streams,
1935 &self.rect_pipeline,
1936 &self.sdf_pipeline,
1937 &self.quad_pipeline,
1938 &self.path_gradient_pipeline,
1939 &self.shadow_pipeline,
1940 rect_batch,
1941 sdf_batch,
1942 quad_batch,
1943 path_gradient_batch,
1944 shadow_batch,
1945 self.atlas_texture,
1946 self.path_atlas_texture,
1947 quad_source,
1948 index_binding
1949 );
1950 quad_source = None;
1951 if transform_stack.len() > 1 {
1952 transform_stack.pop();
1953 }
1954 current_transform = transform_stack
1955 .last()
1956 .copied()
1957 .unwrap_or(Transform2D::IDENTITY);
1958 }
1959 teksilo_canvas::DrawCommand::BeginBlurredSubtree { .. }
1960 | teksilo_canvas::DrawCommand::EndBlurredSubtree => {
1961 unreachable!("blur boundaries are handled at the segment level");
1964 }
1965 }
1966 cmd_idx += 1;
1967 }
1968
1969 flush_all!(
1971 pass,
1972 &self.queue,
1973 self.streams,
1974 &self.rect_pipeline,
1975 &self.sdf_pipeline,
1976 &self.quad_pipeline,
1977 &self.path_gradient_pipeline,
1978 &self.shadow_pipeline,
1979 rect_batch,
1980 sdf_batch,
1981 quad_batch,
1982 path_gradient_batch,
1983 shadow_batch,
1984 self.atlas_texture,
1985 self.path_atlas_texture,
1986 quad_source,
1987 index_binding
1988 );
1989 quad_source = None;
1990 } if cmd_idx >= frame.draw_order.len() {
1994 break;
1995 }
1996 match &frame.draw_order[cmd_idx] {
1997 teksilo_canvas::DrawCommand::BeginBlurredSubtree { bounds, radius } => {
1998 let device_w = (bounds.width * scale_factor).ceil().max(1.0) as u32;
2000 let device_h = (bounds.height * scale_factor).ceil().max(1.0) as u32;
2001 let intermediate = self.blur_pool.acquire(&self.device, device_w, device_h);
2002 let (bucket_w, bucket_h) = self.blur_pool.dimensions(intermediate);
2003
2004 let translate = Transform2D {
2009 m: [
2010 1.0,
2011 0.0,
2012 0.0,
2013 1.0,
2014 -bounds.x * scale_factor,
2015 -bounds.y * scale_factor,
2016 ],
2017 };
2018 let prev_top = transform_stack
2019 .last()
2020 .copied()
2021 .unwrap_or(Transform2D::IDENTITY);
2022 let new_top = translate.then(&prev_top);
2023 transform_stack.push(new_top);
2024 current_transform = new_top;
2025
2026 target_stack.push(ActiveTarget {
2027 intermediate: Some(intermediate),
2028 viewport_w: bucket_w,
2029 viewport_h: bucket_h,
2030 opened: false,
2031 pending_composites: Vec::new(),
2032 clip_stack: Vec::new(),
2033 blur_bounds: Some(*bounds),
2034 blur_radius_logical: Some(*radius),
2035 used_w: Some(device_w),
2036 used_h: Some(device_h),
2037 bucket_w: Some(bucket_w),
2038 bucket_h: Some(bucket_h),
2039 });
2040 }
2041 teksilo_canvas::DrawCommand::EndBlurredSubtree => {
2042 let scope = target_stack
2043 .pop()
2044 .expect("EndBlurredSubtree without matching Begin");
2045 debug_assert!(
2046 scope.intermediate.is_some(),
2047 "End popped the surface (impossible if walker is balanced)"
2048 );
2049 let intermediate = scope
2050 .intermediate
2051 .expect("blur scope intermediate set in BeginBlurredSubtree");
2052 let bounds = scope
2053 .blur_bounds
2054 .expect("blur scope bounds set in BeginBlurredSubtree");
2055 let radius = scope
2056 .blur_radius_logical
2057 .expect("blur scope radius set in BeginBlurredSubtree");
2058 let used_w = scope
2059 .used_w
2060 .expect("blur scope used_w set in BeginBlurredSubtree");
2061 let used_h = scope
2062 .used_h
2063 .expect("blur scope used_h set in BeginBlurredSubtree");
2064 let bucket_w = scope
2065 .bucket_w
2066 .expect("blur scope bucket_w set in BeginBlurredSubtree");
2067 let bucket_h = scope
2068 .bucket_h
2069 .expect("blur scope bucket_h set in BeginBlurredSubtree");
2070
2071 if transform_stack.len() > 1 {
2073 transform_stack.pop();
2074 }
2075 current_transform = transform_stack
2076 .last()
2077 .copied()
2078 .unwrap_or(Transform2D::IDENTITY);
2079
2080 let blurred = run_kawase_chain(
2084 &self.device,
2085 &self.queue,
2086 &mut encoder,
2087 &mut self.blur_pool,
2088 &mut self.blur_pipelines,
2089 intermediate,
2090 used_w,
2091 used_h,
2092 bucket_w,
2093 bucket_h,
2094 radius * scale_factor,
2095 );
2096
2097 target_stack
2100 .last_mut()
2101 .expect("target_stack always has the surface target")
2102 .pending_composites
2103 .push(PendingComposite {
2104 blurred_texture: blurred.texture,
2105 used_w: blurred.used_w,
2106 used_h: blurred.used_h,
2107 bucket_w: blurred.bucket_w,
2108 bucket_h: blurred.bucket_h,
2109 bounds,
2110 });
2111 }
2112 _ => unreachable!("inner loop only breaks on Begin/End"),
2113 }
2114 cmd_idx += 1;
2115 }
2116
2117 debug_assert!(
2118 target_stack.len() == 1,
2119 "target_stack not balanced at EOF — unmatched Begin/End in walker output"
2120 );
2121 let final_composites = std::mem::take(
2125 &mut target_stack
2126 .last_mut()
2127 .expect("target_stack always has the surface target")
2128 .pending_composites,
2129 );
2130 if !final_composites.is_empty() {
2131 let surface = target_stack
2132 .last_mut()
2133 .expect("target_stack always has the surface target");
2134 let load_op = if surface.opened {
2135 wgpu::LoadOp::Load
2136 } else {
2137 wgpu::LoadOp::Clear(surface_clear_color)
2138 };
2139 surface.opened = true;
2140 let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2141 label: Some("teksilo_final_composite_pass"),
2142 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2143 view,
2144 resolve_target: None,
2145 ops: wgpu::Operations {
2146 load: load_op,
2147 store: wgpu::StoreOp::Store,
2148 },
2149 depth_slice: None,
2150 })],
2151 depth_stencil_attachment: None,
2152 timestamp_writes: None,
2153 occlusion_query_set: None,
2154 multiview_mask: None,
2155 });
2156 for pc in &final_composites {
2157 composite_blur_quad(
2158 &self.device,
2159 &self.queue,
2160 &mut pass,
2161 &self.blur_pool,
2162 &self.quad_pipeline,
2163 &self.quad_bind_group_layout,
2164 &self.blur_composite_sampler,
2165 &self.streams.quad,
2166 index_binding,
2167 pc.blurred_texture,
2168 pc.used_w,
2169 pc.used_h,
2170 pc.bucket_w,
2171 pc.bucket_h,
2172 pc.bounds,
2173 scale_factor,
2174 viewport_width,
2175 viewport_height,
2176 );
2177 }
2178 } else if !target_stack
2179 .last()
2180 .expect("target_stack always has the surface target")
2181 .opened
2182 {
2183 let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
2185 label: Some("teksilo_empty_clear_pass"),
2186 color_attachments: &[Some(wgpu::RenderPassColorAttachment {
2187 view,
2188 resolve_target: None,
2189 ops: wgpu::Operations {
2190 load: wgpu::LoadOp::Clear(surface_clear_color),
2191 store: wgpu::StoreOp::Store,
2192 },
2193 depth_slice: None,
2194 })],
2195 depth_stencil_attachment: None,
2196 timestamp_writes: None,
2197 occlusion_query_set: None,
2198 multiview_mask: None,
2199 });
2200 }
2201 }
2202
2203 let submission = self.queue.submit(std::iter::once(encoder.finish()));
2204 let idle = self.live.stats().textures == 0;
2207 self.live.backend_mut().after_submit(idle);
2208 if self.live.backend_mut().take_released() {
2209 crate::gpu_reclaim::flag_device(
2210 self.live.backend().health(),
2211 &self.device,
2212 submission.clone(),
2213 );
2214 }
2215 self.last_submission = Some(submission);
2216 }
2217
2218 #[allow(clippy::too_many_arguments)]
2226 fn draw_live_image(
2227 &self,
2228 pass: &mut wgpu::RenderPass,
2229 frame: &RenderFrame,
2230 idx: usize,
2231 scale_factor: f32,
2232 viewport_width: u32,
2233 viewport_height: u32,
2234 opacity: f32,
2235 transform: &Transform2D,
2236 index_binding: Option<(&wgpu::Buffer, u64, u64)>,
2237 ) {
2238 let (Some(quad), Some(decision)) =
2239 (frame.live_images.get(idx), self.live.decisions().get(idx))
2240 else {
2241 return;
2242 };
2243 if !decision.draw {
2244 return;
2245 }
2246 let Some(texture) = self.live.texture(quad.consumer.source().id()) else {
2247 return;
2248 };
2249 let Some(bind_group) = texture.bind_group(quad.filter) else {
2250 return;
2251 };
2252 let format = quad.consumer.source().format();
2253 let mut flags = crate::vertex::QUAD_FLAG_COLOR_GLYPH;
2254 if format.is_opaque() {
2255 flags |= crate::vertex::QUAD_FLAG_OPAQUE;
2256 }
2257 if format.is_bgr() {
2258 flags |= crate::vertex::QUAD_FLAG_SWAP_RB;
2259 }
2260 let verts = crate::vertex::live_quad_verts(
2261 quad,
2262 texture.size(),
2263 scale_factor,
2264 transform,
2265 [1.0, 1.0, 1.0, opacity],
2266 flags,
2267 );
2268 let ndc: [QuadVertex; 4] = std::array::from_fn(|i| QuadVertex {
2269 position: pixel_to_ndc(verts[i].position, viewport_width, viewport_height),
2270 ..verts[i]
2271 });
2272 let bytes: &[u8] = bytemuck::cast_slice(&ndc);
2273 let Some((vb, v_off, v_len)) = self.streams.quad.write(&self.queue, bytes) else {
2274 return;
2275 };
2276 let Some((ib, _, _)) = index_binding else {
2277 return;
2278 };
2279 pass.set_pipeline(&self.quad_pipeline);
2280 pass.set_bind_group(0, bind_group, &[]);
2281 pass.set_vertex_buffer(0, vb.slice(v_off..v_off + v_len));
2282 pass.set_index_buffer(ib.slice(0..24), wgpu::IndexFormat::Uint32);
2283 pass.draw_indexed(0..6, 0, 0..1);
2284 }
2285
2286 #[allow(clippy::too_many_arguments)]
2290 fn draw_image(
2291 &self,
2292 pass: &mut wgpu::RenderPass,
2293 image: &teksilo_canvas::ImageQuad,
2294 scale_factor: f32,
2295 viewport_width: u32,
2296 viewport_height: u32,
2297 opacity: f32,
2298 transform: &Transform2D,
2299 index_binding: Option<(&wgpu::Buffer, u64, u64)>,
2300 ) {
2301 let bind_group = match self.image_manager.get_bind_group(&image.name) {
2302 Some(bg) => bg,
2303 None => return,
2304 };
2305
2306 let [x, y, w, h] = image.screen;
2307 let sx = x * scale_factor;
2308 let sy = y * scale_factor;
2309 let sw = w * scale_factor;
2310 let sh = h * scale_factor;
2311
2312 let (color, flags) = if let Some(tint) = image.tint {
2315 (
2318 crate::vertex::srgb_to_linear_rgba([tint[0], tint[1], tint[2], tint[3] * opacity]),
2319 0,
2320 )
2321 } else {
2322 (
2323 [1.0, 1.0, 1.0, opacity],
2324 crate::vertex::QUAD_FLAG_COLOR_GLYPH,
2325 )
2326 };
2327
2328 let verts = [
2329 QuadVertex {
2330 position: [sx, sy],
2331 tex_coord: [0.0, 0.0],
2332 color,
2333 flags,
2334 text_params: 0,
2335 },
2336 QuadVertex {
2337 position: [sx + sw, sy],
2338 tex_coord: [1.0, 0.0],
2339 color,
2340 flags,
2341 text_params: 0,
2342 },
2343 QuadVertex {
2344 position: [sx + sw, sy + sh],
2345 tex_coord: [1.0, 1.0],
2346 color,
2347 flags,
2348 text_params: 0,
2349 },
2350 QuadVertex {
2351 position: [sx, sy + sh],
2352 tex_coord: [0.0, 1.0],
2353 color,
2354 flags,
2355 text_params: 0,
2356 },
2357 ];
2358
2359 let ndc_verts: [QuadVertex; 4] = std::array::from_fn(|i| {
2360 let v = verts[i];
2361 let tp = apply_transform_pixel(v.position, transform);
2362 QuadVertex {
2363 position: pixel_to_ndc(tp, viewport_width, viewport_height),
2364 ..v
2365 }
2366 });
2367
2368 let bytes: &[u8] = bytemuck::cast_slice(&ndc_verts);
2372 let Some((vb, v_off, v_len)) = self.streams.quad.write(&self.queue, bytes) else {
2373 return;
2374 };
2375 let Some((ib, _, _)) = index_binding else {
2376 return;
2377 };
2378
2379 pass.set_pipeline(&self.quad_pipeline);
2380 pass.set_bind_group(0, bind_group, &[]);
2381 pass.set_vertex_buffer(0, vb.slice(v_off..v_off + v_len));
2382 pass.set_index_buffer(ib.slice(0..24), wgpu::IndexFormat::Uint32);
2383 pass.draw_indexed(0..6, 0, 0..1);
2384 }
2385
2386 fn upload_path_atlas(&mut self, width: u32, height: u32, pixels: Vec<u8>) {
2388 if width == 0 || height == 0 {
2389 return;
2390 }
2391
2392 let needs_recreate = self
2393 .path_atlas_texture
2394 .as_ref()
2395 .is_none_or(|t| t.width != width || t.height != height);
2396
2397 if needs_recreate {
2398 let texture = self.device.create_texture(&wgpu::TextureDescriptor {
2399 label: Some("path_atlas"),
2400 size: wgpu::Extent3d {
2401 width,
2402 height,
2403 depth_or_array_layers: 1,
2404 },
2405 mip_level_count: 1,
2406 sample_count: 1,
2407 dimension: wgpu::TextureDimension::D2,
2408 format: wgpu::TextureFormat::Rgba8UnormSrgb,
2409 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2410 view_formats: &[],
2411 });
2412
2413 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
2414 let sampler = self.device.create_sampler(&wgpu::SamplerDescriptor {
2415 mag_filter: wgpu::FilterMode::Linear,
2416 min_filter: wgpu::FilterMode::Linear,
2417 ..Default::default()
2418 });
2419
2420 let bind_group_layout = self.quad_pipeline.get_bind_group_layout(0);
2421 let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
2422 label: Some("path_atlas_bind_group"),
2423 layout: &bind_group_layout,
2424 entries: &[
2425 wgpu::BindGroupEntry {
2426 binding: 0,
2427 resource: wgpu::BindingResource::TextureView(&view),
2428 },
2429 wgpu::BindGroupEntry {
2430 binding: 1,
2431 resource: wgpu::BindingResource::Sampler(&sampler),
2432 },
2433 ],
2434 });
2435
2436 self.path_atlas_texture = Some(AtlasTexture {
2437 texture,
2438 bind_group,
2439 width,
2440 height,
2441 });
2442 }
2443
2444 if let Some(atlas) = &self.path_atlas_texture {
2445 self.queue.write_texture(
2446 wgpu::TexelCopyTextureInfo {
2447 texture: &atlas.texture,
2448 mip_level: 0,
2449 origin: wgpu::Origin3d::ZERO,
2450 aspect: wgpu::TextureAspect::All,
2451 },
2452 &pixels,
2453 wgpu::TexelCopyBufferLayout {
2454 offset: 0,
2455 bytes_per_row: Some(width * 4),
2456 rows_per_image: Some(height),
2457 },
2458 wgpu::Extent3d {
2459 width,
2460 height,
2461 depth_or_array_layers: 1,
2462 },
2463 );
2464 }
2465 }
2466
2467 pub fn device(&self) -> &wgpu::Device {
2468 &self.device
2469 }
2470
2471 pub fn queue(&self) -> &wgpu::Queue {
2472 &self.queue
2473 }
2474
2475 pub fn register_image(&mut self, name: &str, width: u32, height: u32, pixels: &[u8]) {
2477 let layout = self.quad_pipeline.get_bind_group_layout(0);
2478 self.image_manager.register_image(
2479 name,
2480 width,
2481 height,
2482 pixels,
2483 &self.device,
2484 &self.queue,
2485 &layout,
2486 );
2487 }
2488
2489 pub fn remove_image(&mut self, name: &str) {
2491 self.image_manager.remove(name);
2492 }
2493}
2494
2495fn path_quad_verts(
2497 entry: &teksilo_canvas::PathEntry,
2498 placement: &crate::path_atlas::PathPlacement,
2499 atlas_width: u32,
2500 atlas_height: u32,
2501 opacity: f32,
2502 transform: &Transform2D,
2503) -> [QuadVertex; 4] {
2504 let region = &placement.region;
2509 let [sx, sy, sw, sh] = placement.device_rect;
2510
2511 let aw = atlas_width.max(1) as f32;
2512 let ah = atlas_height.max(1) as f32;
2513 let u0 = region.x as f32 / aw;
2514 let v0 = region.y as f32 / ah;
2515 let u1 = (region.x + region.w) as f32 / aw;
2516 let v1 = (region.y + region.h) as f32 / ah;
2517
2518 let lin = crate::vertex::srgb_to_linear_rgba(entry.color);
2525 let color = [lin[0], lin[1], lin[2], entry.color[3] * opacity];
2526
2527 let positions = [
2528 apply_transform_pixel([sx, sy], transform),
2529 apply_transform_pixel([sx + sw, sy], transform),
2530 apply_transform_pixel([sx + sw, sy + sh], transform),
2531 apply_transform_pixel([sx, sy + sh], transform),
2532 ];
2533 let uvs = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]];
2534
2535 [
2538 QuadVertex {
2539 position: positions[0],
2540 tex_coord: uvs[0],
2541 color,
2542 flags: 0,
2543 text_params: 0,
2544 },
2545 QuadVertex {
2546 position: positions[1],
2547 tex_coord: uvs[1],
2548 color,
2549 flags: 0,
2550 text_params: 0,
2551 },
2552 QuadVertex {
2553 position: positions[2],
2554 tex_coord: uvs[2],
2555 color,
2556 flags: 0,
2557 text_params: 0,
2558 },
2559 QuadVertex {
2560 position: positions[3],
2561 tex_coord: uvs[3],
2562 color,
2563 flags: 0,
2564 text_params: 0,
2565 },
2566 ]
2567}
2568
2569fn path_gradient_quad_verts(
2578 entry: &teksilo_canvas::PathEntry,
2579 placement: &crate::path_atlas::PathPlacement,
2580 scale_factor: f32,
2581 atlas_width: u32,
2582 atlas_height: u32,
2583 current_opacity: f32,
2584 transform: &Transform2D,
2585) -> [crate::vertex::PathGradientVertex; 4] {
2586 crate::vertex::PathGradientVertex::from_path_entry(
2587 entry,
2588 placement,
2589 scale_factor,
2590 atlas_width,
2591 atlas_height,
2592 current_opacity,
2593 transform,
2594 )
2595}
2596
2597fn pixel_to_ndc(pixel: [f32; 2], viewport_width: u32, viewport_height: u32) -> [f32; 2] {
2598 let x = (pixel[0] / viewport_width as f32) * 2.0 - 1.0;
2599 let y = 1.0 - (pixel[1] / viewport_height as f32) * 2.0; [x, y]
2601}
2602
2603fn apply_transform_pixel(pixel: [f32; 2], transform: &Transform2D) -> [f32; 2] {
2605 let [a, b, c, d, tx, ty] = transform.m;
2606 [
2607 a * pixel[0] + c * pixel[1] + tx,
2608 b * pixel[0] + d * pixel[1] + ty,
2609 ]
2610}
2611
2612struct KawaseResult {
2618 texture: crate::blur::AcquiredTexture,
2619 used_w: u32,
2620 used_h: u32,
2621 bucket_w: u32,
2622 bucket_h: u32,
2623}
2624
2625#[allow(clippy::too_many_arguments)]
2631fn run_kawase_chain(
2632 device: &wgpu::Device,
2633 queue: &wgpu::Queue,
2634 encoder: &mut wgpu::CommandEncoder,
2635 pool: &mut crate::blur::BlurPool,
2636 pipelines: &mut crate::blur::BlurPipelines,
2637 source: crate::blur::AcquiredTexture,
2638 used_w: u32,
2639 used_h: u32,
2640 bucket_w: u32,
2641 bucket_h: u32,
2642 radius_device_px: f32,
2643) -> KawaseResult {
2644 let levels = crate::blur::kawase_levels(radius_device_px);
2645
2646 let mut current = (source, used_w, used_h, bucket_w, bucket_h);
2650
2651 let mut chain: Vec<(crate::blur::AcquiredTexture, u32, u32, u32, u32)> =
2655 Vec::with_capacity(levels as usize + 1);
2656 chain.push(current);
2657
2658 const KERNEL_OFFSET: f32 = 0.5;
2663
2664 for _ in 0..levels {
2666 let (src_handle, src_used_w, src_used_h, src_bucket_w, src_bucket_h) = current;
2667 let dst_used_w = (src_used_w / 2).max(1);
2668 let dst_used_h = (src_used_h / 2).max(1);
2669 let dst = pool.acquire(device, dst_used_w, dst_used_h);
2670 let (dst_bucket_w, dst_bucket_h) = pool.dimensions(dst);
2671
2672 let params = crate::blur::BlurParams {
2674 offset: crate::blur::kawase_offset(src_bucket_w, src_bucket_h, KERNEL_OFFSET),
2675 };
2676 let params_offset = pipelines.params.push(queue, ¶ms);
2677 let bind_group = pool.make_bind_group(device, src_handle, pipelines.params.buffer());
2678
2679 crate::fullscreen::run_fullscreen_pass(
2680 encoder,
2681 &pipelines.down,
2682 &bind_group,
2683 &[params_offset],
2684 pool.view(dst),
2685 dst_used_w,
2686 dst_used_h,
2687 wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
2688 None,
2689 "kawase_down_pass",
2690 );
2691
2692 current = (dst, dst_used_w, dst_used_h, dst_bucket_w, dst_bucket_h);
2693 chain.push(current);
2694 }
2695
2696 for level in (0..levels).rev() {
2700 let (src_handle, _src_used_w, _src_used_h, src_bucket_w, src_bucket_h) = current;
2701 let target = chain[level as usize];
2702 let dst_used_w = target.1;
2703 let dst_used_h = target.2;
2704 let dst = pool.acquire(device, dst_used_w, dst_used_h);
2705 let (dst_bucket_w, dst_bucket_h) = pool.dimensions(dst);
2706
2707 let params = crate::blur::BlurParams {
2708 offset: crate::blur::kawase_offset(src_bucket_w, src_bucket_h, KERNEL_OFFSET),
2709 };
2710 let params_offset = pipelines.params.push(queue, ¶ms);
2711 let bind_group = pool.make_bind_group(device, src_handle, pipelines.params.buffer());
2712
2713 crate::fullscreen::run_fullscreen_pass(
2714 encoder,
2715 &pipelines.up,
2716 &bind_group,
2717 &[params_offset],
2718 pool.view(dst),
2719 dst_used_w,
2720 dst_used_h,
2721 wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
2722 None,
2723 "kawase_up_pass",
2724 );
2725
2726 current = (dst, dst_used_w, dst_used_h, dst_bucket_w, dst_bucket_h);
2727 }
2728
2729 KawaseResult {
2730 texture: current.0,
2731 used_w: current.1,
2732 used_h: current.2,
2733 bucket_w: current.3,
2734 bucket_h: current.4,
2735 }
2736}
2737
2738#[allow(clippy::too_many_arguments)]
2748fn composite_blur_quad(
2749 device: &wgpu::Device,
2750 queue: &wgpu::Queue,
2751 pass: &mut wgpu::RenderPass<'_>,
2752 pool: &crate::blur::BlurPool,
2753 quad_pipeline: &wgpu::RenderPipeline,
2754 quad_bind_group_layout: &wgpu::BindGroupLayout,
2755 sampler: &wgpu::Sampler,
2756 quad_stream: &crate::stream_buffer::StreamBuffer,
2757 index_binding: Option<(&wgpu::Buffer, u64, u64)>,
2758 blurred: crate::blur::AcquiredTexture,
2759 used_w: u32,
2760 used_h: u32,
2761 bucket_w: u32,
2762 bucket_h: u32,
2763 bounds: teksilo_canvas::Rect,
2764 scale_factor: f32,
2765 viewport_width: u32,
2766 viewport_height: u32,
2767) {
2768 let view = pool.view(blurred);
2769 let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
2770 label: Some("blur_composite_bind_group"),
2771 layout: quad_bind_group_layout,
2772 entries: &[
2773 wgpu::BindGroupEntry {
2774 binding: 0,
2775 resource: wgpu::BindingResource::TextureView(view),
2776 },
2777 wgpu::BindGroupEntry {
2778 binding: 1,
2779 resource: wgpu::BindingResource::Sampler(sampler),
2780 },
2781 ],
2782 });
2783
2784 let sx = bounds.x * scale_factor;
2786 let sy = bounds.y * scale_factor;
2787 let sw = bounds.width * scale_factor;
2788 let sh = bounds.height * scale_factor;
2789
2790 let u_max = used_w as f32 / bucket_w as f32;
2794 let v_max = used_h as f32 / bucket_h as f32;
2795
2796 let flags = 1u32;
2798 let color = [1.0, 1.0, 1.0, 1.0];
2799
2800 let p_tl = pixel_to_ndc([sx, sy], viewport_width, viewport_height);
2801 let p_tr = pixel_to_ndc([sx + sw, sy], viewport_width, viewport_height);
2802 let p_br = pixel_to_ndc([sx + sw, sy + sh], viewport_width, viewport_height);
2803 let p_bl = pixel_to_ndc([sx, sy + sh], viewport_width, viewport_height);
2804
2805 let verts: [QuadVertex; 4] = [
2806 QuadVertex {
2807 position: p_tl,
2808 tex_coord: [0.0, 0.0],
2809 color,
2810 flags,
2811 text_params: 0,
2812 },
2813 QuadVertex {
2814 position: p_tr,
2815 tex_coord: [u_max, 0.0],
2816 color,
2817 flags,
2818 text_params: 0,
2819 },
2820 QuadVertex {
2821 position: p_br,
2822 tex_coord: [u_max, v_max],
2823 color,
2824 flags,
2825 text_params: 0,
2826 },
2827 QuadVertex {
2828 position: p_bl,
2829 tex_coord: [0.0, v_max],
2830 color,
2831 flags,
2832 text_params: 0,
2833 },
2834 ];
2835
2836 let _ = device; let Some((vb, v_off, v_len)) = quad_stream.write(queue, bytemuck::cast_slice(&verts)) else {
2842 return;
2843 };
2844 let Some((ib, _, _)) = index_binding else {
2845 return;
2846 };
2847 let composite_index_bytes: u64 = 6 * std::mem::size_of::<u32>() as u64;
2848
2849 pass.set_pipeline(quad_pipeline);
2850 pass.set_bind_group(0, &bind_group, &[]);
2851 pass.set_viewport(
2852 0.0,
2853 0.0,
2854 viewport_width as f32,
2855 viewport_height as f32,
2856 0.0,
2857 1.0,
2858 );
2859 pass.set_vertex_buffer(0, vb.slice(v_off..v_off + v_len));
2860 pass.set_index_buffer(
2861 ib.slice(0..composite_index_bytes),
2862 wgpu::IndexFormat::Uint32,
2863 );
2864 pass.draw_indexed(0..6, 0, 0..1);
2865}
2866
2867fn create_rect_pipeline(
2870 device: &wgpu::Device,
2871 format: wgpu::TextureFormat,
2872) -> wgpu::RenderPipeline {
2873 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
2874 label: Some("rect_shader"),
2875 source: wgpu::ShaderSource::Wgsl(include_str!("shaders/rect.wgsl").into()),
2876 });
2877
2878 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
2879 label: Some("rect_pipeline_layout"),
2880 bind_group_layouts: &[],
2881 immediate_size: 0,
2882 });
2883
2884 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
2885 label: Some("rect_pipeline"),
2886 layout: Some(&layout),
2887 vertex: wgpu::VertexState {
2888 module: &shader,
2889 entry_point: Some("vs_main"),
2890 buffers: &[Some(wgpu::VertexBufferLayout {
2891 array_stride: std::mem::size_of::<RectVertex>() as u64,
2892 step_mode: wgpu::VertexStepMode::Vertex,
2893 attributes: &[
2894 wgpu::VertexAttribute {
2895 offset: 0,
2896 shader_location: 0,
2897 format: wgpu::VertexFormat::Float32x2,
2898 },
2899 wgpu::VertexAttribute {
2900 offset: 8,
2901 shader_location: 1,
2902 format: wgpu::VertexFormat::Float32x4,
2903 },
2904 ],
2905 })],
2906 compilation_options: Default::default(),
2907 },
2908 fragment: Some(wgpu::FragmentState {
2909 module: &shader,
2910 entry_point: Some("fs_main"),
2911 targets: &[Some(wgpu::ColorTargetState {
2912 format,
2913 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
2914 write_mask: wgpu::ColorWrites::ALL,
2915 })],
2916 compilation_options: Default::default(),
2917 }),
2918 primitive: wgpu::PrimitiveState {
2919 topology: wgpu::PrimitiveTopology::TriangleList,
2920 ..Default::default()
2921 },
2922 depth_stencil: None,
2923 multisample: wgpu::MultisampleState::default(),
2924 multiview_mask: None,
2925 cache: None,
2926 })
2927}
2928
2929fn create_sdf_pipeline(device: &wgpu::Device, format: wgpu::TextureFormat) -> wgpu::RenderPipeline {
2930 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
2931 label: Some("sdf_shader"),
2932 source: wgpu::ShaderSource::Wgsl(include_str!("shaders/sdf.wgsl").into()),
2933 });
2934
2935 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
2936 label: Some("sdf_pipeline_layout"),
2937 bind_group_layouts: &[],
2938 immediate_size: 0,
2939 });
2940
2941 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
2942 label: Some("sdf_pipeline"),
2943 layout: Some(&layout),
2944 vertex: wgpu::VertexState {
2945 module: &shader,
2946 entry_point: Some("vs_main"),
2947 buffers: &[Some(wgpu::VertexBufferLayout {
2948 array_stride: std::mem::size_of::<SdfVertex>() as u64,
2949 step_mode: wgpu::VertexStepMode::Vertex,
2950 attributes: &[
2951 wgpu::VertexAttribute {
2952 offset: 0,
2953 shader_location: 0,
2954 format: wgpu::VertexFormat::Float32x2, },
2956 wgpu::VertexAttribute {
2957 offset: 8,
2958 shader_location: 1,
2959 format: wgpu::VertexFormat::Float32x2, },
2961 wgpu::VertexAttribute {
2962 offset: 16,
2963 shader_location: 2,
2964 format: wgpu::VertexFormat::Float32x4, },
2966 wgpu::VertexAttribute {
2967 offset: 32,
2968 shader_location: 3,
2969 format: wgpu::VertexFormat::Float32x4, },
2971 wgpu::VertexAttribute {
2972 offset: 48,
2973 shader_location: 4,
2974 format: wgpu::VertexFormat::Float32x4, },
2976 wgpu::VertexAttribute {
2977 offset: 64,
2978 shader_location: 5,
2979 format: wgpu::VertexFormat::Float32x4, },
2981 wgpu::VertexAttribute {
2982 offset: 80,
2983 shader_location: 6,
2984 format: wgpu::VertexFormat::Float32x4, },
2986 wgpu::VertexAttribute {
2987 offset: 96,
2988 shader_location: 7,
2989 format: wgpu::VertexFormat::Float32x4, },
2991 wgpu::VertexAttribute {
2992 offset: 112,
2993 shader_location: 8,
2994 format: wgpu::VertexFormat::Float32x4, },
2996 wgpu::VertexAttribute {
2997 offset: 128,
2998 shader_location: 9,
2999 format: wgpu::VertexFormat::Float32x4, },
3001 wgpu::VertexAttribute {
3002 offset: 144,
3003 shader_location: 10,
3004 format: wgpu::VertexFormat::Float32x4, },
3006 ],
3007 })],
3008 compilation_options: Default::default(),
3009 },
3010 fragment: Some(wgpu::FragmentState {
3011 module: &shader,
3012 entry_point: Some("fs_main"),
3013 targets: &[Some(wgpu::ColorTargetState {
3014 format,
3015 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
3016 write_mask: wgpu::ColorWrites::ALL,
3017 })],
3018 compilation_options: Default::default(),
3019 }),
3020 primitive: wgpu::PrimitiveState {
3021 topology: wgpu::PrimitiveTopology::TriangleList,
3022 ..Default::default()
3023 },
3024 depth_stencil: None,
3025 multisample: wgpu::MultisampleState::default(),
3026 multiview_mask: None,
3027 cache: None,
3028 })
3029}
3030
3031fn create_quad_pipeline(
3032 device: &wgpu::Device,
3033 format: wgpu::TextureFormat,
3034) -> wgpu::RenderPipeline {
3035 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
3036 label: Some("quad_shader"),
3037 source: wgpu::ShaderSource::Wgsl(include_str!("shaders/quad.wgsl").into()),
3038 });
3039
3040 let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3041 label: Some("quad_bind_group_layout"),
3042 entries: &[
3043 wgpu::BindGroupLayoutEntry {
3044 binding: 0,
3045 visibility: wgpu::ShaderStages::FRAGMENT,
3046 ty: wgpu::BindingType::Texture {
3047 sample_type: wgpu::TextureSampleType::Float { filterable: true },
3048 view_dimension: wgpu::TextureViewDimension::D2,
3049 multisampled: false,
3050 },
3051 count: None,
3052 },
3053 wgpu::BindGroupLayoutEntry {
3054 binding: 1,
3055 visibility: wgpu::ShaderStages::FRAGMENT,
3056 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3057 count: None,
3058 },
3059 ],
3060 });
3061
3062 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
3063 label: Some("quad_pipeline_layout"),
3064 bind_group_layouts: &[Some(&bind_group_layout)],
3065 immediate_size: 0,
3066 });
3067
3068 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
3069 label: Some("quad_pipeline"),
3070 layout: Some(&layout),
3071 vertex: wgpu::VertexState {
3072 module: &shader,
3073 entry_point: Some("vs_main"),
3074 buffers: &[Some(wgpu::VertexBufferLayout {
3075 array_stride: std::mem::size_of::<QuadVertex>() as u64,
3076 step_mode: wgpu::VertexStepMode::Vertex,
3077 attributes: &[
3078 wgpu::VertexAttribute {
3079 offset: 0,
3080 shader_location: 0,
3081 format: wgpu::VertexFormat::Float32x2, },
3083 wgpu::VertexAttribute {
3084 offset: 8,
3085 shader_location: 1,
3086 format: wgpu::VertexFormat::Float32x2, },
3088 wgpu::VertexAttribute {
3089 offset: 16,
3090 shader_location: 2,
3091 format: wgpu::VertexFormat::Float32x4, },
3093 wgpu::VertexAttribute {
3094 offset: 32,
3095 shader_location: 3,
3096 format: wgpu::VertexFormat::Uint32, },
3098 wgpu::VertexAttribute {
3099 offset: 36,
3100 shader_location: 4,
3101 format: wgpu::VertexFormat::Uint32, },
3103 ],
3104 })],
3105 compilation_options: Default::default(),
3106 },
3107 fragment: Some(wgpu::FragmentState {
3108 module: &shader,
3109 entry_point: Some("fs_main"),
3110 targets: &[Some(wgpu::ColorTargetState {
3111 format,
3112 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
3113 write_mask: wgpu::ColorWrites::ALL,
3114 })],
3115 compilation_options: Default::default(),
3116 }),
3117 primitive: wgpu::PrimitiveState {
3118 topology: wgpu::PrimitiveTopology::TriangleList,
3119 ..Default::default()
3120 },
3121 depth_stencil: None,
3122 multisample: wgpu::MultisampleState::default(),
3123 multiview_mask: None,
3124 cache: None,
3125 })
3126}
3127
3128fn create_path_gradient_pipeline(
3134 device: &wgpu::Device,
3135 format: wgpu::TextureFormat,
3136 texture_bind_group_layout: &wgpu::BindGroupLayout,
3137) -> wgpu::RenderPipeline {
3138 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
3139 label: Some("path_gradient_shader"),
3140 source: wgpu::ShaderSource::Wgsl(include_str!("shaders/path_gradient.wgsl").into()),
3141 });
3142
3143 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
3144 label: Some("path_gradient_pipeline_layout"),
3145 bind_group_layouts: &[Some(texture_bind_group_layout)],
3146 immediate_size: 0,
3147 });
3148
3149 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
3150 label: Some("path_gradient_pipeline"),
3151 layout: Some(&layout),
3152 vertex: wgpu::VertexState {
3153 module: &shader,
3154 entry_point: Some("vs_main"),
3155 buffers: &[Some(wgpu::VertexBufferLayout {
3156 array_stride: std::mem::size_of::<crate::vertex::PathGradientVertex>() as u64,
3157 step_mode: wgpu::VertexStepMode::Vertex,
3158 attributes: &[
3159 wgpu::VertexAttribute {
3160 offset: 0,
3161 shader_location: 0,
3162 format: wgpu::VertexFormat::Float32x2, },
3164 wgpu::VertexAttribute {
3165 offset: 8,
3166 shader_location: 1,
3167 format: wgpu::VertexFormat::Float32x2, },
3169 wgpu::VertexAttribute {
3170 offset: 16,
3171 shader_location: 2,
3172 format: wgpu::VertexFormat::Float32x2, },
3174 wgpu::VertexAttribute {
3175 offset: 24,
3176 shader_location: 3,
3177 format: wgpu::VertexFormat::Uint32, },
3179 wgpu::VertexAttribute {
3181 offset: 32,
3182 shader_location: 4,
3183 format: wgpu::VertexFormat::Float32x4, },
3185 wgpu::VertexAttribute {
3186 offset: 48,
3187 shader_location: 5,
3188 format: wgpu::VertexFormat::Float32x4, },
3190 wgpu::VertexAttribute {
3191 offset: 64,
3192 shader_location: 6,
3193 format: wgpu::VertexFormat::Float32x4, },
3195 wgpu::VertexAttribute {
3196 offset: 80,
3197 shader_location: 7,
3198 format: wgpu::VertexFormat::Float32x4, },
3200 wgpu::VertexAttribute {
3201 offset: 96,
3202 shader_location: 8,
3203 format: wgpu::VertexFormat::Float32x4, },
3205 wgpu::VertexAttribute {
3206 offset: 112,
3207 shader_location: 9,
3208 format: wgpu::VertexFormat::Float32x4, },
3210 ],
3211 })],
3212 compilation_options: Default::default(),
3213 },
3214 fragment: Some(wgpu::FragmentState {
3215 module: &shader,
3216 entry_point: Some("fs_main"),
3217 targets: &[Some(wgpu::ColorTargetState {
3218 format,
3219 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
3220 write_mask: wgpu::ColorWrites::ALL,
3221 })],
3222 compilation_options: Default::default(),
3223 }),
3224 primitive: wgpu::PrimitiveState {
3225 topology: wgpu::PrimitiveTopology::TriangleList,
3226 ..Default::default()
3227 },
3228 depth_stencil: None,
3229 multisample: wgpu::MultisampleState::default(),
3230 multiview_mask: None,
3231 cache: None,
3232 })
3233}
3234
3235fn create_shadow_pipeline(
3236 device: &wgpu::Device,
3237 format: wgpu::TextureFormat,
3238) -> wgpu::RenderPipeline {
3239 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
3240 label: Some("shadow_shader"),
3241 source: wgpu::ShaderSource::Wgsl(include_str!("shaders/shadow.wgsl").into()),
3242 });
3243
3244 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
3245 label: Some("shadow_pipeline_layout"),
3246 bind_group_layouts: &[],
3247 immediate_size: 0,
3248 });
3249
3250 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
3251 label: Some("shadow_pipeline"),
3252 layout: Some(&layout),
3253 vertex: wgpu::VertexState {
3254 module: &shader,
3255 entry_point: Some("vs_main"),
3256 buffers: &[Some(wgpu::VertexBufferLayout {
3257 array_stride: std::mem::size_of::<ShadowVertex>() as u64,
3258 step_mode: wgpu::VertexStepMode::Vertex,
3259 attributes: &[
3260 wgpu::VertexAttribute {
3261 offset: 0,
3262 shader_location: 0,
3263 format: wgpu::VertexFormat::Float32x2, },
3265 wgpu::VertexAttribute {
3266 offset: 8,
3267 shader_location: 1,
3268 format: wgpu::VertexFormat::Float32x2, },
3270 wgpu::VertexAttribute {
3271 offset: 16,
3272 shader_location: 2,
3273 format: wgpu::VertexFormat::Float32x4, },
3275 wgpu::VertexAttribute {
3276 offset: 32,
3277 shader_location: 3,
3278 format: wgpu::VertexFormat::Float32x4, },
3280 wgpu::VertexAttribute {
3281 offset: 48,
3282 shader_location: 4,
3283 format: wgpu::VertexFormat::Float32x4, },
3285 wgpu::VertexAttribute {
3286 offset: 64,
3287 shader_location: 5,
3288 format: wgpu::VertexFormat::Float32x4, },
3290 ],
3291 })],
3292 compilation_options: Default::default(),
3293 },
3294 fragment: Some(wgpu::FragmentState {
3295 module: &shader,
3296 entry_point: Some("fs_main"),
3297 targets: &[Some(wgpu::ColorTargetState {
3298 format,
3299 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
3300 write_mask: wgpu::ColorWrites::ALL,
3301 })],
3302 compilation_options: Default::default(),
3303 }),
3304 primitive: wgpu::PrimitiveState {
3305 topology: wgpu::PrimitiveTopology::TriangleList,
3306 ..Default::default()
3307 },
3308 depth_stencil: None,
3309 multisample: wgpu::MultisampleState::default(),
3310 multiview_mask: None,
3311 cache: None,
3312 })
3313}
3314
3315#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3326pub(crate) struct StreamQuadCounts {
3327 pub rect: usize,
3328 pub sdf: usize,
3329 pub quad: usize,
3330 pub shadow: usize,
3331 pub anim_proc: usize,
3332 pub path_gradient: usize,
3335}
3336
3337impl StreamQuadCounts {
3338 pub fn max(&self) -> usize {
3341 self.rect
3342 .max(self.sdf)
3343 .max(self.quad)
3344 .max(self.shadow)
3345 .max(self.anim_proc)
3346 .max(self.path_gradient)
3347 }
3348}
3349
3350pub(crate) fn stream_quad_counts(frame: &RenderFrame) -> StreamQuadCounts {
3372 let composite_quads = frame
3373 .draw_order
3374 .iter()
3375 .filter(|c| matches!(c, teksilo_canvas::DrawCommand::BeginBlurredSubtree { .. }))
3376 .count();
3377 let gradient_paths = frame
3378 .paths
3379 .iter()
3380 .filter(|p| !matches!(p.paint_data, teksilo_canvas::PaintData::Solid))
3381 .count();
3382 let solid_paths = frame.paths.len() - gradient_paths;
3383 StreamQuadCounts {
3384 rect: frame.decorations.len() + frame.cosmetic_lines.len(),
3385 sdf: frame.shapes.len(),
3386 quad: frame.glyphs.len()
3387 + solid_paths
3388 + frame.images.len()
3389 + frame.live_images.len()
3390 + composite_quads,
3391 shadow: frame.shadows.len(),
3392 anim_proc: frame.animated_quads.len(),
3393 path_gradient: gradient_paths,
3394 }
3395}
3396
3397fn create_anim_proc_pipeline(
3403 device: &wgpu::Device,
3404 format: wgpu::TextureFormat,
3405) -> (
3406 wgpu::RenderPipeline,
3407 wgpu::Buffer,
3408 wgpu::BindGroup,
3409 wgpu::BindGroupLayout,
3410) {
3411 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
3412 label: Some("anim_procedural_shader"),
3413 source: wgpu::ShaderSource::Wgsl(include_str!("shaders/anim_procedural.wgsl").into()),
3414 });
3415
3416 let buffer_size = (MAX_ANIM_SLOTS * std::mem::size_of::<teksilo_canvas::AnimParams>()) as u64;
3417 let anim_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
3418 label: Some("anim_uniform_buffer"),
3419 size: buffer_size,
3420 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
3421 mapped_at_creation: false,
3422 });
3423
3424 let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3425 label: Some("anim_uniform_bind_group_layout"),
3426 entries: &[wgpu::BindGroupLayoutEntry {
3427 binding: 0,
3428 visibility: wgpu::ShaderStages::FRAGMENT,
3429 ty: wgpu::BindingType::Buffer {
3430 ty: wgpu::BufferBindingType::Uniform,
3431 has_dynamic_offset: false,
3432 min_binding_size: None,
3433 },
3434 count: None,
3435 }],
3436 });
3437
3438 let anim_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
3439 label: Some("anim_uniform_bind_group"),
3440 layout: &bind_group_layout,
3441 entries: &[wgpu::BindGroupEntry {
3442 binding: 0,
3443 resource: anim_uniform_buffer.as_entire_binding(),
3444 }],
3445 });
3446
3447 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
3448 label: Some("anim_proc_pipeline_layout"),
3449 bind_group_layouts: &[Some(&bind_group_layout)],
3450 immediate_size: 0,
3451 });
3452
3453 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
3454 label: Some("anim_proc_pipeline"),
3455 layout: Some(&pipeline_layout),
3456 vertex: wgpu::VertexState {
3457 module: &shader,
3458 entry_point: Some("vs_main"),
3459 buffers: &[Some(anim_quad_vertex_layout())],
3460 compilation_options: Default::default(),
3461 },
3462 fragment: Some(wgpu::FragmentState {
3463 module: &shader,
3464 entry_point: Some("fs_main"),
3465 targets: &[Some(wgpu::ColorTargetState {
3466 format,
3467 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
3468 write_mask: wgpu::ColorWrites::ALL,
3469 })],
3470 compilation_options: Default::default(),
3471 }),
3472 primitive: wgpu::PrimitiveState {
3473 topology: wgpu::PrimitiveTopology::TriangleList,
3474 ..Default::default()
3475 },
3476 depth_stencil: None,
3477 multisample: wgpu::MultisampleState::default(),
3478 multiview_mask: None,
3479 cache: None,
3480 });
3481
3482 (
3483 pipeline,
3484 anim_uniform_buffer,
3485 anim_uniform_bind_group,
3486 bind_group_layout,
3487 )
3488}
3489
3490fn create_anim_sprite_pipeline(
3497 device: &wgpu::Device,
3498 format: wgpu::TextureFormat,
3499 uniform_layout: &wgpu::BindGroupLayout,
3500 texture_layout: &wgpu::BindGroupLayout,
3501) -> wgpu::RenderPipeline {
3502 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
3503 label: Some("anim_sprite_shader"),
3504 source: wgpu::ShaderSource::Wgsl(include_str!("shaders/anim_sprite.wgsl").into()),
3505 });
3506
3507 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
3508 label: Some("anim_sprite_pipeline_layout"),
3509 bind_group_layouts: &[Some(uniform_layout), Some(texture_layout)],
3510 immediate_size: 0,
3511 });
3512
3513 device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
3514 label: Some("anim_sprite_pipeline"),
3515 layout: Some(&pipeline_layout),
3516 vertex: wgpu::VertexState {
3517 module: &shader,
3518 entry_point: Some("vs_main"),
3519 buffers: &[Some(anim_quad_vertex_layout())],
3520 compilation_options: Default::default(),
3521 },
3522 fragment: Some(wgpu::FragmentState {
3523 module: &shader,
3524 entry_point: Some("fs_main"),
3525 targets: &[Some(wgpu::ColorTargetState {
3526 format,
3527 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
3528 write_mask: wgpu::ColorWrites::ALL,
3529 })],
3530 compilation_options: Default::default(),
3531 }),
3532 primitive: wgpu::PrimitiveState {
3533 topology: wgpu::PrimitiveTopology::TriangleList,
3534 ..Default::default()
3535 },
3536 depth_stencil: None,
3537 multisample: wgpu::MultisampleState::default(),
3538 multiview_mask: None,
3539 cache: None,
3540 })
3541}
3542
3543fn anim_quad_vertex_layout() -> wgpu::VertexBufferLayout<'static> {
3545 const ATTRS: [wgpu::VertexAttribute; 3] = [
3546 wgpu::VertexAttribute {
3547 offset: 0,
3548 shader_location: 0,
3549 format: wgpu::VertexFormat::Float32x2,
3550 },
3551 wgpu::VertexAttribute {
3552 offset: 8,
3553 shader_location: 1,
3554 format: wgpu::VertexFormat::Float32x2,
3555 },
3556 wgpu::VertexAttribute {
3557 offset: 16,
3558 shader_location: 2,
3559 format: wgpu::VertexFormat::Uint32,
3560 },
3561 ];
3562 wgpu::VertexBufferLayout {
3563 array_stride: std::mem::size_of::<AnimQuadVertex>() as u64,
3564 step_mode: wgpu::VertexStepMode::Vertex,
3565 attributes: &ATTRS,
3566 }
3567}
3568
3569#[cfg(test)]
3570mod tests {
3571 use teksilo_canvas::RenderFrame;
3572 use teksilo_canvas::render_frame::{DrawCommand, GlyphQuad, PaintData, ShapeKind, ShapeQuad};
3573
3574 use super::*;
3575
3576 #[test]
3577 fn stream_quad_counts_includes_sprite_anim_quads() {
3578 use teksilo_canvas::render_frame::{AnimatedQuadClass, AnimatedQuadDraw};
3585
3586 let mut frame = RenderFrame::new();
3587 for slot in 0..3 {
3588 frame.animated_quads.push(AnimatedQuadDraw {
3589 screen: [0.0, 0.0, 10.0, 10.0],
3590 slot,
3591 class: AnimatedQuadClass::Procedural,
3592 });
3593 }
3594 for slot in 3..5 {
3595 frame.animated_quads.push(AnimatedQuadDraw {
3596 screen: [0.0, 0.0, 10.0, 10.0],
3597 slot,
3598 class: AnimatedQuadClass::Sprite {
3599 image_name: "icon".to_string(),
3600 },
3601 });
3602 }
3603 frame.glyphs.push(GlyphQuad {
3604 screen: [0.0, 0.0, 8.0, 8.0],
3605 atlas: [0.0, 0.0, 2.0, 2.0],
3606 color: [1.0; 4],
3607 is_color: false,
3608 });
3609
3610 let counts = stream_quad_counts(&frame);
3611 assert_eq!(
3612 counts.anim_proc, 5,
3613 "anim_proc stream must be sized for BOTH Procedural and Sprite quads"
3614 );
3615 assert_eq!(counts.quad, 1);
3616 assert_eq!(counts.rect, 0);
3617 assert_eq!(counts.sdf, 0);
3618 assert_eq!(counts.shadow, 0);
3619 assert_eq!(counts.max(), 5, "index buffer sizes to the largest stream");
3620 }
3621
3622 #[test]
3623 fn stream_quad_counts_splits_solid_and_gradient_paths() {
3624 use teksilo_canvas::render_frame::PathEntry;
3630 use teksilo_canvas::{FillRule, GradientStop, Path, StrokeStyle};
3631 use teksilo_tokens::Color;
3632
3633 let mut frame = RenderFrame::new();
3634 frame.paths.push(PathEntry {
3635 path: Path::new(),
3636 color: [1.0, 0.0, 0.0, 1.0],
3637 stroke_style: StrokeStyle::solid(0.0),
3638 fill_rule: FillRule::Winding,
3639 bounds: [0.0, 0.0, 10.0, 10.0],
3640 paint_data: PaintData::Solid,
3641 });
3642 frame.paths.push(PathEntry {
3643 path: Path::new(),
3644 color: [1.0, 1.0, 1.0, 1.0],
3645 stroke_style: StrokeStyle::solid(0.0),
3646 fill_rule: FillRule::Winding,
3647 bounds: [0.0, 0.0, 20.0, 20.0],
3648 paint_data: PaintData::LinearGradient {
3649 start: [0.0, 0.0],
3650 end: [20.0, 0.0],
3651 stops: vec![
3652 GradientStop {
3653 offset: 0.0,
3654 color: Color::RED,
3655 },
3656 GradientStop {
3657 offset: 1.0,
3658 color: Color::BLUE,
3659 },
3660 ],
3661 },
3662 });
3663
3664 let counts = stream_quad_counts(&frame);
3665 assert_eq!(counts.quad, 1, "the solid path counts toward quad");
3666 assert_eq!(
3667 counts.path_gradient, 1,
3668 "the gradient path counts toward path_gradient, not quad"
3669 );
3670 assert_eq!(counts.rect, 0);
3671 assert_eq!(counts.sdf, 0);
3672 assert_eq!(counts.shadow, 0);
3673 assert_eq!(counts.anim_proc, 0);
3674 assert_eq!(counts.max(), 1);
3675 }
3676
3677 #[test]
3678 fn gradient_path_renders_nonflat_on_gpu() {
3679 use teksilo_canvas::render_frame::PathEntry;
3686 use teksilo_canvas::{FillRule, GradientStop, Path, Rect, StrokeStyle};
3687 use teksilo_tokens::Color;
3688
3689 let Some((mut renderer, device, queue)) = pollster::block_on(
3690 crate::test_support::require_test_renderer("teksilo_render_gradient_path_device"),
3691 ) else {
3692 return; };
3694
3695 let path = Path::rect(Rect::new(1.0, 1.0, 30.0, 30.0));
3697 let bounds = path.bounds();
3698 let mut frame = RenderFrame::new();
3699 frame.paths.push(PathEntry {
3700 path,
3701 color: [1.0, 1.0, 1.0, 1.0],
3702 stroke_style: StrokeStyle::solid(0.0),
3703 fill_rule: FillRule::Winding,
3704 bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
3705 paint_data: PaintData::LinearGradient {
3706 start: [bounds.x, bounds.y],
3707 end: [bounds.x + bounds.width, bounds.y],
3708 stops: vec![
3709 GradientStop {
3710 offset: 0.0,
3711 color: Color::RED,
3712 },
3713 GradientStop {
3714 offset: 1.0,
3715 color: Color::BLUE,
3716 },
3717 ],
3718 },
3719 });
3720 frame.draw_order.push(DrawCommand::Path(0));
3721
3722 let texture = device.create_texture(&wgpu::TextureDescriptor {
3723 label: Some("teksilo_render_gradient_path_target"),
3724 size: wgpu::Extent3d {
3725 width: 32,
3726 height: 32,
3727 depth_or_array_layers: 1,
3728 },
3729 mip_level_count: 1,
3730 sample_count: 1,
3731 dimension: wgpu::TextureDimension::D2,
3732 format: wgpu::TextureFormat::Rgba8UnormSrgb,
3733 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
3734 view_formats: &[],
3735 });
3736 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3737
3738 renderer.render(&frame, &view, 1.0, 32, 32, [0.0, 0.0, 0.0, 0.0]);
3742
3743 let pixels = crate::test_support::read_texture_rgba(&device, &queue, &texture, 32, 32);
3744 let px = |x: usize, y: usize| {
3745 let i = (y * 32 + x) * 4;
3746 [pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
3747 };
3748 let left = px(4, 16);
3750 let right = px(27, 16);
3751
3752 assert!(
3753 left[3] > 200 && right[3] > 200,
3754 "gradient square not covered (coverage-mask atlas broken): left={left:?} right={right:?}"
3755 );
3756 assert!(
3759 left[0] as i32 > left[2] as i32 + 40,
3760 "left edge must be red-dominant, got {left:?}"
3761 );
3762 assert!(
3763 right[2] as i32 > right[0] as i32 + 40,
3764 "right edge must be blue-dominant, got {right:?}"
3765 );
3766 assert!(
3767 (left[0] as i32 - right[0] as i32).abs() > 60,
3768 "gradient looks flat (shader not sampling the gradient): left={left:?} right={right:?}"
3769 );
3770 }
3771
3772 #[test]
3773 fn gradient_path_partial_alpha_preserved() {
3774 use teksilo_canvas::render_frame::PathEntry;
3781 use teksilo_canvas::{FillRule, GradientStop, Path, Rect, StrokeStyle};
3782 use teksilo_tokens::Color;
3783
3784 let Some((mut renderer, device, queue)) = pollster::block_on(
3785 crate::test_support::require_test_renderer("teksilo_render_partial_alpha_device"),
3786 ) else {
3787 return;
3788 };
3789
3790 let path = Path::rect(Rect::new(0.0, 0.0, 32.0, 32.0));
3791 let bounds = path.bounds();
3792 let mut frame = RenderFrame::new();
3793 frame.paths.push(PathEntry {
3794 path,
3795 color: [1.0, 1.0, 1.0, 1.0],
3796 stroke_style: StrokeStyle::solid(0.0),
3797 fill_rule: FillRule::Winding,
3798 bounds: [bounds.x, bounds.y, bounds.width, bounds.height],
3799 paint_data: PaintData::LinearGradient {
3800 start: [0.0, 0.0],
3801 end: [32.0, 0.0],
3802 stops: vec![
3803 GradientStop {
3804 offset: 0.0,
3805 color: Color::from_rgba(0.0, 0.62, 0.45, 1.0),
3806 },
3807 GradientStop {
3808 offset: 1.0,
3809 color: Color::from_rgba(0.0, 0.62, 0.45, 0.4),
3810 },
3811 ],
3812 },
3813 });
3814 frame.draw_order.push(DrawCommand::Path(0));
3815
3816 let texture = device.create_texture(&wgpu::TextureDescriptor {
3817 label: Some("partial_alpha_target"),
3818 size: wgpu::Extent3d {
3819 width: 32,
3820 height: 32,
3821 depth_or_array_layers: 1,
3822 },
3823 mip_level_count: 1,
3824 sample_count: 1,
3825 dimension: wgpu::TextureDimension::D2,
3826 format: wgpu::TextureFormat::Rgba8UnormSrgb,
3827 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
3828 view_formats: &[],
3829 });
3830 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3831 renderer.render(&frame, &view, 1.0, 32, 32, [0.0, 0.0, 0.0, 0.0]);
3832
3833 let px = crate::test_support::read_texture_rgba(&device, &queue, &texture, 32, 32);
3834 let alpha = |x: usize| px[(16 * 32 + x) * 4 + 3];
3835 let (left, right) = (alpha(2), alpha(29));
3836 assert!(
3838 left >= 240,
3839 "opaque (a=1.0) end must stay opaque, got {left} (/255)"
3840 );
3841 assert!(
3842 (90..=115).contains(&right),
3843 "a=0.4 stop must read ~102/255, got {right} — a value near ~61 means the \
3844 pipeline under-renders gradient stop alpha (washed-out fills)"
3845 );
3846 }
3847
3848 #[test]
3849 fn glyph_quad_renders_over_shape_in_offscreen_target() {
3850 let Some((mut renderer, device, queue)) = pollster::block_on(
3851 crate::test_support::require_test_renderer("teksilo_render_test_device"),
3852 ) else {
3853 return;
3854 };
3855
3856 renderer.upload_atlas(
3857 2,
3858 2,
3859 &[
3860 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
3861 ],
3862 );
3863
3864 let mut frame = RenderFrame::new();
3865 frame.shapes.push(ShapeQuad {
3866 screen: [4.0, 4.0, 24.0, 24.0],
3867 color: [0.2, 0.6, 0.9, 1.0],
3868 shape: ShapeKind::RoundedRect,
3869 stroke_width: 0.0,
3870 stroke_space: teksilo_canvas::StrokeSpace::Logical,
3871 corner_radii: [0.0; 4],
3872 paint_data: PaintData::Solid,
3873 });
3874 frame.draw_order.push(DrawCommand::Shape(0));
3875
3876 frame.glyphs.push(GlyphQuad {
3877 screen: [10.0, 10.0, 8.0, 8.0],
3878 atlas: [0.0, 0.0, 2.0, 2.0],
3879 color: [1.0, 1.0, 1.0, 1.0],
3880 is_color: false,
3881 });
3882 frame.draw_order.push(DrawCommand::Glyph(0));
3883
3884 let texture = device.create_texture(&wgpu::TextureDescriptor {
3885 label: Some("teksilo_render_test_target"),
3886 size: wgpu::Extent3d {
3887 width: 32,
3888 height: 32,
3889 depth_or_array_layers: 1,
3890 },
3891 mip_level_count: 1,
3892 sample_count: 1,
3893 dimension: wgpu::TextureDimension::D2,
3894 format: wgpu::TextureFormat::Rgba8UnormSrgb,
3895 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
3896 view_formats: &[],
3897 });
3898 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3899
3900 renderer.render(&frame, &view, 1.0, 32, 32, [0.0, 0.0, 0.0, 0.0]);
3901
3902 let pixels = crate::test_support::read_texture_rgba(&device, &queue, &texture, 32, 32);
3903 let center = ((14 * 32 + 14) * 4) as usize;
3904 let blue_only = [
3905 pixels[center],
3906 pixels[center + 1],
3907 pixels[center + 2],
3908 pixels[center + 3],
3909 ];
3910
3911 assert!(
3912 blue_only[0] > 200 && blue_only[1] > 200 && blue_only[2] > 200,
3913 "expected glyph pixel to be visible over shape, got {:?}",
3914 blue_only
3915 );
3916 }
3917
3918 #[test]
3919 fn glyph_edges_are_blended_as_text_contrast_says() {
3920 use crate::text_contrast::TextContrast;
3924
3925 let Some((mut renderer, device, queue)) = pollster::block_on(
3926 crate::test_support::require_test_renderer("teksilo_render_text_contrast_device"),
3927 ) else {
3928 return;
3929 };
3930
3931 const W: u32 = 32;
3932 let mut atlas = vec![0u8; (W * 4) as usize];
3933 for x in 0..W as usize {
3934 let coverage = (x * 255 / (W as usize - 1)) as u8;
3935 atlas[x * 4..x * 4 + 4].copy_from_slice(&[255, 255, 255, coverage]);
3936 }
3937 renderer.upload_atlas(W, 1, &atlas);
3938
3939 let texture = device.create_texture(&wgpu::TextureDescriptor {
3940 label: Some("text_contrast_target"),
3941 size: wgpu::Extent3d {
3942 width: W,
3943 height: 1,
3944 depth_or_array_layers: 1,
3945 },
3946 mip_level_count: 1,
3947 sample_count: 1,
3948 dimension: wgpu::TextureDimension::D2,
3949 format: wgpu::TextureFormat::Rgba8UnormSrgb,
3950 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
3951 view_formats: &[],
3952 });
3953 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
3954
3955 let encode = |x: f32| {
3956 let x = x.clamp(0.0, 1.0);
3957 let e = if x <= 0.003_130_8 {
3958 x * 12.92
3959 } else {
3960 1.055 * x.powf(1.0 / 2.4) - 0.055
3961 };
3962 (e * 255.0).round() as i32
3963 };
3964
3965 for contrast in [TextContrast::OFF, TextContrast::DEFAULT] {
3966 renderer.set_text_contrast(contrast);
3967 for (text, page) in [(0.0_f32, 1.0_f32), (1.0, 0.0)] {
3968 let mut frame = RenderFrame::new();
3969 frame.glyphs.push(GlyphQuad {
3970 screen: [0.0, 0.0, W as f32, 1.0],
3971 atlas: [0.0, 0.0, W as f32, 1.0],
3972 color: [text, text, text, 1.0],
3973 is_color: false,
3974 });
3975 frame.draw_order.push(DrawCommand::Glyph(0));
3976 renderer.render(&frame, &view, 1.0, W, 1, [page, page, page, 1.0]);
3977 let pixels =
3978 crate::test_support::read_texture_rgba(&device, &queue, &texture, W, 1);
3979 for x in 0..W as usize {
3980 let raw = (x * 255 / (W as usize - 1)) as f32 / 255.0;
3981 let a = contrast.corrected_coverage(raw, [text; 3]);
3982 let expected = encode(page + (text - page) * a);
3984 let got = pixels[x * 4] as i32;
3985 assert!(
3986 (got - expected).abs() <= 2,
3987 "{contrast:?}, text {text} on {page}, coverage {raw}: \
3988 shader wrote {got}, the CPU model says {expected}"
3989 );
3990 }
3991 }
3992 }
3993 }
3994
3995 #[test]
3996 fn fractional_origin_glyph_renders_pixel_exact() {
3997 let Some((mut renderer, device, queue)) = pollster::block_on(
4006 crate::test_support::require_test_renderer("teksilo_render_snap_test_device"),
4007 ) else {
4008 return;
4009 };
4010
4011 let mut atlas = [0u8; 4 * 4 * 4];
4014 for y in 0..3 {
4015 for x in 0..3 {
4016 let i = (y * 4 + x) * 4;
4017 atlas[i..i + 4].copy_from_slice(&[255, 255, 255, 255]);
4018 }
4019 }
4020 renderer.upload_atlas(4, 4, &atlas);
4021
4022 let mut frame = RenderFrame::new();
4023 frame.glyphs.push(GlyphQuad {
4025 screen: [10.4, 10.6, 3.0, 3.0],
4026 atlas: [0.0, 0.0, 3.0, 3.0],
4027 color: [1.0, 1.0, 1.0, 1.0],
4028 is_color: false,
4029 });
4030 frame.draw_order.push(DrawCommand::Glyph(0));
4031
4032 let texture = device.create_texture(&wgpu::TextureDescriptor {
4033 label: Some("teksilo_render_snap_test_target"),
4034 size: wgpu::Extent3d {
4035 width: 32,
4036 height: 32,
4037 depth_or_array_layers: 1,
4038 },
4039 mip_level_count: 1,
4040 sample_count: 1,
4041 dimension: wgpu::TextureDimension::D2,
4042 format: wgpu::TextureFormat::Rgba8UnormSrgb,
4043 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4044 view_formats: &[],
4045 });
4046 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4047
4048 renderer.render(&frame, &view, 1.0, 32, 32, [0.0, 0.0, 0.0, 0.0]);
4049
4050 let pixels = crate::test_support::read_texture_rgba(&device, &queue, &texture, 32, 32);
4051 let alpha = |x: usize, y: usize| pixels[(y * 32 + x) * 4 + 3];
4052
4053 for y in 11..14 {
4057 for x in 10..13 {
4058 assert_eq!(
4059 alpha(x, y),
4060 255,
4061 "interior pixel ({x},{y}) must be fully opaque — \
4062 bilinear edge feathering means the snap did not fire"
4063 );
4064 }
4065 }
4066 for y in 10..15 {
4069 for x in 9..14 {
4070 let inside = (10..13).contains(&x) && (11..14).contains(&y);
4071 if !inside {
4072 assert_eq!(
4073 alpha(x, y),
4074 0,
4075 "ring pixel ({x},{y}) must be untouched — \
4076 the snapped quad must not bleed past its bitmap"
4077 );
4078 }
4079 }
4080 }
4081 }
4082
4083 #[test]
4096 fn fractional_origin_path_renders_pixel_exact() {
4097 let Some((mut renderer, device, queue)) = pollster::block_on(
4098 crate::test_support::require_test_renderer("teksilo_render_path_snap_test_device"),
4099 ) else {
4100 return;
4101 };
4102
4103 let mut path = teksilo_canvas::Path::new();
4106 path.move_to(teksilo_canvas::Point::new(8.5, 4.0));
4107 path.line_to(teksilo_canvas::Point::new(8.5, 12.0));
4108 let stroke_style = teksilo_canvas::StrokeStyle::solid(1.0);
4109 let bounds = path.bounds().expand(stroke_style.width);
4110 assert_eq!(bounds.x, 7.5, "the half-pixel origin this test is about");
4111
4112 let mut frame = RenderFrame::new();
4113 frame.paths.push(teksilo_canvas::PathEntry {
4114 path,
4115 color: [1.0, 1.0, 1.0, 1.0],
4116 stroke_style,
4117 fill_rule: teksilo_canvas::FillRule::Winding,
4118 bounds: bounds.to_array(),
4119 paint_data: teksilo_canvas::PaintData::Solid,
4120 });
4121 frame.draw_order.push(DrawCommand::Path(0));
4122
4123 let texture = device.create_texture(&wgpu::TextureDescriptor {
4124 label: Some("teksilo_render_path_snap_test_target"),
4125 size: wgpu::Extent3d {
4126 width: 32,
4127 height: 32,
4128 depth_or_array_layers: 1,
4129 },
4130 mip_level_count: 1,
4131 sample_count: 1,
4132 dimension: wgpu::TextureDimension::D2,
4133 format: wgpu::TextureFormat::Rgba8UnormSrgb,
4134 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4135 view_formats: &[],
4136 });
4137 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4138
4139 renderer.render(&frame, &view, 1.0, 32, 32, [0.0, 0.0, 0.0, 0.0]);
4140
4141 let pixels = crate::test_support::read_texture_rgba(&device, &queue, &texture, 32, 32);
4142 let alpha = |x: usize, y: usize| pixels[(y * 32 + x) * 4 + 3];
4143
4144 for y in 5..11 {
4145 assert_eq!(
4146 alpha(8, y),
4147 255,
4148 "the hairline's own column must be fully inked at y={y} — \
4149 anything less means the quad was resampled off the pixel grid"
4150 );
4151 for x in [6, 7, 9, 10] {
4152 assert_eq!(
4153 alpha(x, y),
4154 0,
4155 "({x},{y}) must be untouched — a 1 px stroke that leaks \
4156 into its neighbours is the blur this snap removes"
4157 );
4158 }
4159 }
4160 }
4161
4162 fn render_to_pixels(
4165 renderer: &mut Renderer,
4166 device: &wgpu::Device,
4167 queue: &wgpu::Queue,
4168 frame: &RenderFrame,
4169 ) -> Vec<u8> {
4170 let texture = device.create_texture(&wgpu::TextureDescriptor {
4171 label: Some("teksilo_render_blur_isolation_target"),
4172 size: wgpu::Extent3d {
4173 width: 64,
4174 height: 32,
4175 depth_or_array_layers: 1,
4176 },
4177 mip_level_count: 1,
4178 sample_count: 1,
4179 dimension: wgpu::TextureDimension::D2,
4180 format: wgpu::TextureFormat::Rgba8UnormSrgb,
4181 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4182 view_formats: &[],
4183 });
4184 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4185 renderer.render(frame, &view, 1.0, 64, 32, [0.0, 0.0, 0.0, 0.0]);
4186 crate::test_support::read_texture_rgba(device, queue, &texture, 64, 32)
4187 }
4188
4189 fn push_blurred_square(
4191 frame: &mut RenderFrame,
4192 bounds: teksilo_canvas::Rect,
4193 radius: f32,
4194 square: teksilo_canvas::Rect,
4195 ) {
4196 frame
4197 .draw_order
4198 .push(DrawCommand::BeginBlurredSubtree { bounds, radius });
4199 let idx = frame.decorations.len();
4200 frame.decorations.push(teksilo_canvas::DecorationRect {
4201 rect: square.to_array(),
4202 color: [1.0, 1.0, 1.0, 1.0],
4203 kind: teksilo_canvas::DecorationKind::WidgetBackground,
4204 });
4205 frame.draw_order.push(DrawCommand::Decoration(idx));
4206 frame.draw_order.push(DrawCommand::EndBlurredSubtree);
4207 }
4208
4209 #[test]
4210 fn a_blur_scope_does_not_take_the_kernel_of_a_later_one() {
4211 use teksilo_canvas::Rect;
4212 let Some((mut renderer, device, queue)) = pollster::block_on(
4213 crate::test_support::require_test_renderer("teksilo_render_blur_isolation_device"),
4214 ) else {
4215 return; };
4217
4218 let a_bounds = Rect::new(0.0, 0.0, 32.0, 32.0);
4220 let a_square = Rect::new(12.0, 12.0, 8.0, 8.0);
4221 let mut alone = RenderFrame::new();
4222 push_blurred_square(&mut alone, a_bounds, 6.0, a_square);
4223
4224 let mut followed = RenderFrame::new();
4228 push_blurred_square(&mut followed, a_bounds, 6.0, a_square);
4229 push_blurred_square(
4230 &mut followed,
4231 Rect::new(40.0, 8.0, 16.0, 16.0),
4232 2.0,
4233 Rect::new(44.0, 12.0, 8.0, 8.0),
4234 );
4235
4236 let a_alone = render_to_pixels(&mut renderer, &device, &queue, &alone);
4237 let a_followed = render_to_pixels(&mut renderer, &device, &queue, &followed);
4238 let region = |pixels: &[u8]| -> Vec<u8> {
4239 (0..32)
4240 .flat_map(|y| pixels[y * 64 * 4..(y * 64 + 32) * 4].to_vec())
4241 .collect()
4242 };
4243 assert!(
4244 region(&a_alone).iter().any(|&b| b != 0),
4245 "scope A must have drawn something"
4246 );
4247 assert_eq!(
4248 region(&a_alone),
4249 region(&a_followed),
4250 "scope A must blur the same whatever blur scope follows it in the frame"
4251 );
4252 }
4253
4254 #[test]
4255 fn each_kawase_pass_gets_its_own_parameter_slot() {
4256 let Some((_renderer, device, queue)) = pollster::block_on(
4257 crate::test_support::require_test_renderer("teksilo_render_blur_slots_device"),
4258 ) else {
4259 return; };
4261 let mut arena = crate::blur::KawaseParamArena::new(&device);
4262 let passes = crate::blur::PARAM_SLOTS_PER_SCOPE + 3;
4264 arena.begin_frame(&device, passes);
4265 let offsets: Vec<u32> = (0..passes)
4266 .map(|i| {
4267 let v = i as f32;
4268 arena.push(
4269 &queue,
4270 &crate::blur::BlurParams {
4271 offset: [v, v + 0.5, 0.0, 0.0],
4272 },
4273 )
4274 })
4275 .collect();
4276 let stride = arena.slot_stride();
4277 for (i, offset) in offsets.iter().enumerate() {
4278 assert_eq!(u64::from(*offset), stride * i as u64);
4279 assert_eq!(
4280 u64::from(*offset) % u64::from(device.limits().min_uniform_buffer_offset_alignment),
4281 0,
4282 "dynamic offsets must respect the device alignment"
4283 );
4284 }
4285
4286 let size = arena.buffer().size();
4287 let readback = device.create_buffer(&wgpu::BufferDescriptor {
4288 label: Some("blur_params_readback"),
4289 size,
4290 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
4291 mapped_at_creation: false,
4292 });
4293 let mut encoder =
4294 device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
4295 encoder.copy_buffer_to_buffer(arena.buffer(), 0, &readback, 0, size);
4296 queue.submit(Some(encoder.finish()));
4297 readback.slice(..).map_async(wgpu::MapMode::Read, |_| {});
4298 device
4299 .poll(wgpu::PollType::Wait {
4300 submission_index: None,
4301 timeout: None,
4302 })
4303 .expect("poll");
4304 let bytes = readback
4305 .slice(..)
4306 .get_mapped_range()
4307 .expect("mapped readback")
4308 .to_vec();
4309 for (i, offset) in offsets.iter().enumerate() {
4310 let at = *offset as usize;
4311 let slot: &[f32] = bytemuck::cast_slice(&bytes[at..at + 16]);
4312 assert_eq!(slot, &[i as f32, i as f32 + 0.5, 0.0, 0.0], "slot {i}");
4313 }
4314 }
4315
4316 fn render_scaled(
4319 renderer: &mut Renderer,
4320 device: &wgpu::Device,
4321 queue: &wgpu::Queue,
4322 frame: &RenderFrame,
4323 scale: f32,
4324 (w, h): (u32, u32),
4325 ) -> impl Fn(u32, u32) -> [u8; 4] {
4326 let texture = device.create_texture(&wgpu::TextureDescriptor {
4327 label: Some("teksilo_render_clip_target"),
4328 size: wgpu::Extent3d {
4329 width: w,
4330 height: h,
4331 depth_or_array_layers: 1,
4332 },
4333 mip_level_count: 1,
4334 sample_count: 1,
4335 dimension: wgpu::TextureDimension::D2,
4336 format: wgpu::TextureFormat::Rgba8UnormSrgb,
4337 usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4338 view_formats: &[],
4339 });
4340 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4341 renderer.render(frame, &view, scale, w, h, [0.0, 0.0, 0.0, 0.0]);
4342 let pixels = crate::test_support::read_texture_rgba(device, queue, &texture, w, h);
4343 move |x, y| {
4344 let i = ((y * w + x) * 4) as usize;
4345 [pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
4346 }
4347 }
4348
4349 fn push_white_rect(frame: &mut RenderFrame, rect: teksilo_canvas::Rect) {
4350 let idx = frame.decorations.len();
4351 frame.decorations.push(teksilo_canvas::DecorationRect {
4352 rect: rect.to_array(),
4353 color: [1.0, 1.0, 1.0, 1.0],
4354 kind: teksilo_canvas::DecorationKind::WidgetBackground,
4355 });
4356 frame.draw_order.push(DrawCommand::Decoration(idx));
4357 }
4358
4359 #[test]
4360 fn a_clip_under_a_translation_lands_where_the_content_does_at_fractional_scale() {
4361 use teksilo_canvas::Rect;
4362 let Some((mut renderer, device, queue)) = pollster::block_on(
4363 crate::test_support::require_test_renderer("teksilo_render_clip_translate_device"),
4364 ) else {
4365 return; };
4367 let mut frame = RenderFrame::new();
4371 frame
4372 .draw_order
4373 .push(DrawCommand::PushTransform(Transform2D::translate(
4374 10.0, 0.0,
4375 )));
4376 frame
4377 .draw_order
4378 .push(DrawCommand::SetClip(Rect::new(0.0, 0.0, 20.0, 20.0)));
4379 push_white_rect(&mut frame, Rect::new(0.0, 0.0, 40.0, 20.0));
4380 frame.draw_order.push(DrawCommand::ClearClip);
4381 frame.draw_order.push(DrawCommand::PopTransform);
4382
4383 let px = render_scaled(&mut renderer, &device, &queue, &frame, 1.5, (96, 40));
4384 assert_eq!(px(17, 10)[3], 255, "inside the clip, near its leading edge");
4385 assert_eq!(
4386 px(43, 10)[3],
4387 255,
4388 "inside the clip, near its trailing edge"
4389 );
4390 assert_eq!(px(47, 10)[3], 0, "past the clip's trailing edge");
4391 assert_eq!(px(12, 10)[3], 0, "before the content starts");
4392 }
4393
4394 #[test]
4395 fn a_clip_still_applies_after_a_blur_scope_reopens_the_pass() {
4396 use teksilo_canvas::Rect;
4397 let Some((mut renderer, device, queue)) = pollster::block_on(
4398 crate::test_support::require_test_renderer("teksilo_render_clip_after_blur_device"),
4399 ) else {
4400 return; };
4402 let mut frame = RenderFrame::new();
4406 frame
4407 .draw_order
4408 .push(DrawCommand::SetClip(Rect::new(0.0, 0.0, 20.0, 32.0)));
4409 push_blurred_square(
4410 &mut frame,
4411 Rect::new(0.0, 0.0, 16.0, 16.0),
4412 2.0,
4413 Rect::new(4.0, 4.0, 8.0, 8.0),
4414 );
4415 push_white_rect(&mut frame, Rect::new(0.0, 20.0, 64.0, 12.0));
4416 frame.draw_order.push(DrawCommand::ClearClip);
4417
4418 let px = render_scaled(&mut renderer, &device, &queue, &frame, 1.0, (64, 32));
4419 assert_eq!(px(10, 26)[3], 255, "inside the clip");
4420 assert_eq!(px(40, 26)[3], 0, "outside the clip");
4421 }
4422
4423 #[test]
4424 fn a_clip_set_before_a_blur_scope_does_not_clip_inside_its_intermediate() {
4425 use teksilo_canvas::Rect;
4426 let Some((mut renderer, device, queue)) = pollster::block_on(
4427 crate::test_support::require_test_renderer("teksilo_render_clip_into_blur_device"),
4428 ) else {
4429 return; };
4431 let mut frame = RenderFrame::new();
4437 frame
4438 .draw_order
4439 .push(DrawCommand::SetClip(Rect::new(30.0, 0.0, 34.0, 32.0)));
4440 push_blurred_square(
4441 &mut frame,
4442 Rect::new(30.0, 0.0, 16.0, 16.0),
4443 2.0,
4444 Rect::new(32.0, 2.0, 12.0, 12.0),
4445 );
4446 frame.draw_order.push(DrawCommand::ClearClip);
4447
4448 let px = render_scaled(&mut renderer, &device, &queue, &frame, 1.0, (64, 32));
4449 assert!(
4450 px(38, 8)[3] > 128,
4451 "the blurred square shows at the centre of the scope, got {:?}",
4452 px(38, 8)
4453 );
4454 }
4455
4456 #[test]
4457 fn a_clip_opened_inside_a_blur_scope_stays_in_the_intermediates_space() {
4458 use teksilo_canvas::Rect;
4459 let Some((mut renderer, device, queue)) = pollster::block_on(
4460 crate::test_support::require_test_renderer("teksilo_render_clip_inside_blur_device"),
4461 ) else {
4462 return; };
4464 let mut frame = RenderFrame::new();
4472 frame
4473 .draw_order
4474 .push(DrawCommand::SetClip(Rect::new(30.0, 0.0, 34.0, 32.0)));
4475 let scope = Rect::new(30.0, 0.0, 16.0, 16.0);
4476 frame.draw_order.push(DrawCommand::BeginBlurredSubtree {
4477 bounds: scope,
4478 radius: 2.0,
4479 });
4480 frame.draw_order.push(DrawCommand::SetClip(scope));
4481 push_white_rect(&mut frame, Rect::new(32.0, 2.0, 12.0, 12.0));
4482 frame.draw_order.push(DrawCommand::ClearClip);
4483 push_white_rect(&mut frame, Rect::new(32.0, 2.0, 12.0, 12.0));
4484 frame.draw_order.push(DrawCommand::EndBlurredSubtree);
4485 frame.draw_order.push(DrawCommand::ClearClip);
4486
4487 let px = render_scaled(&mut renderer, &device, &queue, &frame, 1.0, (64, 32));
4488 assert!(
4489 px(38, 8)[3] > 128,
4490 "the square drawn inside the scope shows, got {:?}",
4491 px(38, 8)
4492 );
4493 }
4494
4495 #[test]
4496 fn a_clip_that_starts_before_the_target_keeps_its_far_edge() {
4497 use teksilo_canvas::Rect;
4498 let Some((mut renderer, device, queue)) = pollster::block_on(
4499 crate::test_support::require_test_renderer("teksilo_render_clip_negative_device"),
4500 ) else {
4501 return; };
4503 let mut frame = RenderFrame::new();
4506 frame
4507 .draw_order
4508 .push(DrawCommand::SetClip(Rect::new(-10.0, 0.0, 30.0, 20.0)));
4509 push_white_rect(&mut frame, Rect::new(0.0, 0.0, 64.0, 20.0));
4510 frame.draw_order.push(DrawCommand::ClearClip);
4511
4512 let px = render_scaled(&mut renderer, &device, &queue, &frame, 1.0, (64, 32));
4513 assert_eq!(px(18, 10)[3], 255, "inside the clip");
4514 assert_eq!(px(24, 10)[3], 0, "past the clip's far edge");
4515 }
4516}