cranpose-wgpu-hal 30.0.21

Cranpose's patched fork of wgpu-hal 30.0.1 (forks/README.md in the Cranpose repository). Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! The GL state a command buffer's commands have set, so that a command
//! setting what the context already holds makes no GL call.
//!
//! On WebGL every GL call crosses from WebAssembly into JavaScript and is
//! validated and serialized for the browser's GPU process, which decodes and
//! validates it again. The encoder re-specifies every vertex attribute of a
//! pipeline at each draw whose buffers or first instance moved, disables them
//! all at each pipeline switch, and binds textures, uniform buffers and the
//! scissor again for every batch; most of those calls set what is already set.
//!
//! The state lives for one command buffer: the queue resets the context's
//! state before each one, and the device's own calls (buffer and texture
//! uploads) run between them. Any command the tracker does not know forgets
//! everything it holds, after it has made the context agree with the commands
//! it deferred.

use alloc::vec::Vec;
use core::{fmt, ops::Range};

use glow::HasContext;

use super::{
    AttributeDesc, BlendDesc, ColorTargetDesc, Command as C, DepthState, StencilOps,
    VertexAttribKind, VertexBufferDesc, MAX_TEXTURE_SLOTS, MAX_VERTEX_ATTRIBUTES,
};

/// Uniform buffer bindings tracked by slot; a slot above them is bound
/// every time.
const TRACKED_UNIFORM_SLOTS: usize = 16;

/// Where one attribute reads its data, as `glVertexAttrib[I]Pointer` set it.
#[derive(Clone, Copy, PartialEq)]
struct AttributePointer {
    buffer: glow::Buffer,
    size: i32,
    format: u32,
    integer: bool,
    stride: i32,
    offset: i32,
}

#[derive(Clone, Copy, Default)]
struct Attribute {
    enabled: Option<bool>,
    divisor: Option<u32>,
    pointer: Option<AttributePointer>,
}

#[derive(Clone, PartialEq)]
struct BoundTexture {
    target: u32,
    texture: glow::Texture,
    aspects: crate::FormatAspects,
    mip_levels: Range<u32>,
}

#[derive(Clone, Copy, PartialEq)]
struct StencilFunc {
    function: u32,
    reference: u32,
    read_mask: u32,
}

#[derive(Clone, PartialEq)]
struct StencilWrite {
    write_mask: u32,
    ops: StencilOps,
}

/// The tracked state; `None` is a value the tracker does not know.
#[derive(Default)]
pub(super) struct GlState {
    array_buffer: Option<glow::Buffer>,
    attributes: [Attribute; MAX_VERTEX_ATTRIBUTES],
    /// Attributes an `UnsetVertexAttribute` turned off, which stay enabled
    /// until an untracked command or the end of the command buffer needs the
    /// context to agree: the next pipeline usually enables most of them
    /// again, and a draw reads none of them (see `apply`).
    pending_disables: u32,
    program: Option<glow::Program>,
    scissor: Option<(i32, i32, i32, i32)>,
    scissor_test: Option<bool>,
    depth_test: Option<bool>,
    stencil_test: Option<bool>,
    depth: Option<(u32, bool)>,
    /// Front and back faces.
    stencil_funcs: [Option<StencilFunc>; 2],
    stencil_writes: [Option<StencilWrite>; 2],
    uniform_buffers: [Option<(glow::Buffer, i32, i32)>; TRACKED_UNIFORM_SLOTS],
    active_texture: Option<u32>,
    textures: [Option<BoundTexture>; MAX_TEXTURE_SLOTS],
    samplers: [Option<Option<glow::Sampler>>; MAX_TEXTURE_SLOTS],
    /// The default draw buffer's write mask.
    color_mask: Option<wgt::ColorWrites>,
    blend: Option<bool>,
    /// The color and alpha blend equations.
    blend_equations: Option<(u32, u32)>,
    /// The color source and destination factors, then the alpha ones.
    blend_funcs: Option<[u32; 4]>,
    element_buffer: Option<glow::Buffer>,
    /// The base and max levels and the aspects each texture was last bound
    /// with: state of the texture object, which a bind with the same ones
    /// need not set again.
    texture_levels: Vec<(glow::Texture, Range<u32>, crate::FormatAspects)>,
    /// The first-instance uniform each program last drew with: state of the
    /// program object.
    first_instances: Vec<(glow::Program, u32)>,
}

impl fmt::Debug for GlState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("GlState").finish_non_exhaustive()
    }
}

