1pub use ::wgpu;
11
12mod atlas;
13mod effects_pass;
14pub mod interop;
15mod layer_pool;
16mod offscreen;
17mod pipeline;
18mod ramp;
19mod shared_exporter;
20mod window;
21
22pub use interop::{ExportedHandle, ExternalSyncHandle};
23pub use offscreen::WgpuOffscreenRenderer;
24pub use pipeline::WgpuRenderer;
25pub use shared_exporter::{SharedFrameLease, SharedSlot, WgpuSharedExportRenderer};
26pub use window::{PreparedWgpuContext, WgpuWindowRenderer};
27
28use core::future::Future;
29use core::pin::pin;
30use core::task::{Context, Poll, Waker};
31use std::sync::{Arc, Condvar, Mutex};
32use std::task::Wake;
33use std::vec::Vec;
34
35use crate::motion::{DrawOp, DrawPayload};
36use crate::renderers::software::compute_unoccluded_clip;
37use crate::solver::Region;
38use crate::style::Color;
39
40#[repr(C)]
42#[derive(Copy, Clone, Debug, Default, PartialEq)]
43pub struct GpuPrimitive {
44 pub bounds: [f32; 4],
46 pub clip: [f32; 4],
48 pub uv: [f32; 4],
50 pub color0: [f32; 4],
52 pub color1: [f32; 4],
54 pub border_color: [f32; 4],
56 pub params: [f32; 4],
60 pub extra: [f32; 4],
62 pub radii: [f32; 4],
64 pub grad_a: [f32; 4],
66 pub grad_b: [f32; 4],
68 pub xform: [f32; 4],
70}
71
72pub(crate) const KIND_QUAD: f32 = 0.0;
73pub(crate) const KIND_SHADOW: f32 = 1.0;
74pub(crate) const KIND_GLYPH: f32 = 2.0;
75pub(crate) const KIND_SPRITE: f32 = 3.0;
76pub(crate) const KIND_ARC: f32 = 4.0;
77pub(crate) const IDENTITY_XFORM: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
78
79#[repr(C)]
80#[derive(Copy, Clone, Debug, Default)]
81pub(crate) struct ViewportUniform {
82 pub(crate) size: [f32; 2],
83 pub(crate) is_srgb: f32,
84 pub(crate) _pad: f32,
85}
86
87#[inline]
88pub(crate) fn pod_as_bytes<T: Copy>(slice: &[T]) -> &[u8] {
89 unsafe {
90 core::slice::from_raw_parts(
91 slice.as_ptr() as *const u8,
92 core::mem::size_of_val(slice),
93 )
94 }
95}
96
97#[inline(always)]
98pub(crate) fn color_to_f32(c: Color) -> [f32; 4] {
99 const INV: f32 = 1.0 / 255.0;
100 [
101 (c.r() as f32) * INV,
102 (c.g() as f32) * INV,
103 (c.b() as f32) * INV,
104 (c.a() as f32) * INV,
105 ]
106}
107
108#[inline]
109#[allow(clippy::too_many_arguments)]
110pub(crate) fn make_quad_primitive(
111 bounds: [f32; 4],
112 clip: [f32; 4],
113 clip_radius: f32,
114 corner_radius: f32,
115 border_width: f32,
116 horiz_grad: bool,
117 bg: Color,
118 bg_grad: Color,
119 border_color: Color,
120) -> GpuPrimitive {
121 GpuPrimitive {
122 bounds,
123 clip,
124 uv: [0.0; 4],
125 color0: color_to_f32(bg),
126 color1: color_to_f32(bg_grad),
127 border_color: color_to_f32(border_color),
128 params: [
129 corner_radius,
130 border_width,
131 KIND_QUAD,
132 if horiz_grad { 1.0 } else { 0.0 },
133 ],
134 extra: [clip_radius, 0.0, 0.0, 0.0],
135 radii: [corner_radius; 4],
136 grad_a: [0.0; 4],
137 grad_b: [0.0; 4],
138 xform: IDENTITY_XFORM,
139 }
140}
141
142#[inline]
143pub(crate) fn make_shadow_primitive(
144 bounds: [f32; 4],
145 clip: [f32; 4],
146 clip_radius: f32,
147 corner_radius: f32,
148 blur_radius: f32,
149 color: Color,
150) -> GpuPrimitive {
151 GpuPrimitive {
152 bounds,
153 clip,
154 uv: [0.0; 4],
155 color0: color_to_f32(color),
156 color1: [0.0; 4],
157 border_color: [0.0; 4],
158 params: [corner_radius, blur_radius, KIND_SHADOW, 0.0],
159 extra: [clip_radius, 0.0, 0.0, 0.0],
160 radii: [corner_radius; 4],
161 grad_a: [0.0; 4],
162 grad_b: [0.0; 4],
163 xform: IDENTITY_XFORM,
164 }
165}
166
167#[inline]
168#[allow(clippy::too_many_arguments)]
169pub(crate) fn make_arc_primitive(
170 bounds: [f32; 4],
171 clip: [f32; 4],
172 clip_radius: f32,
173 thickness_px: f32,
174 start_deg10: u16,
175 sweep_deg10: u16,
176 fill_sweep_deg10: u16,
177 track_color: Color,
178 fill_color: Color,
179) -> GpuPrimitive {
180 const DEG10_TO_RAD: f32 = core::f32::consts::PI / 1800.0;
181 let start_rad = ((start_deg10 % 3600) as f32) * DEG10_TO_RAD;
182 let sweep_rad = (sweep_deg10.clamp(20, 3590) as f32) * DEG10_TO_RAD;
183 let fill_rad = (fill_sweep_deg10.min(sweep_deg10) as f32) * DEG10_TO_RAD;
184 GpuPrimitive {
185 bounds,
186 clip,
187 uv: [start_rad, sweep_rad, fill_rad, thickness_px],
188 color0: color_to_f32(track_color),
189 color1: color_to_f32(fill_color),
190 border_color: [0.0; 4],
191 params: [0.0, 0.0, KIND_ARC, 0.0],
192 extra: [clip_radius, 0.0, 0.0, 0.0],
193 radii: [0.0; 4],
194 grad_a: [0.0; 4],
195 grad_b: [0.0; 4],
196 xform: IDENTITY_XFORM,
197 }
198}
199
200#[inline]
202#[allow(clippy::too_many_arguments)]
203pub(crate) fn make_styled_quad_primitive(
204 bounds: [f32; 4],
205 clip: [f32; 4],
206 clip_radius: f32,
207 sq: &crate::paint::StyledQuad<'_>,
208 scale: f32,
209 ramp_v: Option<f32>,
210) -> Option<GpuPrimitive> {
211 let radii = [
212 (sq.radii.tl as f32) * scale,
213 (sq.radii.tr as f32) * scale,
214 (sq.radii.br as f32) * scale,
215 (sq.radii.bl as f32) * scale,
216 ];
217 let bw = if sq.border_width == 0 {
218 0.0
219 } else {
220 ((sq.border_width as f32) * scale).round().max(1.0)
221 };
222 let (xform, tx, ty) = if let Some(t) = sq.transform {
223 if !t.is_identity() {
224 let linear_only = crate::paint::Transform2D::new(t.a, t.b, t.c, t.d, 0.0, 0.0);
225 let inv = linear_only.invert()?;
226 ([inv.a, inv.b, inv.c, inv.d], t.e * scale, t.f * scale)
227 } else {
228 (IDENTITY_XFORM, 0.0, 0.0)
229 }
230 } else {
231 (IDENTITY_XFORM, 0.0, 0.0)
232 };
233
234 let (color0, color1, grad_kind, grad_a, grad_b, extend_f) = match sq.paint {
235 crate::paint::Paint::Solid(c) => {
236 let cf = color_to_f32(c.scale_alpha(sq.opacity));
237 (cf, cf, 0.0, [0.0; 4], [0.0, 0.0, tx, ty], 0.0)
238 }
239 crate::paint::Paint::LinearGradient {
240 start, end, extend, ..
241 } => (
242 [0.0; 4],
243 [0.0; 4],
244 1.0,
245 [start[0], start[1], end[0], end[1]],
246 [0.0, 0.0, tx, ty],
247 extend as u8 as f32,
248 ),
249 crate::paint::Paint::RadialGradient {
250 center,
251 radius,
252 focal,
253 focal_radius,
254 extend,
255 ..
256 } => (
257 [0.0; 4],
258 [0.0; 4],
259 2.0,
260 [center[0], center[1], radius, focal[0]],
261 [focal[1], focal_radius, tx, ty],
262 extend as u8 as f32,
263 ),
264 crate::paint::Paint::ConicGradient {
265 center,
266 start_angle_deg,
267 sweep_deg,
268 extend,
269 ..
270 } => {
271 let start_rad = (start_angle_deg * (core::f32::consts::PI / 180.0))
272 .rem_euclid(core::f32::consts::TAU);
273 let sweep_rad = (sweep_deg.abs().max(1e-3) * (core::f32::consts::PI / 180.0))
274 .min(core::f32::consts::TAU);
275 (
276 [0.0; 4],
277 [0.0; 4],
278 3.0,
279 [center[0], center[1], start_rad, sweep_rad],
280 [0.0, 0.0, tx, ty],
281 extend as u8 as f32,
282 )
283 }
284 };
285
286 Some(GpuPrimitive {
287 bounds,
288 clip,
289 uv: [0.0; 4],
290 color0,
291 color1,
292 border_color: color_to_f32(sq.border_color),
293 params: [sq.radii.max_radius() as f32 * scale, bw, KIND_QUAD, 0.0],
294 extra: [clip_radius, grad_kind, ramp_v.unwrap_or(0.0), extend_f],
295 radii,
296 grad_a,
297 grad_b,
298 xform,
299 })
300}
301
302#[inline(always)]
307pub(crate) fn snap_bounds(r: Region, scale: f32) -> [f32; 4] {
308 let x0 = ((r.x as f32) * scale).round();
309 let y0 = ((r.y as f32) * scale).round();
310 let w = if r.w == 1 {
311 scale.round().max(1.0)
312 } else {
313 (((r.right() as f32) * scale).round() - x0).max(0.0)
314 };
315 let h = if r.h == 1 {
316 scale.round().max(1.0)
317 } else {
318 (((r.bottom() as f32) * scale).round() - y0).max(0.0)
319 };
320 [x0, y0, w, h]
321}
322
323#[inline(always)]
325pub(crate) fn snap_clip(r: Region, scale: f32) -> [f32; 4] {
326 [
327 ((r.x as f32) * scale).round(),
328 ((r.y as f32) * scale).round(),
329 ((r.right() as f32) * scale).round(),
330 ((r.bottom() as f32) * scale).round(),
331 ]
332}
333
334pub(crate) fn create_wgpu_instance(backends: ::wgpu::Backends) -> ::wgpu::Instance {
337 let mut backend_options = ::wgpu::BackendOptions::from_env_or_default();
338 #[cfg(target_os = "windows")]
339 if ::wgpu::Dx12Compiler::from_env().is_none() {
340 backend_options.dx12.shader_compiler = ::wgpu::Dx12Compiler::Fxc;
341 }
342 ::wgpu::Instance::new(::wgpu::InstanceDescriptor {
343 backends,
344 flags: ::wgpu::InstanceFlags::empty().with_env(),
345 backend_options,
346 memory_budget_thresholds: ::wgpu::MemoryBudgetThresholds::default(),
347 display: None,
348 })
349}
350
351pub(crate) fn block_on<F: Future>(fut: F) -> F::Output {
353 struct ThreadSignal {
354 ready: Mutex<bool>,
355 cv: Condvar,
356 }
357 impl Wake for ThreadSignal {
358 fn wake(self: Arc<Self>) {
359 self.wake_by_ref();
360 }
361 fn wake_by_ref(self: &Arc<Self>) {
362 if let Ok(mut guard) = self.ready.lock() {
363 *guard = true;
364 self.cv.notify_one();
365 }
366 }
367 }
368
369 let signal = Arc::new(ThreadSignal {
370 ready: Mutex::new(false),
371 cv: Condvar::new(),
372 });
373 let waker = Waker::from(signal.clone());
374 let mut cx = Context::from_waker(&waker);
375 let mut fut = pin!(fut);
376 loop {
377 match fut.as_mut().poll(&mut cx) {
378 Poll::Ready(out) => return out,
379 Poll::Pending => {
380 if let Ok(mut guard) = signal.ready.lock() {
381 while !*guard {
382 guard = match signal.cv.wait(guard) {
383 Ok(g) => g,
384 Err(poisoned) => poisoned.into_inner(),
385 };
386 }
387 *guard = false;
388 }
389 }
390 }
391 }
392}
393
394#[derive(Clone, Debug, Default)]
396pub struct WgpuScene {
397 pub primitives: Vec<GpuPrimitive>,
398 pub quad_count: usize,
399 pub shadow_count: usize,
400 pub text_run_count: usize,
401 pub sprite_count: usize,
402 pub arc_count: usize,
403}
404
405impl WgpuScene {
406 pub fn new() -> Self {
407 Self::default()
408 }
409
410 pub fn clear(&mut self) {
411 self.primitives.clear();
412 self.quad_count = 0;
413 self.shadow_count = 0;
414 self.text_run_count = 0;
415 self.sprite_count = 0;
416 self.arc_count = 0;
417 }
418
419 pub fn record_draw_ops(
421 &mut self,
422 ops: &[DrawOp<'_>],
423 dpi_scale: i16,
424 dirty_regions: &[Region],
425 ) -> usize {
426 self.clear();
427 if dirty_regions.is_empty() {
428 return 0;
429 }
430 let s = (dpi_scale.max(1)) as f32;
431 for &dirty in dirty_regions {
432 if dirty.is_empty() {
433 continue;
434 }
435 for (idx, op) in ops.iter().enumerate() {
436 let raw_clip = dirty.intersect(op.clip).intersect(op.bounds);
437 if raw_clip.is_empty() {
438 continue;
439 }
440 let eff_clip = compute_unoccluded_clip(raw_clip, &ops[(idx + 1)..]);
441 if eff_clip.is_empty() {
442 continue;
443 }
444 let sb = snap_bounds(op.bounds, s);
445 let clip_region = if op.clip_radius > 0 { op.clip } else { eff_clip };
446 let sc = snap_clip(clip_region, s);
447 let cr = (op.clip_radius as f32) * s;
448 match op.payload {
449 DrawPayload::Quad {
450 bg,
451 bg_grad,
452 border_color,
453 rounded,
454 border_width,
455 } => {
456 let bw = ((border_width & 0x7F) as f32) * s;
457 let horiz = (border_width & 0x80) != 0;
458 let r = (rounded as f32) * s;
459 let is_shadow = border_color.a() == 0 && (border_width & 0x7F) > 0;
460 if is_shadow {
461 if bg.a() > 0 {
462 self.shadow_count += 1;
463 self.primitives
464 .push(make_shadow_primitive(sb, sc, cr, r, bw, bg));
465 }
466 } else if bg.a() > 0 || bg_grad.a() > 0 || (bw > 0.0 && border_color.a() > 0)
467 {
468 self.quad_count += 1;
469 self.primitives.push(make_quad_primitive(
470 sb,
471 sc,
472 cr,
473 r,
474 bw,
475 horiz,
476 bg,
477 bg_grad,
478 border_color,
479 ));
480 }
481 }
482 DrawPayload::TextRun { text, color, .. } => {
483 if !text.is_empty() && color.a() > 0 {
484 self.text_run_count += 1;
485 }
486 }
487 DrawPayload::Sprite(crate::element::SpriteSource::Arc {
488 thickness,
489 start_deg10,
490 sweep_deg10,
491 fill_sweep_deg10,
492 track_color,
493 fill_color,
494 }) => {
495 self.arc_count += 1;
496 self.primitives.push(make_arc_primitive(
497 sb,
498 sc,
499 cr,
500 (thickness as f32) * s,
501 start_deg10,
502 sweep_deg10,
503 fill_sweep_deg10,
504 track_color,
505 fill_color,
506 ));
507 }
508 DrawPayload::Sprite(_) => {
509 self.sprite_count += 1;
510 }
511 DrawPayload::StyledQuad(sq) => {
512 if let Some(prim) = make_styled_quad_primitive(sb, sc, cr, sq, s, None) {
513 self.quad_count += 1;
514 self.primitives.push(prim);
515 }
516 }
517 DrawPayload::PushLayer(_) | DrawPayload::PopLayer => {}
518 DrawPayload::ExternalTexture(_) => {
519 self.sprite_count += 1;
520 }
521 }
522 }
523 }
524 self.primitives.len() + self.text_run_count + self.sprite_count
525 }
526}