1use crate::gpu::create_texture;
2#[cfg(target_os = "macos")]
3use crate::interop::{IoSurface, import_io_surface};
4use crate::{Gpu, Rect};
5use rustc_hash::FxHashMap;
6use std::collections::VecDeque;
7#[cfg(not(target_arch = "wasm32"))]
8use std::mem::take;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
11#[cfg(not(target_arch = "wasm32"))]
12use std::time::{Duration, Instant};
13use thiserror::Error;
14use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
15#[cfg(target_arch = "wasm32")]
16use web_time::{Duration, Instant};
17#[cfg(not(target_arch = "wasm32"))]
18use wgpu::PollType;
19use wgpu::{AdapterInfo, Device, Queue, Texture, TextureFormat, TextureUsages};
20
21const RELEASE_POLL: Duration = Duration::from_millis(2);
22
23static NEXT_SURFACE: AtomicU64 = AtomicU64::new(1);
24
25type Waker = Arc<dyn Fn() + Send + Sync>;
26type StatusSink = Box<dyn Fn(SurfaceStatus)>;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
29pub struct SurfaceId(u64);
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub struct BufferRef {
33 pub(crate) set: u64,
34 index: u32,
35}
36
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub enum Origin {
39 #[default]
40 TopLeft,
41 BottomLeft,
42}
43
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
45pub enum AlphaMode {
46 #[default]
47 Premultiplied,
48 Opaque,
49}
50
51#[derive(Clone, Copy, Debug, PartialEq)]
52pub struct Frame {
53 buffer: BufferRef,
54 region: Option<Rect>,
55 origin: Origin,
56 alpha: AlphaMode,
57}
58
59impl Frame {
60 pub fn new(buffer: BufferRef) -> Self {
61 Frame {
62 buffer,
63 region: None,
64 origin: Origin::TopLeft,
65 alpha: AlphaMode::Premultiplied,
66 }
67 }
68
69 pub fn region(mut self, region: Rect) -> Self {
70 self.region = Some(region);
71 self
72 }
73
74 pub fn origin(mut self, origin: Origin) -> Self {
75 self.origin = origin;
76 self
77 }
78
79 pub fn alpha(mut self, alpha: AlphaMode) -> Self {
80 self.alpha = alpha;
81 self
82 }
83}
84
85#[derive(Clone, Copy, Debug, PartialEq)]
86pub struct SurfaceConfig {
87 pub width: u32,
88 pub height: u32,
89 pub scale: f32,
90 pub visible: bool,
91}
92
93#[derive(Clone, Debug, Error, PartialEq, Eq)]
94pub enum SurfaceError {
95 #[error("this platform cannot share {0} with the compositor")]
96 Unsupported(&'static str),
97 #[error("the surface has not been attached to a compositor")]
98 NotAttached,
99 #[error("the producer renders on a different GPU from the compositor")]
100 AdapterMismatch,
101 #[error("surface buffers must be BGRA8 or RGBA8 without sRGB encoding, not {0:?}")]
102 Format(TextureFormat),
103 #[error("failed to allocate a {width}x{height} shared buffer")]
104 Allocation { width: u32, height: u32 },
105 #[error("failed to share a buffer with the compositor: {0}")]
106 Import(String),
107 #[error("{0}")]
108 Producer(String),
109}
110
111#[derive(Clone, Debug, Default, PartialEq, Eq)]
112pub enum SurfaceStatus {
113 #[default]
114 Waiting,
115 Live,
116 Failed(SurfaceError),
117}
118
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub enum SurfaceEvent {
121 Attached,
122 Configure(SurfaceConfig),
123 FrameRequest { target: Instant },
124 Detached,
125}
126
127enum Notice {
128 Attached(Box<SurfaceCx>),
129 Event(SurfaceEvent),
130 Released(BufferRef),
131}
132
133#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
134pub enum Sharing {
135 #[default]
136 Device,
137 Native,
138}
139
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub struct BufferDesc {
142 pub(crate) width: u32,
143 pub(crate) height: u32,
144 pub(crate) format: TextureFormat,
145 pub(crate) count: u32,
146 pub(crate) sharing: Sharing,
147}
148
149impl BufferDesc {
150 pub fn new(width: u32, height: u32) -> Self {
151 BufferDesc {
152 width,
153 height,
154 format: TextureFormat::Bgra8Unorm,
155 count: 3,
156 sharing: Sharing::Device,
157 }
158 }
159
160 pub fn format(mut self, format: TextureFormat) -> Self {
161 self.format = format;
162 self
163 }
164
165 pub fn count(mut self, count: u32) -> Self {
166 self.count = count;
167 self
168 }
169
170 pub fn sharing(mut self, sharing: Sharing) -> Self {
171 self.sharing = sharing;
172 self
173 }
174}
175
176#[derive(Clone, Debug)]
177pub struct SharedBuffer {
178 texture: Texture,
179 #[cfg(target_os = "macos")]
180 io_surface: Option<IoSurface>,
181}
182
183impl SharedBuffer {
184 pub fn texture(&self) -> &Texture {
185 &self.texture
186 }
187
188 #[cfg(target_os = "macos")]
189 pub fn io_surface(&self) -> Option<&IoSurface> {
190 self.io_surface.as_ref()
191 }
192}
193
194#[derive(Clone)]
195pub struct SurfaceCx {
196 device: Device,
197 queue: Queue,
198 adapter: AdapterInfo,
199 waker: Option<Waker>,
200}
201
202impl SurfaceCx {
203 pub fn device(&self) -> &Device {
204 &self.device
205 }
206
207 pub fn queue(&self) -> &Queue {
208 &self.queue
209 }
210
211 pub fn adapter(&self) -> &AdapterInfo {
212 &self.adapter
213 }
214
215 fn allocate(&self, desc: &BufferDesc) -> Result<Vec<SharedBuffer>, SurfaceError> {
216 check_format(desc.format)?;
217 (0..desc.count.max(1))
218 .map(|_| match desc.sharing {
219 Sharing::Device => Ok(SharedBuffer {
220 texture: create_texture(
221 &self.device,
222 "rouge surface buffer",
223 (desc.width.max(1), desc.height.max(1)),
224 desc.format,
225 buffer_usage(),
226 ),
227 #[cfg(target_os = "macos")]
228 io_surface: None,
229 }),
230 Sharing::Native => native_buffer(self, desc),
231 })
232 .collect()
233 }
234}
235
236#[cfg(target_os = "macos")]
237fn native_buffer(cx: &SurfaceCx, desc: &BufferDesc) -> Result<SharedBuffer, SurfaceError> {
238 if desc.format != TextureFormat::Bgra8Unorm {
239 return Err(SurfaceError::Format(desc.format));
240 }
241 let surface = IoSurface::new(desc.width, desc.height)?;
242 let texture = import_io_surface(&cx.device, &surface, desc.format, buffer_usage())?;
243 Ok(SharedBuffer {
244 texture,
245 io_surface: Some(surface),
246 })
247}
248
249#[cfg(not(target_os = "macos"))]
250fn native_buffer(_cx: &SurfaceCx, _desc: &BufferDesc) -> Result<SharedBuffer, SurfaceError> {
251 Err(SurfaceError::Unsupported("native buffers"))
252}
253
254fn buffer_usage() -> TextureUsages {
255 TextureUsages::TEXTURE_BINDING
256 | TextureUsages::RENDER_ATTACHMENT
257 | TextureUsages::COPY_SRC
258 | TextureUsages::COPY_DST
259}
260
261fn check_format(format: TextureFormat) -> Result<(), SurfaceError> {
262 match format {
263 TextureFormat::Bgra8Unorm | TextureFormat::Rgba8Unorm => Ok(()),
264 other => Err(SurfaceError::Format(other)),
265 }
266}
267
268enum Message {
269 Register(u64, Vec<Texture>),
270 Unregister(u64),
271 Submit(Frame),
272 RequestFrame,
273 Fail(SurfaceError),
274}
275
276struct Pool {
277 desc: BufferDesc,
278 set: u64,
279 buffers: Vec<SharedBuffer>,
280 free: VecDeque<u32>,
281}
282
283pub struct SurfaceProducer {
284 id: SurfaceId,
285 messages: UnboundedSender<Message>,
286 notices: UnboundedReceiver<Notice>,
287 cx: Option<SurfaceCx>,
288 pool: Option<Pool>,
289 sets: u64,
290}
291
292pub struct SurfaceSource {
293 id: SurfaceId,
294 messages: UnboundedReceiver<Message>,
295 notices: UnboundedSender<Notice>,
296}
297
298impl SurfaceSource {
299 pub fn id(&self) -> SurfaceId {
300 self.id
301 }
302}
303
304pub fn surface_channel() -> (SurfaceProducer, SurfaceSource) {
305 let id = SurfaceId(NEXT_SURFACE.fetch_add(1, Ordering::Relaxed));
306 let (messages, inbox) = unbounded_channel();
307 let (notices, outbox) = unbounded_channel();
308 let producer = SurfaceProducer {
309 id,
310 messages,
311 notices: outbox,
312 cx: None,
313 pool: None,
314 sets: 0,
315 };
316 let source = SurfaceSource {
317 id,
318 messages: inbox,
319 notices,
320 };
321 (producer, source)
322}
323
324impl SurfaceProducer {
325 pub fn id(&self) -> SurfaceId {
326 self.id
327 }
328
329 pub fn cx(&self) -> Option<&SurfaceCx> {
330 self.cx.as_ref()
331 }
332
333 pub fn configure(&mut self, desc: BufferDesc) -> Result<(), SurfaceError> {
334 if self.pool.as_ref().is_some_and(|pool| pool.desc == desc) {
335 return Ok(());
336 }
337 let cx = self.cx.as_ref().ok_or(SurfaceError::NotAttached)?;
338 let buffers = cx.allocate(&desc)?;
339 self.sets += 1;
340 let textures = buffers
341 .iter()
342 .map(|buffer| buffer.texture.clone())
343 .collect();
344 self.send(Message::Register(self.sets, textures));
345 if let Some(old) = self.pool.take() {
346 self.send(Message::Unregister(old.set));
347 }
348 self.pool = Some(Pool {
349 desc,
350 set: self.sets,
351 free: (0..buffers.len() as u32).collect(),
352 buffers,
353 });
354 Ok(())
355 }
356
357 pub fn acquire(&mut self) -> Option<(BufferRef, &SharedBuffer)> {
358 let pool = self.pool.as_mut()?;
359 let index = pool.free.pop_front()?;
360 let buffer = BufferRef {
361 set: pool.set,
362 index,
363 };
364 Some((buffer, &pool.buffers[index as usize]))
365 }
366
367 pub fn buffers(&self) -> &[SharedBuffer] {
368 self.pool.as_ref().map_or(&[], |pool| &pool.buffers)
369 }
370
371 pub fn free_buffers(&self) -> usize {
372 self.pool.as_ref().map_or(0, |pool| pool.free.len())
373 }
374
375 pub fn submit(&mut self, frame: Frame) {
376 self.send(Message::Submit(frame));
377 }
378
379 pub fn request_frame(&self) {
380 self.send(Message::RequestFrame);
381 }
382
383 pub fn fail(&self, error: SurfaceError) {
384 self.send(Message::Fail(error));
385 }
386
387 pub fn try_recv(&mut self) -> Option<SurfaceEvent> {
388 while let Ok(notice) = self.notices.try_recv() {
389 if let Some(event) = self.observe(notice) {
390 return Some(event);
391 }
392 }
393 None
394 }
395
396 pub async fn recv(&mut self) -> Option<SurfaceEvent> {
397 loop {
398 let notice = self.notices.recv().await?;
399 if let Some(event) = self.observe(notice) {
400 return Some(event);
401 }
402 }
403 }
404
405 #[cfg(not(target_arch = "wasm32"))]
406 pub fn blocking_recv(&mut self) -> Option<SurfaceEvent> {
407 loop {
408 let notice = self.notices.blocking_recv()?;
409 if let Some(event) = self.observe(notice) {
410 return Some(event);
411 }
412 }
413 }
414
415 fn observe(&mut self, notice: Notice) -> Option<SurfaceEvent> {
416 match notice {
417 Notice::Attached(cx) => {
418 self.cx = Some(*cx);
419 Some(SurfaceEvent::Attached)
420 }
421 Notice::Event(event) => Some(event),
422 Notice::Released(buffer) => {
423 if let Some(pool) = &mut self.pool
424 && pool.set == buffer.set
425 && !pool.free.contains(&buffer.index)
426 {
427 pool.free.push_back(buffer.index);
428 }
429 None
430 }
431 }
432 }
433
434 fn send(&self, message: Message) {
435 if self.messages.send(message).is_ok()
436 && let Some(waker) = self.cx.as_ref().and_then(|cx| cx.waker.as_ref())
437 {
438 waker();
439 }
440 }
441}
442
443#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
444pub struct SurfaceStats {
445 pub surfaces: usize,
446 pub frames_submitted: u64,
447 pub frames_latched: u64,
448 pub frames_discarded: u64,
449 pub buffers_released: u64,
450}
451
452#[derive(Clone, Debug)]
453pub(crate) struct Latched {
454 pub buffer: BufferRef,
455 pub texture: Texture,
456 pub region: Rect,
457 pub origin: Origin,
458 pub alpha: AlphaMode,
459}
460
461struct Entry {
462 messages: UnboundedReceiver<Message>,
463 notices: UnboundedSender<Notice>,
464 status: StatusSink,
465 sets: Vec<(u64, Vec<Texture>)>,
466 pending: Option<Frame>,
467 current: Option<Latched>,
468 latched: u64,
469 config: Option<SurfaceConfig>,
470 binds: usize,
471 wants_frame: bool,
472 detached: bool,
473 failed: bool,
474}
475
476impl Entry {
477 fn visible(&self) -> bool {
478 !self.detached && self.config.is_some_and(|config| config.visible)
479 }
480
481 fn emit(&self, event: SurfaceEvent) {
482 let _ = self.notices.send(Notice::Event(event));
483 }
484
485 fn texture(&self, buffer: BufferRef) -> Option<&Texture> {
486 let (_, textures) = self.sets.iter().find(|(set, _)| *set == buffer.set)?;
487 textures.get(buffer.index as usize)
488 }
489
490 fn discard(&self, frame: Frame, stats: &mut SurfaceStats) {
491 let _ = self.notices.send(Notice::Released(frame.buffer));
492 stats.frames_discarded += 1;
493 }
494
495 fn fail(&mut self, error: SurfaceError, stats: &mut SurfaceStats) {
496 self.failed = true;
497 if let Some(frame) = self.pending.take() {
498 self.discard(frame, stats);
499 }
500 (self.status)(SurfaceStatus::Failed(error));
501 }
502
503 fn receive(&mut self, stats: &mut SurfaceStats) {
504 while let Ok(message) = self.messages.try_recv() {
505 match message {
506 Message::Register(set, textures) => {
507 let invalid = textures
508 .iter()
509 .map(Texture::format)
510 .find(|format| check_format(*format).is_err());
511 match invalid {
512 Some(format) => self.fail(SurfaceError::Format(format), stats),
513 None => self.sets.push((set, textures)),
514 }
515 }
516 Message::Unregister(set) => self.sets.retain(|(id, _)| *id != set),
517 Message::Submit(frame) => {
518 stats.frames_submitted += 1;
519 if self.detached || self.failed || self.texture(frame.buffer).is_none() {
520 self.discard(frame, stats);
521 } else if let Some(skipped) = self.pending.replace(frame) {
522 self.discard(skipped, stats);
523 }
524 }
525 Message::RequestFrame => self.wants_frame = true,
526 Message::Fail(error) => self.fail(error, stats),
527 }
528 }
529 }
530
531 fn latch(&mut self, retired: &mut Vec<Retired>, stats: &mut SurfaceStats) -> bool {
532 self.receive(stats);
533 let Some(frame) = self.pending.take() else {
534 return false;
535 };
536 let Some(texture) = self.texture(frame.buffer).cloned() else {
537 self.discard(frame, stats);
538 return false;
539 };
540 let full = Rect::new(0.0, 0.0, texture.width() as f32, texture.height() as f32);
541 let latched = Latched {
542 buffer: frame.buffer,
543 texture,
544 region: frame.region.map_or(full, |region| region.intersect(&full)),
545 origin: frame.origin,
546 alpha: frame.alpha,
547 };
548 if let Some(previous) = self.current.replace(latched) {
549 retired.push(Retired {
550 notices: self.notices.clone(),
551 buffer: previous.buffer,
552 });
553 } else {
554 (self.status)(SurfaceStatus::Live);
555 }
556 self.latched += 1;
557 stats.frames_latched += 1;
558 true
559 }
560}
561
562struct Retired {
563 notices: UnboundedSender<Notice>,
564 buffer: BufferRef,
565}
566
567impl Retired {
568 fn release(self) {
569 let _ = self.notices.send(Notice::Released(self.buffer));
570 }
571}
572
573pub struct Surfaces {
574 device: Device,
575 queue: Queue,
576 adapter: AdapterInfo,
577 waker: Option<Waker>,
578 entries: FxHashMap<SurfaceId, Entry>,
579 retired: Vec<Retired>,
580 outstanding: Arc<AtomicUsize>,
581 stats: SurfaceStats,
582}
583
584impl Surfaces {
585 pub fn new(gpu: &Gpu) -> Self {
586 Surfaces {
587 device: gpu.device.clone(),
588 queue: gpu.queue.clone(),
589 adapter: gpu.adapter.get_info(),
590 waker: None,
591 entries: FxHashMap::default(),
592 retired: Vec::new(),
593 outstanding: Arc::new(AtomicUsize::new(0)),
594 stats: SurfaceStats::default(),
595 }
596 }
597
598 pub fn with_waker(mut self, waker: impl Fn() + Send + Sync + 'static) -> Self {
599 self.waker = Some(Arc::new(waker));
600 self
601 }
602
603 pub fn stats(&self) -> SurfaceStats {
604 SurfaceStats {
605 surfaces: self.entries.len(),
606 ..self.stats
607 }
608 }
609
610 pub fn latch(&mut self) -> bool {
611 let mut changed = false;
612 for entry in self.entries.values_mut() {
613 changed |= entry.latch(&mut self.retired, &mut self.stats);
614 }
615 self.collect();
616 changed
617 }
618
619 pub fn needs_frame(&self) -> bool {
620 self.entries
621 .values()
622 .any(|entry| entry.wants_frame && entry.visible())
623 }
624
625 pub fn next_deadline(&self) -> Option<Instant> {
626 (self.outstanding.load(Ordering::Acquire) > 0).then(|| Instant::now() + RELEASE_POLL)
627 }
628
629 pub fn presented(&mut self, at: Instant, interval: Duration) {
630 for entry in self.entries.values_mut() {
631 if entry.wants_frame && entry.visible() {
632 entry.wants_frame = false;
633 entry.emit(SurfaceEvent::FrameRequest {
634 target: at + interval,
635 });
636 }
637 }
638 }
639
640 pub fn maintain(&mut self) {
641 if !self.retired.is_empty() {
642 self.stats.buffers_released += self.retired.len() as u64;
643 #[cfg(not(target_arch = "wasm32"))]
644 self.release_after_gpu();
645 #[cfg(target_arch = "wasm32")]
646 self.retired.drain(..).for_each(Retired::release);
647 }
648 #[cfg(not(target_arch = "wasm32"))]
649 if self.outstanding.load(Ordering::Acquire) > 0 {
650 let _ = self.device.poll(PollType::Poll);
651 }
652 }
653
654 #[cfg(not(target_arch = "wasm32"))]
655 fn release_after_gpu(&mut self) {
656 let retired = take(&mut self.retired);
657 self.outstanding.fetch_add(1, Ordering::AcqRel);
658 let outstanding = self.outstanding.clone();
659 self.queue.on_submitted_work_done(move || {
660 retired.into_iter().for_each(Retired::release);
661 outstanding.fetch_sub(1, Ordering::AcqRel);
662 });
663 }
664
665 pub fn frame(&self, id: SurfaceId) -> Option<u64> {
666 let entry = self.entries.get(&id)?;
667 entry.current.as_ref().map(|_| entry.latched)
668 }
669
670 pub(crate) fn latched(&self, id: SurfaceId) -> Option<&Latched> {
671 self.entries.get(&id)?.current.as_ref()
672 }
673
674 pub(crate) fn holds(&self, id: SurfaceId, set: u64) -> bool {
675 self.entries.get(&id).is_some_and(|entry| {
676 entry.sets.iter().any(|(held, _)| *held == set)
677 || entry
678 .current
679 .as_ref()
680 .is_some_and(|current| current.buffer.set == set)
681 })
682 }
683
684 pub fn place(&mut self, id: SurfaceId, config: SurfaceConfig) {
685 if let Some(entry) = self.entries.get_mut(&id)
686 && entry.config != Some(config)
687 && !entry.detached
688 {
689 entry.config = Some(config);
690 entry.emit(SurfaceEvent::Configure(config));
691 }
692 }
693
694 pub fn detach(&mut self, id: SurfaceId) {
695 if let Some(entry) = self.entries.get_mut(&id)
696 && !entry.detached
697 {
698 entry.detached = true;
699 entry.wants_frame = false;
700 if let Some(frame) = entry.pending.take() {
701 entry.discard(frame, &mut self.stats);
702 }
703 entry.emit(SurfaceEvent::Detached);
704 }
705 }
706
707 pub fn bind(&mut self, id: SurfaceId) {
708 if let Some(entry) = self.entries.get_mut(&id) {
709 entry.binds += 1;
710 }
711 }
712
713 pub fn unbind(&mut self, id: SurfaceId) {
714 if let Some(entry) = self.entries.get_mut(&id) {
715 entry.binds = entry.binds.saturating_sub(1);
716 }
717 }
718
719 pub fn attach(&mut self, source: SurfaceSource, status: impl Fn(SurfaceStatus) + 'static) {
720 let SurfaceSource {
721 id,
722 messages,
723 notices,
724 } = source;
725 let cx = SurfaceCx {
726 device: self.device.clone(),
727 queue: self.queue.clone(),
728 adapter: self.adapter.clone(),
729 waker: self.waker.clone(),
730 };
731 let _ = notices.send(Notice::Attached(Box::new(cx)));
732 status(SurfaceStatus::Waiting);
733 self.entries.insert(
734 id,
735 Entry {
736 messages,
737 notices,
738 status: Box::new(status),
739 sets: Vec::new(),
740 pending: None,
741 current: None,
742 latched: 0,
743 config: None,
744 binds: 0,
745 wants_frame: false,
746 detached: false,
747 failed: false,
748 },
749 );
750 }
751
752 fn collect(&mut self) {
753 let retired = &mut self.retired;
754 self.entries.retain(|_, entry| {
755 let keep = !entry.detached || entry.binds > 0;
756 if !keep && let Some(current) = entry.current.take() {
757 retired.push(Retired {
758 notices: entry.notices.clone(),
759 buffer: current.buffer,
760 });
761 }
762 keep
763 });
764 }
765}