mln-rs-webgpu 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Small buffer writes, copied into place ahead of the next frame's commands.
//! A frame writes many small runs (uniforms, symbol vertices), and on Metal
//! wgpu's `Queue::write_buffer` makes a staging buffer for every call, a trip
//! into the kernel each.
//!
//! Natively each write goes straight into a staging belt's mapped memory, and
//! a write that continues the previous one, in both its buffer and the belt,
//! joins its copy. In the browser, where mapping waits for the event loop,
//! the writes are gathered, merged where they touch or overlap in one buffer
//! (the later write's bytes winning), and uploaded with one
//! `Queue::write_buffer` into a staging buffer that is kept while it's big
//! enough. Bytes that are still in a JS array (`write_buffer_from_host`) go to
//! `GPUQueue.writeBuffer` from there instead, without a copy in wasm
//! memory.

#[cfg(any(target_arch = "wasm32", test))]
use std::ops::Range;

/// Writes up to this size are gathered; larger ones go to the queue.
const GATHERED: usize = 64 << 10;

#[cfg(any(target_arch = "wasm32", test))]
/// A gathered write: `len` bytes at `offset` in `buffer`, from `at` in the
/// gathered data. Generic over the buffer only for the tests.
#[derive(Clone, Debug)]
struct Write<B> {
    buffer: B,
    offset: u64,
    at: u64,
    len: u64,
}

#[cfg(any(target_arch = "wasm32", test))]
/// One copy into place: `len` bytes at `offset` in the buffer of its writes,
/// from `at` in the upload, made of the writes `order[writes]`.
#[derive(Clone, Debug)]
struct Run {
    offset: u64,
    at: u64,
    len: u64,
    writes: Range<usize>,
    /// Whether its writes overlap, so must land in the order they came.
    overlapping: bool,
}

#[cfg(any(target_arch = "wasm32", test))]
#[derive(Debug)]
struct Pending<B> {
    data: Vec<u8>,
    writes: Vec<Write<B>>,
    /// The writes' indices by buffer and offset, and the runs they merge
    /// into: kept for their allocations.
    order: Vec<usize>,
    runs: Vec<Run>,
}

#[cfg(any(target_arch = "wasm32", test))]
impl<B> Default for Pending<B> {
    fn default() -> Self {
        Self { data: Vec::new(), writes: Vec::new(), order: Vec::new(), runs: Vec::new() }
    }
}

#[cfg(any(target_arch = "wasm32", test))]
impl<B: Ord> Pending<B> {
    /// Gathers `data` and the zeros after it up to `padded` bytes.
    fn gather(&mut self, buffer: B, offset: u64, data: &[u8], padded: u64) {
        let at = self.data.len();
        self.data.extend_from_slice(data);
        self.data.resize(at + padded as usize, 0);
        self.writes.push(Write { buffer, offset, at: at as u64, len: padded });
    }

    #[cfg(target_arch = "wasm32")]
    /// Whether a gathered write touches `len` bytes at `offset` of `buffer`:
    /// a write that goes to the queue directly would land before it.
    fn overlaps(&self, buffer: &B, offset: u64, len: u64) -> bool {
        self.writes.iter().any(|w| w.buffer == *buffer && w.offset < offset + len && offset < w.offset + w.len)
    }

    /// The buffer that `run` copies into.
    fn target(&self, run: &Run) -> &B {
        &self.writes[self.order[run.writes.start]].buffer
    }

    /// Merges the writes into runs and returns the upload's size.
    fn plan(&mut self) -> u64 {
        let Self { writes, order, runs, .. } = self;
        order.clear();
        order.extend(0..writes.len());
        order.sort_unstable_by(|&a, &b| {
            (&writes[a].buffer, writes[a].offset, a).cmp(&(&writes[b].buffer, writes[b].offset, b))
        });
        runs.clear();
        let mut size = 0;
        for (n, &i) in order.iter().enumerate() {
            let w = &writes[i];
            if let Some(run) = runs.last_mut()
                && writes[order[run.writes.start]].buffer == w.buffer
                && w.offset <= run.offset + run.len
            {
                let end = run.offset + run.len;
                run.overlapping |= w.offset < end;
                let grown = (w.offset + w.len).saturating_sub(end);
                run.len += grown;
                run.writes.end = n + 1;
                size += grown;
            } else {
                runs.push(Run { offset: w.offset, at: size, len: w.len, writes: n..n + 1, overlapping: false });
                size += w.len;
            }
        }
        size
    }