impl GlState {
    /// Runs `command` when the tracker owns it and returns `true`; otherwise
    /// makes the context agree with what the tracker deferred, forgets what
    /// the command may change, and returns `false` for the queue to run it.
    /// `first_instance` is where the program in use takes its emulated first
    /// instance, which the tracker sets for each draw.
    pub(super) unsafe fn apply(
        &mut self,
        gl: &glow::Context,
        command: &C,
        first_instance: Option<&glow::UniformLocation>,
    ) -> bool {
        match *command {
            C::SetVertexAttribute {
                buffer: Some(buffer),
                ref buffer_desc,
                ref attribute_desc,
            } => unsafe { self.set_attribute(gl, buffer, buffer_desc, attribute_desc) },
            C::UnsetVertexAttribute(location) => {
                self.pending_disables |= 1 << location;
            }
            C::SetProgram(ref inner) => {
                let program = inner.program;
                if self.program != Some(program) {
                    unsafe { gl.use_program(Some(program)) };
                    self.program = Some(program);
                }
            }
            C::SetScissor(ref rect) => {
                let scissor = (rect.x, rect.y, rect.w, rect.h);
                if self.scissor != Some(scissor) {
                    unsafe { gl.scissor(rect.x, rect.y, rect.w, rect.h) };
                    self.scissor = Some(scissor);
                }
                unsafe { Self::toggle(gl, &mut self.scissor_test, glow::SCISSOR_TEST, true) };
            }
            C::ConfigureDepthStencil(aspects) => unsafe {
                let depth = aspects.contains(crate::FormatAspects::DEPTH);
                let stencil = aspects.contains(crate::FormatAspects::STENCIL);
                Self::toggle(gl, &mut self.depth_test, glow::DEPTH_TEST, depth);
                Self::toggle(gl, &mut self.stencil_test, glow::STENCIL_TEST, stencil);
            },
            C::SetDepth(DepthState { function, mask }) => {
                if self.depth != Some((function, mask)) {
                    unsafe { gl.depth_func(function) };
                    unsafe { gl.depth_mask(mask) };
                    self.depth = Some((function, mask));
                }
            }
            C::SetStencilFunc {
                face,
                function,
                reference,
                read_mask,
            } => {
                let func = StencilFunc {
                    function,
                    reference,
                    read_mask,
                };
                if Self::stencil_faces(face).any(|side| self.stencil_funcs[side] != Some(func)) {
                    unsafe {
                        gl.stencil_func_separate(face, function, reference as i32, read_mask)
                    };
                    for side in Self::stencil_faces(face) {
                        self.stencil_funcs[side] = Some(func);
                    }
                }
            }
            C::SetStencilOps {
                face,
                write_mask,
                ref ops,
            } => {
                let write = StencilWrite {
                    write_mask,
                    ops: ops.clone(),
                };
                if Self::stencil_faces(face)
                    .any(|side| self.stencil_writes[side].as_ref() != Some(&write))
                {
                    unsafe { gl.stencil_mask_separate(face, write_mask) };
                    unsafe { gl.stencil_op_separate(face, ops.fail, ops.depth_fail, ops.pass) };
                    for side in Self::stencil_faces(face) {
                        self.stencil_writes[side] = Some(write.clone());
                    }
                }
            }
            C::BindBuffer {
                target: glow::UNIFORM_BUFFER,
                slot,
                buffer,
                offset,
                size,
            } if (slot as usize) < TRACKED_UNIFORM_SLOTS => {
                let binding = Some((buffer, offset, size));
                if self.uniform_buffers[slot as usize] != binding {
                    unsafe {
                        gl.bind_buffer_range(glow::UNIFORM_BUFFER, slot, Some(buffer), offset, size)
                    };
                    self.uniform_buffers[slot as usize] = binding;
                }
            }
            C::BindSampler(unit, sampler) => {
                if self.samplers[unit as usize] != Some(sampler) {
                    unsafe { gl.bind_sampler(unit, sampler) };
                    self.samplers[unit as usize] = Some(sampler);
                }
            }
            C::BindTexture {
                slot,
                texture,
                target,
                aspects,
                ref mip_levels,
            } => unsafe {
                self.bind_texture(
                    gl,
                    slot,
                    BoundTexture {
                        target,
                        texture,
                        aspects,
                        mip_levels: mip_levels.clone(),
                    },
                )
            },
            // Bindings of other targets and slots, and image units.
            C::BindBuffer { .. } | C::BindImage { .. } => return false,
            // The queue binds a new index buffer and notes it for its copies.
            C::SetIndexBuffer(buffer) => {
                if self.element_buffer == Some(buffer) {
                    return true;
                }
                self.element_buffer = Some(buffer);
                return false;
            }
            C::SetColorTarget {
                draw_buffer_index: None,
                desc: ColorTargetDesc { mask, ref blend },
            } => unsafe { self.set_color_target(gl, mask, blend.as_ref()) },
            // One draw buffer's own target leaves the default one unknown.
            C::SetColorTarget {
                draw_buffer_index: Some(_),
                ..
            } => {
                self.color_mask = None;
                self.blend = None;
                self.blend_equations = None;
                self.blend_funcs = None;
                return false;
            }
            // A draw's program reads only the attributes its pipeline pointed,
            // so the deferred disables wait: GL and WebGL fetch and range-check
            // only the attributes a program reads, and an attribute left
            // enabled keeps the live buffer it was pointed at.
            C::Draw { first_instance: value, .. } | C::DrawIndexed { first_instance: value, .. } => {
                if let Some(location) = first_instance {
                    unsafe { self.set_first_instance(gl, location, value) };
                }
                return false;
            }
            // The queue sets the first instance of an indirect draw to 0.
            C::DrawIndirect { .. } | C::DrawIndexedIndirect { .. } => {
                if let Some(program) = self.program {
                    self.first_instances.retain(|&(held, _)| held != program);
                }
                return false;
            }
            // State the tracker holds none of.
            C::SetViewport { .. }
            | C::SetDepthBias(_)
            | C::SetAlphaToCoverage(_)
            | C::SetPrimitive(_)
            | C::SetBlendConstant(_)
            | C::SetImmediates { .. }
            | C::SetClipDistances { .. }
            | C::InsertDebugMarker(_)
            | C::PushDebugGroup(_)
            | C::PopDebugGroup => return false,
            _ => {
                unsafe { self.forget(gl) };
                return false;
            }
        }
        true
    }

