Skip to main content

alpha2_render/
bind_group.rs

1//! Bind groups, all made through [`BindGroups::create`], kept by what they bind when it is ours.
2
3use std::collections::{HashMap, HashSet};
4use std::num::NonZeroU64;
5use std::sync::Mutex;
6
7use crate::retire::Retired;
8
9/// Bind group creation and reuse counters.
10#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
11pub struct BindGroupStats {
12    /// Bind groups created since renderer construction.
13    pub created: u64,
14    /// Requests served by a kept bind group.
15    pub reused: u64,
16    /// Bind groups kept for reuse now.
17    pub kept: usize,
18}
19
20#[derive(Debug)]
21pub(crate) struct OffsetBindGroup<const N: usize> {
22    pub(crate) group: wgpu::BindGroup,
23    // WebGPU takes dynamic offsets in binding number order.
24    pub(crate) offsets: [u32; N],
25}
26
27impl<const N: usize> OffsetBindGroup<N> {
28    pub(crate) fn set(&self, pass: &mut wgpu::RenderPass<'_>, index: u32) {
29        pass.set_bind_group(index, &self.group, &self.offsets);
30    }
31}
32
33pub(crate) const SAMPLER_GROUP: u32 = 1;
34
35#[derive(Debug)]
36pub(crate) struct LinearSampler {
37    pub(crate) layout: wgpu::BindGroupLayout,
38    pub(crate) group: wgpu::BindGroup,
39}
40
41impl LinearSampler {
42    pub(crate) fn new(device: &wgpu::Device, bind_groups: &BindGroups) -> Self {
43        let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
44            label: Some("alpha2 linear sampler layout"),
45            entries: &[wgpu::BindGroupLayoutEntry {
46                binding: 0,
47                visibility: wgpu::ShaderStages::FRAGMENT,
48                ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
49                count: None,
50            }],
51        });
52        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
53            label: Some("alpha2 linear sampler"),
54            address_mode_u: wgpu::AddressMode::ClampToEdge,
55            address_mode_v: wgpu::AddressMode::ClampToEdge,
56            mag_filter: wgpu::FilterMode::Linear,
57            min_filter: wgpu::FilterMode::Linear,
58            ..Default::default()
59        });
60        let group = bind_groups.create(
61            device,
62            &wgpu::BindGroupDescriptor {
63                label: Some("alpha2 linear sampler group"),
64                layout: &layout,
65                entries: &[wgpu::BindGroupEntry {
66                    binding: 0,
67                    resource: wgpu::BindingResource::Sampler(&sampler),
68                }],
69            },
70            0,
71        );
72        Self { layout, group }
73    }
74
75    pub(crate) fn set(&self, pass: &mut wgpu::RenderPass<'_>) {
76        pass.set_bind_group(SAMPLER_GROUP, &self.group, &[]);
77    }
78}
79
80const UNUSED_FRAMES_KEPT: u64 = 64;
81
82#[derive(Debug, Default)]
83pub(crate) struct BindGroups {
84    state: Mutex<State>,
85}
86
87#[derive(Debug, Default)]
88struct State {
89    owned_textures: HashSet<wgpu::Texture>,
90    owned_buffers: HashSet<wgpu::Buffer>,
91    kept: HashMap<Box<[Bound]>, Kept>,
92    key: Vec<Bound>,
93    frame: u64,
94    created: u64,
95    reused: u64,
96}
97
98#[derive(Debug)]
99struct Kept {
100    group: wgpu::BindGroup,
101    used_frame: u64,
102}
103
104#[derive(Clone, Debug, Eq, Hash, PartialEq)]
105enum Bound {
106    Layout(wgpu::BindGroupLayout),
107    View(u32, wgpu::TextureView),
108    Sampler(u32, wgpu::Sampler),
109    Buffer(u32, wgpu::Buffer, u64, Option<NonZeroU64>),
110}
111
112impl Bound {
113    fn binds_texture(&self, texture: &wgpu::Texture) -> bool {
114        matches!(self, Self::View(_, view) if view.texture() == texture)
115    }
116
117    fn binds_buffer(&self, buffer: &wgpu::Buffer) -> bool {
118        matches!(self, Self::Buffer(_, bound, ..) if bound == buffer)
119    }
120}
121
122impl BindGroups {
123    pub(crate) fn create(
124        &self,
125        device: &wgpu::Device,
126        descriptor: &wgpu::BindGroupDescriptor<'_>,
127        frame: u64,
128    ) -> wgpu::BindGroup {
129        let mut state = self.lock();
130        if state.frame != frame {
131            state.frame = frame;
132            state
133                .kept
134                .retain(|_, kept| frame.saturating_sub(kept.used_frame) < UNUSED_FRAMES_KEPT);
135        }
136        let mut key = std::mem::take(&mut state.key);
137        key.clear();
138        let keepable = state.key_of(descriptor, &mut key);
139        if keepable && let Some(kept) = state.kept.get_mut(key.as_slice()) {
140            kept.used_frame = frame;
141            let group = kept.group.clone();
142            state.reused = state.reused.saturating_add(1);
143            state.key = key;
144            return group;
145        }
146        state.created = state.created.saturating_add(1);
147        #[expect(
148            clippy::disallowed_methods,
149            reason = "the one place a bind group is created"
150        )]
151        let group = device.create_bind_group(descriptor);
152        if keepable {
153            state.kept.insert(
154                key.into_boxed_slice(),
155                Kept {
156                    group: group.clone(),
157                    used_frame: frame,
158                },
159            );
160        } else {
161            state.key = key;
162        }
163        group
164    }
165
166    pub(crate) fn adopt_texture(&self, texture: &wgpu::Texture) {
167        self.lock().owned_textures.insert(texture.clone());
168    }
169
170    pub(crate) fn adopt_buffer(&self, buffer: &wgpu::Buffer) {
171        self.lock().owned_buffers.insert(buffer.clone());
172    }
173
174    pub(crate) fn release(&self, resource: &Retired) {
175        match resource {
176            Retired::Texture(texture) => self.release_texture(texture),
177            Retired::Buffer(buffer) => self.release_buffer(buffer),
178        }
179    }
180
181    pub(crate) fn release_texture(&self, texture: &wgpu::Texture) {
182        let mut state = self.lock();
183        if state.owned_textures.remove(texture) {
184            state
185                .kept
186                .retain(|key, _| !key.iter().any(|bound| bound.binds_texture(texture)));
187        }
188    }
189
190    pub(crate) fn release_buffer(&self, buffer: &wgpu::Buffer) {
191        let mut state = self.lock();
192        if state.owned_buffers.remove(buffer) {
193            state
194                .kept
195                .retain(|key, _| !key.iter().any(|bound| bound.binds_buffer(buffer)));
196        }
197    }
198
199    pub(crate) fn clear(&self) {
200        self.lock().kept.clear();
201    }
202
203    pub(crate) fn stats(&self) -> BindGroupStats {
204        let state = self.lock();
205        BindGroupStats {
206            created: state.created,
207            reused: state.reused,
208            kept: state.kept.len(),
209        }
210    }
211
212    fn lock(&self) -> std::sync::MutexGuard<'_, State> {
213        self.state
214            .lock()
215            .unwrap_or_else(std::sync::PoisonError::into_inner)
216    }
217}
218
219impl State {
220    fn key_of(&self, descriptor: &wgpu::BindGroupDescriptor<'_>, key: &mut Vec<Bound>) -> bool {
221        key.push(Bound::Layout(descriptor.layout.clone()));
222        for entry in descriptor.entries {
223            let bound = match &entry.resource {
224                wgpu::BindingResource::TextureView(view)
225                    if self.owned_textures.contains(view.texture()) =>
226                {
227                    Bound::View(entry.binding, (*view).clone())
228                }
229                wgpu::BindingResource::Sampler(sampler) => {
230                    Bound::Sampler(entry.binding, (*sampler).clone())
231                }
232                wgpu::BindingResource::Buffer(binding)
233                    if self.owned_buffers.contains(binding.buffer) =>
234                {
235                    Bound::Buffer(
236                        entry.binding,
237                        binding.buffer.clone(),
238                        binding.offset,
239                        binding.size,
240                    )
241                }
242                _ => return false,
243            };
244            key.push(bound);
245        }
246        key.iter()
247            .any(|bound| matches!(bound, Bound::View(..) | Bound::Buffer(..)))
248    }
249}