    /// Lays the planned runs out in the upload, `plan`'s size long: `put`
    /// writes bytes at an offset in it.
    fn fill(&mut self, mut put: impl FnMut(usize, &[u8])) {
        let Self { data, writes, order, runs } = self;
        for run in runs.iter() {
            let members = &mut order[run.writes.clone()];
            if run.overlapping {
                // Gathered order, so later writes land over earlier ones.
                members.sort_unstable();
            }
            for &i in members.iter() {
                let w = &writes[i];
                let (at, len) = (w.at as usize, w.len as usize);
                put((run.at + w.offset - run.offset) as usize, &data[at..at + len]);
            }
        }
    }

    #[cfg(target_arch = "wasm32")]
    fn clear(&mut self) {
        self.data.clear();
        self.writes.clear();
        self.runs.clear();
    }
}

/// The buffer writes made since the last submission, and the staging
/// memory that uploads them.
#[derive(Debug, Default)]
pub(crate) struct Writes {
    #[cfg(not(target_arch = "wasm32"))]
    belt: Option<wgpu::util::StagingBelt>,
    #[cfg(not(target_arch = "wasm32"))]
    copies: Vec<Copy>,
    #[cfg(target_arch = "wasm32")]
    pending: Pending<wgpu::Buffer>,
    /// Reused while it's big enough: writes to it are ordered after the
    /// submissions that copied from it.
    #[cfg(target_arch = "wasm32")]
    staging: Option<wgpu::Buffer>,
    #[cfg(target_arch = "wasm32")]
    upload: Vec<u8>,
    /// Whether direct `Queue::write_buffer` / `Queue::write_texture` writes
    /// have been queued since the last submission.
    queue_writes: bool,
}

/// A copy from the belt into place.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
struct Copy {
    staging: wgpu::Buffer,
    at: u64,
    target: wgpu::Buffer,
    offset: u64,
    len: u64,
}

