iced_wgpu/
buffer.rs

1use std::marker::PhantomData;
2use std::num::NonZeroU64;
3use std::ops::RangeBounds;
4
5pub const MAX_WRITE_SIZE: usize = 100 * 1024;
6
7#[allow(unsafe_code)]
8const MAX_WRITE_SIZE_U64: NonZeroU64 =
9    unsafe { NonZeroU64::new_unchecked(MAX_WRITE_SIZE as u64) };
10
11#[derive(Debug)]
12pub struct Buffer<T> {
13    label: &'static str,
14    size: u64,
15    usage: wgpu::BufferUsages,
16    pub(crate) raw: wgpu::Buffer,
17    offsets: Vec<wgpu::BufferAddress>,
18    type_: PhantomData<T>,
19}
20
21impl<T: bytemuck::Pod> Buffer<T> {
22    pub fn new(
23        device: &wgpu::Device,
24        label: &'static str,
25        amount: usize,
26        usage: wgpu::BufferUsages,
27    ) -> Self {
28        let size = next_copy_size::<T>(amount);
29
30        let raw = device.create_buffer(&wgpu::BufferDescriptor {
31            label: Some(label),
32            size,
33            usage,
34            mapped_at_creation: false,
35        });
36
37        Self {
38            label,
39            size,
40            usage,
41            raw,
42            offsets: Vec::new(),
43            type_: PhantomData,
44        }
45    }
46
47    pub fn resize(&mut self, device: &wgpu::Device, new_count: usize) -> bool {
48        let new_size = (std::mem::size_of::<T>() * new_count) as u64;
49
50        if self.size < new_size {
51            self.offsets.clear();
52
53            self.raw = device.create_buffer(&wgpu::BufferDescriptor {
54                label: Some(self.label),
55                size: new_size,
56                usage: self.usage,
57                mapped_at_creation: false,
58            });
59
60            self.size = new_size;
61
62            true
63        } else {
64            false
65        }
66    }
67
68    /// Returns the size of the written bytes.
69    pub fn write(
70        &mut self,
71        device: &wgpu::Device,
72        encoder: &mut wgpu::CommandEncoder,
73        belt: &mut wgpu::util::StagingBelt,
74        offset: usize,
75        contents: &[T],
76    ) -> usize {
77        let bytes: &[u8] = bytemuck::cast_slice(contents);
78        let mut bytes_written = 0;
79
80        // Split write into multiple chunks if necessary
81        while bytes_written + MAX_WRITE_SIZE < bytes.len() {
82            belt.write_buffer(
83                encoder,
84                &self.raw,
85                (offset + bytes_written) as u64,
86                MAX_WRITE_SIZE_U64,
87                device,
88            )
89            .copy_from_slice(
90                &bytes[bytes_written..bytes_written + MAX_WRITE_SIZE],
91            );
92
93            bytes_written += MAX_WRITE_SIZE;
94        }
95
96        // There will always be some bytes left, since the previous
97        // loop guarantees `bytes_written < bytes.len()`
98        let bytes_left = ((bytes.len() - bytes_written) as u64)
99            .try_into()
100            .expect("non-empty write");
101
102        // Write them
103        belt.write_buffer(
104            encoder,
105            &self.raw,
106            (offset + bytes_written) as u64,
107            bytes_left,
108            device,
109        )
110        .copy_from_slice(&bytes[bytes_written..]);
111
112        self.offsets.push(offset as u64);
113
114        bytes.len()
115    }
116
117    pub fn slice(
118        &self,
119        bounds: impl RangeBounds<wgpu::BufferAddress>,
120    ) -> wgpu::BufferSlice<'_> {
121        self.raw.slice(bounds)
122    }
123
124    /// Returns the slice calculated from the offset stored at the given index.
125    pub fn slice_from_index(&self, index: usize) -> wgpu::BufferSlice<'_> {
126        self.raw.slice(self.offset_at(index)..)
127    }
128
129    /// Clears any temporary data (i.e. offsets) from the buffer.
130    pub fn clear(&mut self) {
131        self.offsets.clear();
132    }
133
134    /// Returns the offset at `index`, if it exists.
135    fn offset_at(&self, index: usize) -> &wgpu::BufferAddress {
136        self.offsets.get(index).expect("No offset at index.")
137    }
138}
139
140fn next_copy_size<T>(amount: usize) -> u64 {
141    let align_mask = wgpu::COPY_BUFFER_ALIGNMENT - 1;
142
143    (((std::mem::size_of::<T>() * amount).next_power_of_two() as u64
144        + align_mask)
145        & !align_mask)
146        .max(wgpu::COPY_BUFFER_ALIGNMENT)
147}