egui_pop_viewport/device.rs
1//! Device tiles (feature `wgpu`): a tile that already lives on the
2//! render device, handed to the viewport with no copy through the CPU.
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! A source that renders on the GPU (an engine running on the device
8//! eframe opened) answers a request with a [`DeviceTile`] through
9//! [`TileSink::deliver_device`](crate::source::TileSink::deliver_device):
10//!
11//! - **a texture** ([`DeviceTile::texture`]): any 2D float-sampled format
12//! (`Rgba16Float`, `Rgba32Float`, `Rgba8Unorm`, `Rgba8UnormSrgb`...),
13//! with `TEXTURE_BINDING` usage, read texel by texel;
14//! - **a storage buffer** ([`DeviceTile::buffer`]): `f32` values, one to
15//! four channels a pixel, rows `row_floats` apart ([`BufferLayout`]),
16//! with `STORAGE` usage, read in place (the GPU path binds the rows the
17//! tile covers, nothing is copied).
18//!
19//! Its values are scene-referred ([`Encoding::Scene`], as
20//! [`Pixels::Scene`]: the display stage runs on them in the shader, as for
21//! uploaded tiles) or display-ready ([`Encoding::Display`], as
22//! [`Pixels::Display`]: sRGB-encoded, shown as they are). Alpha is not
23//! drawn: the image is opaque, as on the GPU path's uploaded tiles.
24//!
25//! The resource must have been created on the render state's device (the
26//! one [`gpu::install`](crate::gpu::install) was given), and the work
27//! writing it submitted to that device's queue before the hand-over. A
28//! tile from another device, or one that does not fit, is refused with a
29//! [`DeviceTileError`]: the source's fallback ([`DeviceTile::fallback`]),
30//! when it offers one, then gives CPU pixels that take the usual path.
31//! The fallback runs on the thread that delivers the tile, never on the
32//! interface thread: a tile refused when the interface takes it in (the
33//! render device changed in between) is dropped and asked for again.
34//!
35//! What the producer needs alive while the tile is shown (its image, with
36//! the charge it carries in the producer's memory accounting) rides with
37//! the tile ([`DeviceTile::keep`]): the viewport holds it exactly as long
38//! as it holds the tile, and drops it when the tile is replaced, evicted
39//! or refused, or the viewport's state is dropped.
40//! The viewport's upload counters
41//! ([`ViewportState::transfers`](crate::ViewportState::transfers)) count
42//! device tiles as bound, with no byte copied.
43
44use std::any::Any;
45use std::fmt;
46
47use egui_wgpu::wgpu;
48
49use crate::source::Pixels;
50
51/// What a device tile's values are, as [`Pixels`] says for CPU tiles.
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
53pub enum Encoding {
54 /// Linear values in the source's working space: the viewport's
55 /// display stage (its matrix, clamp and transfer) runs on them.
56 #[default]
57 Scene,
58 /// sRGB-encoded values, the display transform already applied: shown
59 /// as they are (an `…Srgb` texture format is read back to its
60 /// encoded values).
61 Display,
62}
63
64impl Encoding {
65 pub fn name(self) -> &'static str {
66 match self {
67 Encoding::Scene => "scene",
68 Encoding::Display => "display",
69 }
70 }
71}
72
73/// Where a tile's pixels are in a storage buffer of `f32` values: pixel
74/// `(x, y)` of the image starts at float
75/// `offset / 4 + y * row_floats + x * channels`.
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
77pub struct BufferLayout {
78 /// Bytes from the buffer's start to pixel `(0, 0)`; a multiple of 4.
79 pub offset: u64,
80 /// Floats from one row to the next.
81 pub row_floats: u32,
82 /// Floats a pixel: 1 (grey), 2 (grey, alpha), 3 (RGB) or 4 (RGBA).
83 pub channels: u32,
84}
85
86impl BufferLayout {
87 /// Rows of `width` pixels of `channels` floats, packed, from the
88 /// buffer's start.
89 pub fn packed(width: u32, channels: u32) -> BufferLayout {
90 BufferLayout {
91 offset: 0,
92 row_floats: width.saturating_mul(channels),
93 channels,
94 }
95 }
96
97 /// The bytes to bind for the `size` pixels from `origin`, with
98 /// bindings aligned to `align` bytes: `(offset, size, base)`, `base`
99 /// being the tile's first float within the binding.
100 pub(crate) fn binding(&self, origin: [u32; 2], size: [u32; 2], align: u64) -> (u64, u64, u64) {
101 let row = u64::from(self.row_floats);
102 let ch = u64::from(self.channels);
103 let first = self.offset / 4 + u64::from(origin[1]) * row + u64::from(origin[0]) * ch;
104 let end = self.offset / 4
105 + (u64::from(origin[1]) + u64::from(size[1]).max(1) - 1) * row
106 + (u64::from(origin[0]) + u64::from(size[0])) * ch;
107 let align = align.max(4);
108 let start = first * 4 / align * align;
109 (start, end * 4 - start, first - start / 4)
110 }
111}
112
113/// The resource a device tile reads.
114#[derive(Clone, Debug)]
115pub enum Resource {
116 /// A 2D texture of a float-sampled format, `TEXTURE_BINDING` usage.
117 Texture(wgpu::Texture),
118 /// A storage buffer of `f32` values, `STORAGE` usage.
119 Buffer {
120 buffer: wgpu::Buffer,
121 layout: BufferLayout,
122 },
123}
124
125impl Resource {
126 pub fn name(&self) -> &'static str {
127 match self {
128 Resource::Texture(_) => "texture",
129 Resource::Buffer { .. } => "buffer",
130 }
131 }
132}
133
134/// CPU pixels for a device tile the viewport cannot draw.
135type Fallback = Box<dyn FnOnce() -> Option<Pixels> + Send>;
136
137/// What a device tile keeps alive while the viewport holds it.
138pub(crate) type Keep = Box<dyn Any + Send + Sync>;
139
140/// A tile on the render device: the resource, the device it was created
141/// on, what its values are, and where the tile starts in it.
142pub struct DeviceTile {
143 pub(crate) device: wgpu::Device,
144 pub(crate) resource: Resource,
145 pub(crate) encoding: Encoding,
146 pub(crate) origin: [u32; 2],
147 pub(crate) fallback: Option<Fallback>,
148 pub(crate) keep: Vec<Keep>,
149}
150
151impl fmt::Debug for DeviceTile {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 f.debug_struct("DeviceTile")
154 .field("resource", &self.resource)
155 .field("encoding", &self.encoding)
156 .field("origin", &self.origin)
157 .field("fallback", &self.fallback.is_some())
158 .field("keep", &self.keep.len())
159 .finish()
160 }
161}
162
163impl DeviceTile {
164 /// A tile read from `texture`, created on `device`; scene-referred
165 /// values, from the texture's top left.
166 pub fn texture(device: &wgpu::Device, texture: wgpu::Texture) -> DeviceTile {
167 DeviceTile::new(device, Resource::Texture(texture))
168 }
169
170 /// A tile read from `buffer`, created on `device`, laid out as
171 /// `layout` says; scene-referred values, from pixel `(0, 0)`.
172 pub fn buffer(device: &wgpu::Device, buffer: wgpu::Buffer, layout: BufferLayout) -> DeviceTile {
173 DeviceTile::new(device, Resource::Buffer { buffer, layout })
174 }
175
176 fn new(device: &wgpu::Device, resource: Resource) -> DeviceTile {
177 DeviceTile {
178 device: device.clone(),
179 resource,
180 encoding: Encoding::Scene,
181 origin: [0, 0],
182 fallback: None,
183 keep: Vec::new(),
184 }
185 }
186
187 /// What the values are ([`Encoding::Scene`] by default).
188 pub fn encoding(mut self, encoding: Encoding) -> DeviceTile {
189 self.encoding = encoding;
190 self
191 }
192
193 /// The tile starts at pixel `origin` of the resource (a tile cut
194 /// from a larger image): its `request.size` pixels from there.
195 pub fn origin(mut self, origin: [u32; 2]) -> DeviceTile {
196 self.origin = origin;
197 self
198 }
199
200 /// CPU pixels, made only when the viewport refuses the tile (another
201 /// device, no GPU path, a resource that does not fit): they then
202 /// take the CPU tiles' path. Called at most once, on the thread that
203 /// calls [`TileSink::deliver_device`](crate::source::TileSink::deliver_device),
204 /// never on the interface thread (unless the source delivers from
205 /// it): a tile refused when the interface takes it in is dropped,
206 /// its fallback not called, and the tile asked for again through
207 /// the source's `request`. `None` gives up (the request fails).
208 pub fn fallback(
209 mut self,
210 pixels: impl FnOnce() -> Option<Pixels> + Send + 'static,
211 ) -> DeviceTile {
212 self.fallback = Some(Box::new(pixels));
213 self
214 }
215
216 /// Keeps `value` alive as long as the viewport holds the tile: until
217 /// the tile is replaced, evicted, invalidated or refused, or the
218 /// viewport's state is dropped (on the GPU path, at the next paint
219 /// after the release, once the tile's binding is gone). For what
220 /// owns the resource's memory on the producer's side (its image and
221 /// the charge it carries in a GPU memory ledger), so that memory is
222 /// accounted for while it is shown. Each call adds one value.
223 pub fn keep(mut self, value: impl Any + Send + Sync) -> DeviceTile {
224 self.keep.push(Box::new(value));
225 self
226 }
227
228 /// The device the resource was created on.
229 pub fn device(&self) -> &wgpu::Device {
230 &self.device
231 }
232
233 pub fn resource(&self) -> &Resource {
234 &self.resource
235 }
236
237 pub fn has_fallback(&self) -> bool {
238 self.fallback.is_some()
239 }
240
241 /// Bytes of GPU memory the tile's pixels take in its resource.
242 pub(crate) fn footprint(&self, size: [u32; 2]) -> usize {
243 let n = size[0] as usize * size[1] as usize;
244 match &self.resource {
245 Resource::Texture(t) => n * t.format().block_copy_size(None).unwrap_or(8) as usize,
246 Resource::Buffer { layout, .. } => n * layout.channels as usize * 4,
247 }
248 }
249
250 /// Whether the viewport can draw it for a tile of `size` pixels on
251 /// `render` (`None`: no GPU path installed).
252 pub fn check(
253 &self,
254 render: Option<&RenderDevice>,
255 size: [u32; 2],
256 ) -> Result<(), DeviceTileError> {
257 let Some(render) = render else {
258 return Err(DeviceTileError::NoGpuPath);
259 };
260 if self.device != render.device {
261 return Err(DeviceTileError::OtherDevice);
262 }
263 let [ox, oy] = self.origin;
264 let unfit = |why: String| Err(DeviceTileError::Unfit(why));
265 match &self.resource {
266 Resource::Texture(t) => {
267 if !t.usage().contains(wgpu::TextureUsages::TEXTURE_BINDING) {
268 return unfit("the texture lacks TEXTURE_BINDING usage".into());
269 }
270 if t.dimension() != wgpu::TextureDimension::D2
271 || t.depth_or_array_layers() != 1
272 || t.sample_count() != 1
273 {
274 return unfit(
275 "the texture is not a single-sampled 2D texture of one layer".into(),
276 );
277 }
278 if !matches!(
279 t.format().sample_type(None, None),
280 Some(wgpu::TextureSampleType::Float { .. })
281 ) {
282 return unfit(format!("{:?} is not a float-sampled format", t.format()));
283 }
284 let need = [
285 u64::from(ox) + u64::from(size[0]),
286 u64::from(oy) + u64::from(size[1]),
287 ];
288 if u64::from(t.width()) < need[0] || u64::from(t.height()) < need[1] {
289 return unfit(format!(
290 "the texture is {}×{}, the tile needs {}×{} from ({ox}, {oy})",
291 t.width(),
292 t.height(),
293 size[0],
294 size[1]
295 ));
296 }
297 }
298 Resource::Buffer { buffer, layout } => {
299 if !render.buffers {
300 return Err(DeviceTileError::BuffersUnsupported);
301 }
302 if !buffer.usage().contains(wgpu::BufferUsages::STORAGE) {
303 return unfit("the buffer lacks STORAGE usage".into());
304 }
305 if !(1..=4).contains(&layout.channels) {
306 return unfit(format!("{} channels (1 to 4 are drawn)", layout.channels));
307 }
308 if layout.offset % 4 != 0 {
309 return unfit(format!("offset {} is not a multiple of 4", layout.offset));
310 }
311 let row = (u64::from(ox) + u64::from(size[0])) * u64::from(layout.channels);
312 if u64::from(layout.row_floats) < row {
313 return unfit(format!(
314 "rows of {} floats, the tile needs {row}",
315 layout.row_floats
316 ));
317 }
318 let (start, bytes, _) = layout.binding(self.origin, size, render.storage_align);
319 if start + bytes > buffer.size() {
320 return unfit(format!(
321 "the buffer holds {} bytes, the tile reads up to {}",
322 buffer.size(),
323 start + bytes
324 ));
325 }
326 if bytes > render.max_binding {
327 return unfit(format!(
328 "the tile's rows take {bytes} bytes, over the device's binding limit of {}",
329 render.max_binding
330 ));
331 }
332 }
333 }
334 Ok(())
335 }
336}
337
338/// The render device the GPU path draws with, as device tiles are
339/// checked against it.
340#[derive(Clone, Debug)]
341pub struct RenderDevice {
342 pub device: wgpu::Device,
343 /// Storage buffers can be read by the tile shader on this adapter.
344 pub buffers: bool,
345 /// The device's `min_storage_buffer_offset_alignment`.
346 pub storage_align: u64,
347 /// The device's `max_storage_buffer_binding_size`.
348 pub max_binding: u64,
349}
350
351/// Why a device tile was refused.
352#[derive(Clone, Debug, PartialEq, Eq)]
353pub enum DeviceTileError {
354 /// No GPU path is installed in the context: nothing can bind it.
355 NoGpuPath,
356 /// The resource was created on another device than the render
357 /// state's.
358 OtherDevice,
359 /// This adapter cannot read storage buffers in a fragment shader.
360 BuffersUnsupported,
361 /// The resource does not fit the tile (usage, format, size), said.
362 Unfit(String),
363}
364
365impl fmt::Display for DeviceTileError {
366 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367 match self {
368 DeviceTileError::NoGpuPath => {
369 f.write_str("no GPU path is installed (gpu::install): device tiles cannot be drawn")
370 }
371 DeviceTileError::OtherDevice => f.write_str(
372 "the tile's resource was created on another wgpu device than the render state's; \
373 create it on the device gpu::install was given",
374 ),
375 DeviceTileError::BuffersUnsupported => f.write_str(
376 "this adapter cannot read storage buffers in a fragment shader: deliver a texture",
377 ),
378 DeviceTileError::Unfit(why) => write!(f, "the resource does not fit the tile: {why}"),
379 }
380 }
381}
382
383impl std::error::Error for DeviceTileError {}
384
385#[cfg(test)]
386mod tests {
387 use super::*;
388
389 #[test]
390 fn a_packed_buffer_binds_the_rows_a_tile_covers() {
391 // A 1000-pixel wide RGBA image, the tile at (256, 512), 256 × 256.
392 let layout = BufferLayout::packed(1000, 4);
393 let (start, bytes, base) = layout.binding([256, 512], [256, 256], 256);
394 let first = 512 * 4000 + 256 * 4;
395 let end = (512 + 255) * 4000 + (256 + 256) * 4;
396 assert_eq!(start % 256, 0);
397 assert_eq!(start / 4 + base, first);
398 assert_eq!(start + bytes, end * 4);
399 assert!(base * 4 < 256);
400 }
401
402 #[test]
403 fn an_offset_and_three_channels_are_counted_in_floats() {
404 let layout = BufferLayout {
405 offset: 64,
406 row_floats: 30,
407 channels: 3,
408 };
409 let (start, bytes, base) = layout.binding([2, 1], [4, 2], 4);
410 assert_eq!(start / 4 + base, 16 + 30 + 6);
411 assert_eq!((start + bytes) / 4, 16 + 2 * 30 + 6 * 3);
412 }
413}