impl Writes {
    /// Writes `data` at `offset` in `buffer` ahead of the commands submitted
    /// after the next [`encode`](Self::encode)'s, as `Queue::write_buffer`
    /// does ahead of the next submission's. The bytes after `data` up to
    /// `padded` bytes from `offset` already hold zeros: those may be written
    /// too, so that the copy can join the next write's.
    pub(crate) fn write_padded(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        buffer: &wgpu::Buffer,
        offset: u64,
        data: &[u8],
        padded: u64,
    ) {
        debug_assert!(padded >= data.len() as u64);
        if data.is_empty() {
            return;
        }
        // Copies take 4-byte offsets and sizes: the queue reports an
        // unaligned write.
        let len = data.len() as u64;
        let aligned =
            offset.is_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT) && len.is_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT);
        let padded = if padded.is_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT) { padded } else { len };
        if aligned
            && (data.len() <= GATHERED || self.overlaps(buffer, offset, len))
            && self.gather(device, buffer, offset, data, padded)
        {
            return;
        }
        queue.write_buffer(buffer, offset, data);
        self.queue_writes = true;
    }

    /// Writes the first `len` bytes of `data`, a multiple of 4, at `offset`
    /// in `buffer` with `GPUQueue.writeBuffer`, straight from the JS array,
    /// ahead of the commands submitted after the next
    /// [`encode`](Self::encode)'s. That's also ahead of the writes gathered
    /// so far: those it overlaps are submitted first.
    #[cfg(target_family = "wasm")]
    pub(crate) fn write_from_host(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        buffer: &wgpu::Buffer,
        offset: u64,
        data: &js_sys::Uint8Array,
        len: u64,
    ) {
        if len == 0 {
            return;
        }
        debug_assert!(len.is_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT));
        if self.overlaps(buffer, offset, len)
            && let Some(writes) = self.encode(device, queue)
        {
            queue.submit([writes]);
        }
        let (Some(queue), Some(buffer)) = (queue.as_webgpu(), buffer.as_webgpu()) else {
            return;
        };
        if let Err(error) =
            queue.write_buffer_with_f64_and_u8_array_and_u32_and_u32(buffer, offset as f64, data, 0, len as u32)
        {
            tracing::error!(target: crate::log_target::RENDER, error = ?error, "Writing a buffer from a JS array failed");
        } else {
            self.queue_writes = true;
        }
    }

    /// Copies `data` and the zeros after it up to `padded` bytes into the
    /// belt, to land at `offset` in `buffer`; false if the belt's slice isn't
    /// mapped.
    #[cfg(not(target_arch = "wasm32"))]
    fn gather(&mut self, device: &wgpu::Device, buffer: &wgpu::Buffer, offset: u64, data: &[u8], padded: u64) -> bool {
        let Some(size) = wgpu::BufferSize::new(padded) else {
            return true;
        };
        let belt = self.belt.get_or_insert_with(|| wgpu::util::StagingBelt::new(device.clone(), GATHERED as u64));
        let slice = belt.allocate(size, wgpu::BufferSize::MIN);
        let Ok(mut view) = slice.get_mapped_range_mut() else {
            return false;
        };
        view.slice(0..data.len()).copy_from_slice(data);
        view.slice(data.len()..padded as usize).fill(0);
        drop(view);
        let (staging, at, len) = (slice.buffer().clone(), slice.offset(), size.get());
        if let Some(last) = self.copies.last_mut()
            && last.staging == staging
            && last.target == *buffer
            && last.at + last.len == at
            && last.offset + last.len == offset
        {
            last.len += len;
        } else {
            self.copies.push(Copy { staging, at, target: buffer.clone(), offset, len });
        }
        true
    }

    #[cfg(target_arch = "wasm32")]
    fn gather(&mut self, _device: &wgpu::Device, buffer: &wgpu::Buffer, offset: u64, data: &[u8], padded: u64) -> bool {
        self.pending.gather(buffer.clone(), offset, data, padded);
        true
    }

    /// Whether a write made since the last submission touches `len` bytes at
    /// `offset` of `buffer`: a write that goes to the queue directly would
    /// land before it.
    #[cfg(not(target_arch = "wasm32"))]
    fn overlaps(&self, buffer: &wgpu::Buffer, offset: u64, len: u64) -> bool {
        self.copies.iter().any(|c| c.target == *buffer && c.offset < offset + len && offset < c.offset + c.len)
    }

    #[cfg(target_arch = "wasm32")]
    fn overlaps(&self, buffer: &wgpu::Buffer, offset: u64, len: u64) -> bool {
        self.pending.overlaps(buffer, offset, len)
    }

    /// Records a direct write made on the wgpu queue outside this buffer
    /// uploader, so a nonblocking flush still submits it.
    pub(crate) fn note_queue_write(&mut self) {
        self.queue_writes = true;
    }

    /// Marks any direct queue writes as submitted.
    pub(crate) fn submitted(&mut self) {
        self.queue_writes = false;
    }

    /// Whether there are no pending writes to encode or submit.
    pub(crate) fn is_empty(&self) -> bool {
        if self.queue_writes {
            return false;
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            self.copies.is_empty()
        }
        #[cfg(target_arch = "wasm32")]
        {
            self.pending.writes.is_empty()
        }
    }

    /// Returns the commands that copy the writes into place, to submit ahead
    /// of the rest, or `None` when there are none.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fn encode(&mut self, device: &wgpu::Device, _queue: &wgpu::Queue) -> Option<wgpu::CommandBuffer> {
        if self.copies.is_empty() {
            return None;
        }
        let mut encoder =
            device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Buffer writes") });
        for c in self.copies.drain(..) {
            encoder.copy_buffer_to_buffer(&c.staging, c.at, &c.target, c.offset, c.len);
        }
        if let Some(belt) = &mut self.belt {
            belt.finish_and_recall_on_submit(&encoder);
        }
        Some(encoder.finish())
    }

    #[cfg(target_arch = "wasm32")]
    pub(crate) fn encode(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> Option<wgpu::CommandBuffer> {
        let size = self.pending.plan();
        if size == 0 {
            return None;
        }
        let upload = &mut self.upload;
        upload.clear();
        upload.resize(size as usize, 0);
        self.pending.fill(|to, bytes| upload[to..to + bytes.len()].copy_from_slice(bytes));
        let staging = match &self.staging {
            Some(staging) if staging.size() >= size => staging.clone(),
            _ => {
                let staging = device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("Buffer writes"),
                    size: size.next_power_of_two().max(GATHERED as u64),
                    usage: wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
                    mapped_at_creation: false,
                });
                self.staging = Some(staging.clone());
                staging
            }
        };
        queue.write_buffer(&staging, 0, upload.as_slice());
        let mut encoder =
            device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Buffer writes") });
        for run in &self.pending.runs {
            encoder.copy_buffer_to_buffer(&staging, run.at, self.pending.target(run), run.offset, run.len);
        }
        self.pending.clear();
        Some(encoder.finish())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn upload(writes: &[(u32, u64, &[u8])]) -> (Vec<(u32, u64, Vec<u8>)>, u64) {
        let padded: Vec<_> = writes.iter().map(|&(b, o, d)| (b, o, d, d.len() as u64)).collect();
        upload_padded(&padded)
    }

    fn upload_padded(writes: &[(u32, u64, &[u8], u64)]) -> (Vec<(u32, u64, Vec<u8>)>, u64) {
        let mut pending = Pending::default();
        for &(b, o, d, padded) in writes {
            pending.gather(b, o, d, padded);
        }
        let size = pending.plan();
        let mut bytes = vec![0; size as usize];
        pending.fill(|to, b| bytes[to..to + b.len()].copy_from_slice(b));
        let runs = pending
            .runs
            .iter()
            .map(|r| {
                let at = r.at as usize;
                (*pending.target(r), r.offset, bytes[at..at + r.len as usize].to_vec())
            })
            .collect();
        (runs, size)
    }

    #[test]
    fn merges_touching_writes_into_one_copy() {
        let (runs, size) = upload(&[
            (1, 8, &[3, 3, 3, 3]),
            (0, 0, &[1, 1, 1, 1]),
            (1, 0, &[2, 2, 2, 2, 2, 2, 2, 2]),
            (0, 8, &[4, 4, 4, 4]),
        ]);
        assert_eq!(
            runs,
            [(0, 0, vec![1, 1, 1, 1]), (0, 8, vec![4, 4, 4, 4]), (1, 0, vec![2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3])]
        );
        assert_eq!(size, 20);
    }

    #[test]
    fn later_writes_win_where_they_overlap() {
        let (runs, _) = upload(&[
            (0, 4, &[1, 1, 1, 1, 1, 1, 1, 1]),
            (0, 0, &[2, 2, 2, 2, 2, 2, 2, 2]),
            (0, 8, &[3, 3, 3, 3]),
            (0, 4, &[4, 4, 4, 4]),
        ]);
        assert_eq!(runs, [(0, 0, vec![2, 2, 2, 2, 4, 4, 4, 4, 3, 3, 3, 3])]);
    }

    #[test]
    fn padding_joins_writes_to_neighboring_slots() {
        let (runs, size) = upload_padded(&[(0, 0, &[1, 1, 1, 1], 8), (0, 8, &[2, 2, 2, 2], 8)]);
        assert_eq!(runs, [(0, 0, vec![1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0])]);
        assert_eq!(size, 16);
    }
}