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
|
use cgmath::Matrix4;
use wgpu::util::DeviceExt;
pub struct MatrixUniform {
buffer: wgpu::Buffer,
pub bind_group: wgpu::BindGroup,
}
impl MatrixUniform {
pub fn new(
device: &wgpu::Device,
bind_group_layout: &wgpu::BindGroupLayout,
init: Matrix4<f32>,
name: &str,
writable: bool,
) -> Self {
let uniform: [[f32; 4]; 4] = init.into();
let mut usage = wgpu::BufferUsages::UNIFORM;
if writable {
usage |= wgpu::BufferUsages::COPY_DST;
}
let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some(&format!("{name}.buffer")),
contents: bytemuck::cast_slice(&[uniform]),
usage,
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: buffer.as_entire_binding(),
}],
label: Some(&format!("{name}.bind_group")),
});
Self { buffer, bind_group }
}
pub fn layout(device: &wgpu::Device, name: &str) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
label: Some(&format!("{name}.bind_group_layout")),
})
}
pub fn set(&self, queue: &wgpu::Queue, to: Matrix4<f32>) {
let uniform: [[f32; 4]; 4] = to.into();
queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&[uniform]));
}
}
|