Skip to main content

wgpu_types/
origin_extent.rs

1#[cfg(any(feature = "serde", test))]
2use serde::{Deserialize, Serialize};
3
4use crate::TextureDimension;
5
6/// Origin of a copy from a 2D image.
7///
8/// Corresponds to [WebGPU `GPUOrigin2D`](
9/// https://gpuweb.github.io/gpuweb/#dictdef-gpuorigin2ddict).
10#[repr(C)]
11#[derive(Clone, Copy, PartialEq, Eq, Hash)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
14pub struct Origin2d {
15    /// X position of the origin
16    pub x: u32,
17    /// Y position of the origin
18    pub y: u32,
19}
20
21impl Origin2d {
22    /// Zero origin.
23    pub const ZERO: Self = Self { x: 0, y: 0 };
24
25    /// Adds the third dimension to this origin
26    #[must_use]
27    pub fn to_3d(self, z: u32) -> Origin3d {
28        Origin3d {
29            x: self.x,
30            y: self.y,
31            z,
32        }
33    }
34}
35
36impl core::fmt::Debug for Origin2d {
37    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
38        (self.x, self.y).fmt(f)
39    }
40}
41
42/// Origin of a copy to/from a texture.
43///
44/// Corresponds to [WebGPU `GPUOrigin3D`](
45/// https://gpuweb.github.io/gpuweb/#dictdef-gpuorigin3ddict).
46#[repr(C)]
47#[derive(Clone, Copy, PartialEq, Eq, Hash)]
48#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
49#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
50pub struct Origin3d {
51    /// X position of the origin
52    pub x: u32,
53    /// Y position of the origin
54    pub y: u32,
55    /// Z position of the origin
56    pub z: u32,
57}
58
59impl Origin3d {
60    /// Zero origin.
61    pub const ZERO: Self = Self { x: 0, y: 0, z: 0 };
62
63    /// Removes the third dimension from this origin
64    #[must_use]
65    pub fn to_2d(self) -> Origin2d {
66        Origin2d {
67            x: self.x,
68            y: self.y,
69        }
70    }
71}
72
73impl Default for Origin3d {
74    fn default() -> Self {
75        Self::ZERO
76    }
77}
78
79impl core::fmt::Debug for Origin3d {
80    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
81        (self.x, self.y, self.z).fmt(f)
82    }
83}
84
85/// A rectangle with a top-left origin.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
87#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
88pub struct Rect<T> {
89    /// Left edge.
90    pub x: T,
91    /// Top edge.
92    pub y: T,
93    /// Width.
94    pub w: T,
95    /// Height.
96    pub h: T,
97}
98
99impl Rect<u32> {
100    /// Returns the overlap of `self` and `other`, or `None` if it is empty.
101    #[must_use]
102    pub fn intersect(&self, other: &Self) -> Option<Self> {
103        let left = self.x.max(other.x);
104        let top = self.y.max(other.y);
105        let right = self
106            .x
107            .saturating_add(self.w)
108            .min(other.x.saturating_add(other.w));
109        let bottom = self
110            .y
111            .saturating_add(self.h)
112            .min(other.y.saturating_add(other.h));
113        if right <= left || bottom <= top {
114            return None;
115        }
116        Some(Self {
117            x: left,
118            y: top,
119            w: right - left,
120            h: bottom - top,
121        })
122    }
123}
124
125/// Extent of a texture related operation.
126///
127/// Corresponds to [WebGPU `GPUExtent3D`](
128/// https://gpuweb.github.io/gpuweb/#dictdef-gpuextent3ddict).
129#[repr(C)]
130#[derive(Clone, Copy, PartialEq, Eq, Hash)]
131#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
132#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
133pub struct Extent3d {
134    /// Width of the extent
135    pub width: u32,
136    /// Height of the extent
137    pub height: u32,
138    /// The depth of the extent or the number of array layers
139    #[cfg_attr(feature = "serde", serde(default = "default_depth"))]
140    pub depth_or_array_layers: u32,
141}
142
143impl core::fmt::Debug for Extent3d {
144    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
145        (self.width, self.height, self.depth_or_array_layers).fmt(f)
146    }
147}
148
149#[cfg(feature = "serde")]
150fn default_depth() -> u32 {
151    1
152}
153
154impl Default for Extent3d {
155    fn default() -> Self {
156        Self {
157            width: 1,
158            height: 1,
159            depth_or_array_layers: 1,
160        }
161    }
162}
163
164impl Extent3d {
165    /// Calculates the [physical size] backing a texture of the given
166    /// format and extent.  This includes padding to the block width
167    /// and height of the format.
168    ///
169    /// This is the texture extent that you must upload at when uploading to _mipmaps_ of compressed textures.
170    ///
171    /// [physical size]: https://gpuweb.github.io/gpuweb/#physical-miplevel-specific-texture-extent
172    #[must_use]
173    pub fn physical_size(&self, format: crate::TextureFormat) -> Self {
174        let (block_width, block_height) = format.block_dimensions();
175
176        let width = self.width.div_ceil(block_width) * block_width;
177        let height = self.height.div_ceil(block_height) * block_height;
178
179        Self {
180            width,
181            height,
182            depth_or_array_layers: self.depth_or_array_layers,
183        }
184    }
185
186    /// Calculates the maximum possible count of mipmaps.
187    ///
188    /// Treats the depth as part of the mipmaps. If calculating
189    /// for a 2DArray texture, which does not mipmap depth, set depth to 1.
190    #[must_use]
191    pub fn max_mips(&self, dim: TextureDimension) -> u32 {
192        match dim {
193            TextureDimension::D1 => 1,
194            TextureDimension::D2 => {
195                let max_dim = self.width.max(self.height);
196                32 - max_dim.leading_zeros()
197            }
198            TextureDimension::D3 => {
199                let max_dim = self.width.max(self.height.max(self.depth_or_array_layers));
200                32 - max_dim.leading_zeros()
201            }
202        }
203    }
204
205    /// Calculates the extent at a given mip level.
206    ///
207    /// This is a low-level helper for internal use.
208    ///
209    /// It does *not* account for memory size being a multiple of block size.
210    ///
211    /// TODO(<https://github.com/gfx-rs/wgpu/issues/8491>): It also does not
212    /// consider whether an even dimension is required due to chroma
213    /// subsampling, but it probably should.
214    ///
215    /// <https://gpuweb.github.io/gpuweb/#logical-miplevel-specific-texture-extent>
216    #[doc(hidden)]
217    #[must_use]
218    pub fn mip_level_size(&self, level: u32, dim: TextureDimension) -> Self {
219        Self {
220            width: u32::max(1, self.width.unbounded_shr(level)),
221            height: match dim {
222                TextureDimension::D1 => 1,
223                _ => u32::max(1, self.height.unbounded_shr(level)),
224            },
225            depth_or_array_layers: match dim {
226                TextureDimension::D1 => 1,
227                TextureDimension::D2 => self.depth_or_array_layers,
228                TextureDimension::D3 => {
229                    u32::max(1, self.depth_or_array_layers.unbounded_shr(level))
230                }
231            },
232        }
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    fn rect(x: u32, y: u32, w: u32, h: u32) -> Rect<u32> {
241        Rect { x, y, w, h }
242    }
243
244    #[test]
245    fn intersect() {
246        let surface = rect(0, 0, 800, 600);
247        assert_eq!(
248            rect(10, 20, 100, 50).intersect(&surface),
249            Some(rect(10, 20, 100, 50))
250        );
251        assert_eq!(surface.intersect(&surface), Some(surface));
252        assert_eq!(
253            rect(750, 570, 100, 50).intersect(&surface),
254            Some(rect(750, 570, 50, 30))
255        );
256        assert_eq!(rect(900, 0, 100, 50).intersect(&surface), None);
257        assert_eq!(rect(0, 600, 100, 50).intersect(&surface), None);
258        assert_eq!(rect(10, 10, 0, 0).intersect(&surface), None);
259    }
260
261    #[test]
262    fn intersect_does_not_overflow() {
263        let surface = rect(0, 0, 800, 600);
264        assert_eq!(
265            rect(u32::MAX, u32::MAX, u32::MAX, u32::MAX).intersect(&surface),
266            None
267        );
268        assert_eq!(
269            rect(10, 10, u32::MAX, u32::MAX).intersect(&surface),
270            Some(rect(10, 10, 790, 590))
271        );
272    }
273}