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
|
//! Draw meshes of triangles.
use crate::{settings, Transformation};
use core::fmt;
use std::fmt::Formatter;
use iced_graphics::layer::Meshes;
use iced_graphics::shader::Shader;
use iced_graphics::Size;
use crate::buffers::buffer::{needs_recreate, StaticBuffer};
use crate::triangle::gradient::GradientPipeline;
use crate::triangle::solid::SolidPipeline;
pub use iced_graphics::triangle::{Mesh2D, Vertex2D};
mod gradient;
mod msaa;
mod solid;
/// Triangle pipeline for all mesh layers in a [`iced_graphics::Canvas`] widget.
#[derive(Debug)]
pub(crate) struct Pipeline {
blit: Option<msaa::Blit>,
// these are optional so we don't allocate any memory to the GPU if
// application has no triangle meshes.
vertex_buffer: Option<StaticBuffer>,
index_buffer: Option<StaticBuffer>,
pipelines: TrianglePipelines,
}
/// Supported triangle pipelines for different fills. Both use the same vertex shader.
pub(crate) struct TrianglePipelines {
solid: SolidPipeline,
gradient: GradientPipeline,
}
impl fmt::Debug for TrianglePipelines {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("TrianglePipelines").finish()
}
}
impl TrianglePipelines {
/// Resets each pipeline's buffers.
fn clear(&mut self) {
self.solid.buffer.clear();
self.gradient.uniform_buffer.clear();
self.gradient.storage_buffer.clear();
}
/// Writes the contents of each pipeline's CPU buffer to the GPU, resizing the GPU buffer
/// beforehand if necessary.
fn write(
&mut self,
device: &wgpu::Device,
staging_belt: &mut wgpu::util::StagingBelt,
encoder: &mut wgpu::CommandEncoder,
) {
self.solid.write(device, staging_belt, encoder);
self.gradient.write(device, staging_belt, encoder);
}
}
impl Pipeline {
/// Creates supported GL programs, listed in [TrianglePipelines].
pub fn new(
device: &wgpu::Device,
format: wgpu::TextureFormat,
antialiasing: Option<settings::Antialiasing>,
) -> Pipeline {
Pipeline {
blit: antialiasing.map(|a| msaa::Blit::new(device, format, a)),
vertex_buffer: None,
index_buffer: None,
pipelines: TrianglePipelines {
solid: SolidPipeline::new(device, format, antialiasing),
gradient: GradientPipeline::new(device, format, antialiasing),
},
}
}
/// Draws the contents of the current layer's meshes to the [target].
pub fn draw(
&mut self,
device: &wgpu::Device,
staging_belt: &mut wgpu::util::StagingBelt,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
target_size: Size<u32>,
transformation: Transformation,
scale_factor: f32,
meshes: &Meshes<'_>,
) {
//count the total number of vertices & indices we need to handle
let (total_vertices, total_indices) = meshes.attribute_count();
println!("total vertices: {}, total indices: {}", total_vertices, total_indices);
//Only create buffers if they need to be re-sized or don't exist
if needs_recreate(&self.vertex_buffer, total_vertices) {
//mapped to GPU at creation with total vertices
self.vertex_buffer = Some(StaticBuffer::new(
device,
"iced_wgpu::triangle vertex buffer",
//TODO: a more reasonable default to prevent frequent resizing calls
// before this was 10_000
(std::mem::size_of::<Vertex2D>() * total_vertices) as u64,
wgpu::BufferUsages::VERTEX,
meshes.0.len(),
))
}
if needs_recreate(&self.index_buffer, total_indices) {
//mapped to GPU at creation with total indices
self.index_buffer = Some(StaticBuffer::new(
device,
"iced_wgpu::triangle index buffer",
//TODO: a more reasonable default to prevent frequent resizing calls
// before this was 10_000
(std::mem::size_of::<Vertex2D>() * total_indices) as u64,
wgpu::BufferUsages::INDEX,
meshes.0.len(),
));
}
if let Some(vertex_buffer) = &mut self.vertex_buffer {
if let Some(index_buffer) = &mut self.index_buffer {
let mut offset_v = 0;
let mut offset_i = 0;
//TODO: store this more efficiently
let mut indices_lengths = Vec::with_capacity(meshes.0.len());
//iterate through meshes to write all attribute data
for mesh in meshes.0.iter() {
let transform = transformation
* Transformation::translate(
mesh.origin.x,
mesh.origin.y,
);
println!("Mesh attribute data: Vertex: {:?}, Index: {:?}", mesh.buffers.vertices, mesh.buffers.indices);
let vertices = bytemuck::cast_slice(&mesh.buffers.vertices);
let indices = bytemuck::cast_slice(&mesh.buffers.indices);
//TODO: it's (probably) more efficient to reduce this write command and
// iterate first and then upload
println!("vertex buffer len: {}, index length: {}", vertices.len(), indices.len());
vertex_buffer.write(offset_v, vertices);
index_buffer.write(offset_i, indices);
offset_v += vertices.len() as u64;
offset_i += indices.len() as u64;
indices_lengths.push(mesh.buffers.indices.len());
match mesh.shader {
Shader::Solid(color) => {
self.pipelines.solid.push(transform, color);
}
Shader::Gradient(gradient) => {
self.pipelines.gradient.push(transform, gradient);
}
}
}
//done writing to gpu buffer, unmap from host memory since we don't need it
//anymore
vertex_buffer.flush();
index_buffer.flush();
//resize & memcpy uniforms from CPU buffers to GPU buffers for all pipelines
self.pipelines.write(device, staging_belt, encoder);
//configure the render pass now that the data is uploaded to the GPU
{
//configure antialiasing pass
let (attachment, resolve_target, load) =
if let Some(blit) = &mut self.blit {
let (attachment, resolve_target) = blit.targets(
device,
target_size.width,
target_size.height,
);
(
attachment,
Some(resolve_target),
wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
)
} else {
(target, None, wgpu::LoadOp::Load)
};
let mut render_pass = encoder.begin_render_pass(
&wgpu::RenderPassDescriptor {
label: Some("iced_wgpu::triangle render pass"),
color_attachments: &[Some(
wgpu::RenderPassColorAttachment {
view: attachment,
resolve_target,
ops: wgpu::Operations { load, store: true },
},
)],
depth_stencil_attachment: None,
},
);
//TODO: do this a better way; store it in the respective pipelines perhaps
// to be more readable
let mut num_solids = 0;
let mut num_gradients = 0;
//TODO: try to avoid this extra iteration if possible
for index in 0..meshes.0.len() {
let clip_bounds =
(meshes.0[index].clip_bounds * scale_factor).snap();
render_pass.set_scissor_rect(
clip_bounds.x,
clip_bounds.y,
clip_bounds.width,
clip_bounds.height,
);
match meshes.0[index].shader {
Shader::Solid(_) => {
self.pipelines.solid.configure_render_pass(
&mut render_pass,
num_solids,
);
num_solids += 1;
}
Shader::Gradient(_) => {
self.pipelines.gradient.configure_render_pass(
&mut render_pass,
num_gradients,
);
num_gradients += 1;
}
}
render_pass.set_index_buffer(
index_buffer.slice_from_index::<u32>(index),
wgpu::IndexFormat::Uint32,
);
render_pass.set_vertex_buffer(
0,
vertex_buffer.slice_from_index::<Vertex2D>(index),
);
render_pass.draw_indexed(
0..(indices_lengths[index] as u32),
0,
0..1,
);
}
}
}
}
if let Some(blit) = &mut self.blit {
blit.draw(encoder, target);
}
//cleanup
self.pipelines.clear();
}
}
//utility functions for individual pipelines with shared functionality
fn vertex_buffer_layout<'a>() -> wgpu::VertexBufferLayout<'a> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<Vertex2D>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &[wgpu::VertexAttribute {
format: wgpu::VertexFormat::Float32x2,
offset: 0,
shader_location: 0,
}],
}
}
fn default_fragment_target(
texture_format: wgpu::TextureFormat,
) -> Option<wgpu::ColorTargetState> {
Some(wgpu::ColorTargetState {
format: texture_format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})
}
fn default_triangle_primitive_state() -> wgpu::PrimitiveState {
wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList,
front_face: wgpu::FrontFace::Cw,
..Default::default()
}
}
fn default_multisample_state(
antialiasing: Option<settings::Antialiasing>,
) -> wgpu::MultisampleState {
wgpu::MultisampleState {
count: antialiasing.map(|a| a.sample_count()).unwrap_or(1),
mask: !0,
alpha_to_coverage_enabled: false,
}
}
|