    /// Makes the context agree with the deferred disables at the end of a
    /// command buffer, which leaves the attributes as the encoder did.
    pub(super) unsafe fn finish(&mut self, gl: &glow::Context) {
        unsafe { self.disable_pending(gl) };
    }

    /// Forgets everything, as a new command buffer starts with the context
    /// in an unknown state, and keeps the lists' storage.
    pub(super) fn reset(&mut self) {
        let mut texture_levels = core::mem::take(&mut self.texture_levels);
        let mut first_instances = core::mem::take(&mut self.first_instances);
        texture_levels.clear();
        first_instances.clear();
        *self = Self {
            texture_levels,
            first_instances,
            ..Self::default()
        };
    }

    unsafe fn forget(&mut self, gl: &glow::Context) {
        unsafe { self.disable_pending(gl) };
        self.reset();
    }

    unsafe fn disable_pending(&mut self, gl: &glow::Context) {
        let mut pending = core::mem::take(&mut self.pending_disables);
        while pending != 0 {
            let location = pending.trailing_zeros();
            pending &= pending - 1;
            let attribute = &mut self.attributes[location as usize];
            if attribute.enabled != Some(false) {
                unsafe { gl.disable_vertex_attrib_array(location) };
                attribute.enabled = Some(false);
            }
        }
    }

    unsafe fn set_attribute(
        &mut self,
        gl: &glow::Context,
        buffer: glow::Buffer,
        buffer_desc: &VertexBufferDesc,
        attribute_desc: &AttributeDesc,
    ) {
        let location = attribute_desc.location;
        self.pending_disables &= !(1 << location);
        let format = &attribute_desc.format_desc;
        let pointer = AttributePointer {
            buffer,
            size: format.element_count,
            format: format.element_format,
            integer: matches!(format.attrib_kind, VertexAttribKind::Integer),
            stride: buffer_desc.stride as i32,
            offset: attribute_desc.offset as i32,
        };
        let divisor = buffer_desc.step as u32;
        let attribute = &mut self.attributes[location as usize];
        if attribute.enabled != Some(true) {
            unsafe { gl.enable_vertex_attrib_array(location) };
            attribute.enabled = Some(true);
        }
        if attribute.pointer != Some(pointer) {
            if self.array_buffer != Some(buffer) {
                unsafe { gl.bind_buffer(glow::ARRAY_BUFFER, Some(buffer)) };
                self.array_buffer = Some(buffer);
            }
            if pointer.integer {
                unsafe {
                    gl.vertex_attrib_pointer_i32(
                        location,
                        pointer.size,
                        pointer.format,
                        pointer.stride,
                        pointer.offset,
                    )
                };
            } else {
                unsafe {
                    gl.vertex_attrib_pointer_f32(
                        location,
                        pointer.size,
                        pointer.format,
                        true, // always normalized
                        pointer.stride,
                        pointer.offset,
                    )
                };
            }
            attribute.pointer = Some(pointer);
        }
        if attribute.divisor != Some(divisor) {
            unsafe { gl.vertex_attrib_divisor(location, divisor) };
            attribute.divisor = Some(divisor);
        }
    }

