Skip to main content

mln_gfx/
frame.rs

1//! How a frame is drawn into a target: the target begins the frame, the
2//! renderer draws into the textures the target gives it and submits them,
3//! and the target ends the frame, which hands the image off. Each step
4//! takes the backend's `Gpu`, which the caller lends to all three.
5
6use crate::gpu::{Gpu, TargetFormats, TextureId};
7use crate::size::Size;
8
9/// The textures of the backend's `Gpu` that a frame draws into.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct FrameImage {
12    /// In physical pixels.
13    pub size: Size,
14    pub color: TextureId,
15    pub depth_stencil: Option<TextureId>,
16    /// Their formats, as the frame's pipelines name them.
17    pub targets: TargetFormats,
18}
19
20/// A frame read back: premultiplied RGBA, in rows from the top.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct FramePixels {
23    /// In physical pixels.
24    pub size: Size,
25    /// Four bytes for each pixel, `size.width * 4` bytes for each row.
26    pub data: Vec<u8>,
27}
28
29/// How one side of a shared texture waits for the other's GPU work on it.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31pub enum SyncKind {
32    /// The work has finished, so there is nothing to wait for.
33    CpuComplete,
34    /// A `GLsync` in the share group of both sides.
35    OpenGlFence,
36    /// The work went to the queue that both sides submit to, so work
37    /// submitted to it later runs after it.
38    QueueOrder,
39    /// A timeline `VkSemaphore` and the value it reaches.
40    VulkanTimelineSemaphore,
41    /// A sync file descriptor, which signals once.
42    SyncFd,
43    /// An `MTLSharedEvent` and the value it reaches.
44    MetalSharedEvent,
45    /// A shared handle to an `ID3D12Fence` and the value it reaches.
46    D3d12Fence,
47}
48
49impl SyncKind {
50    /// Every kind, from the one that waits least to the one that waits most:
51    /// queue order waits for nothing, a GPU object makes only the GPU wait,
52    /// a sync file crosses APIs, and a finished frame makes the CPU wait.
53    pub(crate) const BY_PREFERENCE: [SyncKind; 7] = [
54        SyncKind::QueueOrder,
55        SyncKind::OpenGlFence,
56        SyncKind::VulkanTimelineSemaphore,
57        SyncKind::MetalSharedEvent,
58        SyncKind::D3d12Fence,
59        SyncKind::SyncFd,
60        SyncKind::CpuComplete,
61    ];
62
63    /// Whether a sync of this kind names an object to wait on.
64    #[must_use]
65    pub fn names_object(self) -> bool {
66        !matches!(self, SyncKind::CpuComplete | SyncKind::QueueOrder)
67    }
68
69    fn bit(self) -> u8 {
70        1 << self as u8
71    }
72}
73
74/// A set of [`SyncKind`]s.
75#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
76pub struct SyncKinds(u8);
77
78impl SyncKinds {
79    pub const NONE: SyncKinds = SyncKinds(0);
80
81    #[must_use]
82    pub fn of(kinds: &[SyncKind]) -> SyncKinds {
83        SyncKinds(kinds.iter().fold(0, |bits, kind| bits | kind.bit()))
84    }
85
86    #[must_use]
87    pub fn contains(self, kind: SyncKind) -> bool {
88        self.0 & kind.bit() != 0
89    }
90
91    #[must_use]
92    pub(crate) fn is_empty(self) -> bool {
93        self.0 == 0
94    }
95
96    #[must_use]
97    pub fn with(self, kind: SyncKind) -> SyncKinds {
98        SyncKinds(self.0 | kind.bit())
99    }
100
101    #[must_use]
102    pub fn union(self, other: SyncKinds) -> SyncKinds {
103        SyncKinds(self.0 | other.0)
104    }
105
106    pub fn iter(self) -> impl Iterator<Item = SyncKind> {
107        SyncKind::BY_PREFERENCE.into_iter().filter(move |kind| self.contains(*kind))
108    }
109
110    /// The kind of `self`, the ones a host accepts, that `supported` has and
111    /// that waits least. A host that names none accepts a finished frame
112    /// where `supported` has one, and queue order otherwise.
113    #[must_use]
114    pub fn pick(self, supported: SyncKinds) -> Option<SyncKind> {
115        let accepted = if !self.is_empty() {
116            self
117        } else if supported.contains(SyncKind::CpuComplete) {
118            SyncKinds::of(&[SyncKind::CpuComplete])
119        } else {
120            SyncKinds::of(&[SyncKind::QueueOrder])
121        };
122        SyncKind::BY_PREFERENCE.into_iter().find(|kind| accepted.contains(*kind) && supported.contains(*kind))
123    }
124}
125
126/// A point in one side's GPU work that the other side waits for before it
127/// uses a shared texture: the object to wait on, as an integer, for the
128/// kinds that name one, and the value a timeline reaches.
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
130pub struct GpuSync {
131    pub kind: SyncKind,
132    pub handle: u64,
133    pub value: u64,
134}
135
136impl GpuSync {
137    /// A sync of a kind that names no object.
138    #[must_use]
139    pub fn of(kind: SyncKind) -> GpuSync {
140        GpuSync { kind, handle: 0, value: 0 }
141    }
142}
143
144/// What the host's reads of a frame's texture end with, which a target
145/// waits for before it draws into the texture again. The target takes the
146/// sync file, or the `GLsync` that `sync` names; dropping it closes the sync
147/// file.
148#[derive(Debug)]
149pub struct ConsumerSync {
150    /// The kind, and the timeline or the `GLsync` with its value. A sync
151    /// file's descriptor is `sync_file`.
152    pub sync: GpuSync,
153    #[cfg(unix)]
154    pub sync_file: Option<std::os::fd::OwnedFd>,
155}
156
157impl ConsumerSync {
158    /// A sync of a kind that names no object, or names one that the host
159    /// keeps.
160    #[must_use]
161    pub fn of(sync: GpuSync) -> ConsumerSync {
162        ConsumerSync {
163            sync,
164            #[cfg(unix)]
165            sync_file: None,
166        }
167    }
168}
169
170/// Where a frame's image went when its frame ended.
171#[derive(Clone, Copy, Debug, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum Handoff {
174    /// A window or surface shows it.
175    Presented,
176    /// The target keeps it, for its owner to read back.
177    ReadBack,
178    /// The host's texture at `slot` of its ring holds it, once the host
179    /// waits for `sync`. The object `sync` names stays the target's until
180    /// the host gives the slot back.
181    GivenBack { slot: usize, sync: GpuSync },
182    /// The target's own image at `slot` of its exported ring holds it, for
183    /// the host to acquire and read once it waits for `sync`. The image and
184    /// the object `sync` names stay the target's until the host gives the
185    /// slot back.
186    Queued { slot: usize, sync: GpuSync },
187    /// Nothing took it: the target had no image to hand off.
188    Dropped,
189}
190
191/// A target that a renderer draws frames into: a window's swapchain, or an
192/// image of the library's that is read back. It belongs to the thread that
193/// built it, and each call takes the `Gpu` of the backend it was built on.
194pub trait FrameTarget {
195    /// The `Gpu` of the target's backend, whose textures the target's
196    /// frames are.
197    type Gpu: Gpu + ?Sized;
198
199    /// Begins a frame, and returns the textures of `gpu` that the renderer
200    /// draws it into, or `None` when the target has nothing to draw into
201    /// now: it has no surface, or the surface is hidden or out of date. The
202    /// caller then skips the frame. Until [`end_frame`](Self::end_frame),
203    /// each call returns the same image, so a caller may begin a frame and
204    /// leave it for the next one.
205    fn begin_frame(&mut self, gpu: &mut Self::Gpu) -> Option<FrameImage>;
206
207    /// Hands the frame's image off, once the renderer has submitted the
208    /// frame's passes to `gpu`.
209    fn end_frame(&mut self, gpu: &mut Self::Gpu) -> Handoff;
210
211    /// Draws the next frames at `size` physical pixels. A target whose
212    /// textures the host or the target's owner sizes ignores it.
213    fn resize(&mut self, gpu: &mut Self::Gpu, size: Size) {
214        let _ = (gpu, size);
215    }
216
217    /// Destroys the target's textures of `gpu`, after which the target
218    /// draws no more frames. A target dropped without it leaves them to the
219    /// `Gpu`, which frees them when it drops.
220    fn tear_down(&mut self, gpu: &mut Self::Gpu);
221}