    unsafe fn bind_texture(&mut self, gl: &glow::Context, slot: u32, bound: BoundTexture) {
        if self.textures[slot as usize].as_ref() == Some(&bound) {
            return;
        }
        if self.active_texture != Some(slot) {
            unsafe { gl.active_texture(glow::TEXTURE0 + slot) };
            self.active_texture = Some(slot);
        }
        let BoundTexture {
            target,
            texture,
            aspects,
            ref mip_levels,
        } = bound;
        unsafe { gl.bind_texture(target, Some(texture)) };
        let levels = (texture, mip_levels.clone(), aspects);
        match self.texture_levels.iter_mut().find(|(held, ..)| *held == texture) {
            Some(held) if *held == levels => {
                self.textures[slot as usize] = Some(bound);
                return;
            }
            Some(held) => *held = levels,
            None => self.texture_levels.push(levels),
        }
        unsafe { gl.tex_parameter_i32(target, glow::TEXTURE_BASE_LEVEL, mip_levels.start as i32) };
        unsafe {
            gl.tex_parameter_i32(target, glow::TEXTURE_MAX_LEVEL, (mip_levels.end - 1) as i32)
        };

        let version = gl.version();
        let is_min_es_3_1 = version.is_embedded && (version.major, version.minor) >= (3, 1);
        let is_min_4_3 = !version.is_embedded && (version.major, version.minor) >= (4, 3);
        if is_min_es_3_1 || is_min_4_3 {
            let mode = match aspects {
                crate::FormatAspects::DEPTH => Some(glow::DEPTH_COMPONENT),
                crate::FormatAspects::STENCIL => Some(glow::STENCIL_INDEX),
                _ => None,
            };
            if let Some(mode) = mode {
                unsafe { gl.tex_parameter_i32(target, glow::DEPTH_STENCIL_TEXTURE_MODE, mode as _) };
            }
        }
        // The levels and mode just set belong to the texture: another unit
        // that holds it may now hold it with other ones.
        for other in self.textures.iter_mut() {
            if other.as_ref().is_some_and(|other| other.texture == texture) {
                *other = None;
            }
        }
        self.textures[slot as usize] = Some(bound);
    }

    /// Sets the default draw buffer's write mask and blend, each part only
    /// where it changes. One equation or pair of factors for both color and
    /// alpha takes the call that sets both.
    unsafe fn set_color_target(
        &mut self,
        gl: &glow::Context,
        mask: wgt::ColorWrites,
        blend: Option<&BlendDesc>,
    ) {
        use wgt::ColorWrites as Cw;
        if self.color_mask != Some(mask) {
            unsafe {
                gl.color_mask(
                    mask.contains(Cw::RED),
                    mask.contains(Cw::GREEN),
                    mask.contains(Cw::BLUE),
                    mask.contains(Cw::ALPHA),
                )
            };
            self.color_mask = Some(mask);
        }
        unsafe { Self::toggle(gl, &mut self.blend, glow::BLEND, blend.is_some()) };
        let Some(blend) = blend else {
            return;
        };
        let equations = (blend.color.equation, blend.alpha.equation);
        if self.blend_equations != Some(equations) {
            if equations.0 == equations.1 {
                unsafe { gl.blend_equation(equations.0) };
            } else {
                unsafe { gl.blend_equation_separate(equations.0, equations.1) };
            }
            self.blend_equations = Some(equations);
        }
        let funcs = [
            blend.color.src,
            blend.color.dst,
            blend.alpha.src,
            blend.alpha.dst,
        ];
        if self.blend_funcs != Some(funcs) {
            if funcs[..2] == funcs[2..] {
                unsafe { gl.blend_func(funcs[0], funcs[1]) };
            } else {
                unsafe { gl.blend_func_separate(funcs[0], funcs[1], funcs[2], funcs[3]) };
            }
            self.blend_funcs = Some(funcs);
        }
    }

    /// Sets the emulated first instance of the program in use at `location`,
    /// unless that program already holds `value`.
    unsafe fn set_first_instance(
        &mut self,
        gl: &glow::Context,
        location: &glow::UniformLocation,
        value: u32,
    ) {
        if let Some(program) = self.program {
            match self.first_instances.iter_mut().find(|(held, _)| *held == program) {
                Some((_, held)) if *held == value => return,
                Some((_, held)) => *held = value,
                None => self.first_instances.push((program, value)),
            }
        }
        unsafe { gl.uniform_1_u32(Some(location), value) };
    }

    unsafe fn toggle(gl: &glow::Context, known: &mut Option<bool>, capability: u32, on: bool) {
        if *known != Some(on) {
            if on {
                unsafe { gl.enable(capability) };
            } else {
                unsafe { gl.disable(capability) };
            }
            *known = Some(on);
        }
    }

    /// The faces, front (0) and back (1), a stencil call for `face` sets.
    fn stencil_faces(face: u32) -> impl Iterator<Item = usize> {
        let (front, back) = match face {
            glow::FRONT => (true, false),
            glow::BACK => (false, true),
            _ => (true, true),
        };
        [front.then_some(0), back.then_some(1)].into_iter().flatten()
    }
}