forked from linebender/vello
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.rs
More file actions
377 lines (348 loc) · 14.2 KB
/
Copy pathrender.rs
File metadata and controls
377 lines (348 loc) · 14.2 KB
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
// Copyright 2025 the Vello Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! GPU rendering module for the sparse strips CPU/GPU rendering engine.
//!
//! This module provides the GPU-side implementation of the hybrid rendering system.
//! It handles:
//! - GPU resource management (buffers, textures, pipelines)
//! - Surface/window management and presentation
//! - Shader execution and rendering
//!
//! The hybrid approach combines CPU-side path processing with efficient GPU rendering
//! to balance flexibility and performance.
use std::fmt::Debug;
use bytemuck::{Pod, Zeroable};
use vello_common::tile::Tile;
use wgpu::{
BindGroup, BindGroupLayout, BlendState, Buffer, ColorTargetState, ColorWrites, Device,
PipelineCompilationOptions, Queue, RenderPass, RenderPipeline, Texture, util::DeviceExt,
};
use crate::scene::Scene;
/// Parameters for the renderer
#[derive(Debug)]
pub struct RenderParams {
/// Width of the rendering target
pub width: u32,
/// Height of the rendering target
pub height: u32,
}
/// Options for the renderer
#[derive(Debug)]
pub struct RendererOptions {}
/// Contains all GPU resources needed for rendering
#[derive(Debug)]
struct GpuResources {
/// Buffer for strip data
pub strips_buffer: Buffer,
/// Texture for alpha values
pub alphas_texture: Texture,
/// Bind group for rendering
pub render_bind_group: BindGroup,
}
/// GPU renderer for the hybrid rendering system
#[derive(Debug)]
pub struct Renderer {
/// Bind group layout for rendering
pub render_bind_group_layout: BindGroupLayout,
/// Pipeline for rendering
pub render_pipeline: RenderPipeline,
/// GPU resources for rendering (created during prepare)
resources: Option<GpuResources>,
}
/// Contains the data needed for rendering
#[derive(Debug, Default)]
pub struct RenderData {
/// GPU strips to be rendered
pub strips: Vec<GpuStrip>,
/// Alpha values used in rendering
pub alphas: Vec<u32>,
}
/// Configuration for the GPU renderer
#[repr(C)]
#[derive(Debug, Copy, Clone, Pod, Zeroable)]
pub struct Config {
/// Width of the rendering target
pub width: u32,
/// Height of the rendering target
pub height: u32,
/// Height of a strip in the rendering
pub strip_height: u32,
}
/// Represents a GPU strip for rendering
#[repr(C)]
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
pub struct GpuStrip {
/// X coordinate of the strip
pub x: u16,
/// Y coordinate of the strip
pub y: u16,
/// Width of the strip
pub width: u16,
/// Width of the portion where alpha blending should be applied.
pub dense_width: u16,
/// Index into the alpha texture where this strip's alpha values begin.
pub col: u32,
/// RGBA color value
pub rgba: u32,
}
impl GpuStrip {
/// Vertex attributes for the strip
pub fn vertex_attributes() -> [wgpu::VertexAttribute; 4] {
wgpu::vertex_attr_array![
0 => Uint32,
1 => Uint32,
2 => Uint32,
3 => Uint32,
]
}
}
impl Renderer {
/// Creates a new renderer
///
/// The target parameter determines if we render to a window or headless
pub fn new(device: &Device, _options: &RendererOptions) -> Self {
let format = wgpu::TextureFormat::Bgra8Unorm;
let render_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: None,
source: wgpu::ShaderSource::Wgsl(
include_str!("../shaders/sparse_strip_renderer.wgsl").into(),
),
});
let render_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Uint,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[&render_bind_group_layout],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: None,
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &render_shader,
entry_point: Some("vs_main"),
buffers: &[wgpu::VertexBufferLayout {
array_stride: size_of::<GpuStrip>() as u64,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &GpuStrip::vertex_attributes(),
}],
compilation_options: PipelineCompilationOptions::default(),
},
fragment: Some(wgpu::FragmentState {
module: &render_shader,
entry_point: Some("fs_main"),
targets: &[Some(ColorTargetState {
format,
blend: Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING),
write_mask: ColorWrites::ALL,
})],
compilation_options: PipelineCompilationOptions::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleStrip,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
cache: None,
});
Self {
render_bind_group_layout,
render_pipeline,
resources: None,
}
}
/// Prepare the GPU buffers for rendering
pub fn prepare(
&mut self,
device: &Device,
queue: &Queue,
scene: &Scene,
render_params: &RenderParams,
) {
let render_data = scene.prepare_render_data();
let required_strips_size = size_of::<GpuStrip>() as u64 * render_data.strips.len() as u64;
let (needs_new_strips_buffer, needs_new_alpha_texture) = match &self.resources {
Some(resources) => {
let strips_too_small = required_strips_size > resources.strips_buffer.size();
let max_texture_dimension_2d = device.limits().max_texture_dimension_2d;
let alpha_len = render_data.alphas.len();
// 4 alpha values u32 each per texel
let required_alpha_height =
(u32::try_from(alpha_len).unwrap()).div_ceil(max_texture_dimension_2d * 4);
let required_alpha_size = max_texture_dimension_2d * required_alpha_height * 4;
let current_alpha_size =
resources.alphas_texture.width() * resources.alphas_texture.height() * 4;
let alpha_too_small = required_alpha_size > current_alpha_size;
(strips_too_small, alpha_too_small)
}
None => (true, true),
};
if needs_new_strips_buffer || needs_new_alpha_texture {
let strips_buffer = if needs_new_strips_buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Strips Buffer"),
size: required_strips_size,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
} else {
// Reuse existing buffer if it's big enough
self.resources
.as_ref()
.expect("Strips buffer not found")
.strips_buffer
.clone()
};
let (alphas_texture, render_bind_group) = if needs_new_alpha_texture {
let max_texture_dimension_2d = device.limits().max_texture_dimension_2d;
let alpha_len = render_data.alphas.len();
// 4 alpha values u32 each per texel
let alpha_texture_height =
(u32::try_from(alpha_len).unwrap()).div_ceil(max_texture_dimension_2d * 4);
// Ensure dimensions don't exceed WebGL2 limits
assert!(
alpha_texture_height <= max_texture_dimension_2d,
"Alpha texture height exceeds WebGL2 limit"
);
let alphas_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Alpha Texture"),
size: wgpu::Extent3d {
width: max_texture_dimension_2d,
height: alpha_texture_height,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Uint,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let alphas_texture_view =
alphas_texture.create_view(&wgpu::TextureViewDescriptor::default());
let config_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Config Buffer"),
contents: bytemuck::bytes_of(&Config {
width: render_params.width,
height: render_params.height,
strip_height: Tile::HEIGHT.into(),
}),
usage: wgpu::BufferUsages::UNIFORM,
});
let render_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Render Bind Group"),
layout: &self.render_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&alphas_texture_view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: config_buf.as_entire_binding(),
},
],
});
(alphas_texture, render_bind_group)
} else {
let resources = self.resources.as_ref().unwrap();
(
resources.alphas_texture.clone(),
resources.render_bind_group.clone(),
)
};
self.resources = Some(GpuResources {
strips_buffer,
alphas_texture,
render_bind_group,
});
};
// Now that we have resources, we can update the data
if let Some(resources) = &self.resources {
// TODO: Explore using `write_buffer_with` to avoid copying the data twice
queue.write_buffer(
&resources.strips_buffer,
0,
bytemuck::cast_slice(&render_data.strips),
);
// Prepare alpha data for the texture with 4 alpha values per texel
let texture_width = resources.alphas_texture.width();
let texture_height = resources.alphas_texture.height();
assert!(
render_data.alphas.len() <= (texture_width * texture_height * 4) as usize,
"Alpha texture dimensions are too small to fit the alpha data"
);
let mut alpha_data = vec![0_u32; render_data.alphas.len()];
alpha_data[..].copy_from_slice(&render_data.alphas);
alpha_data.resize((texture_width * texture_height * 4) as usize, 0);
queue.write_texture(
wgpu::TexelCopyTextureInfo {
texture: &resources.alphas_texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
bytemuck::cast_slice(&alpha_data),
wgpu::TexelCopyBufferLayout {
offset: 0,
// 16 bytes per RGBA32Uint texel (4 u32s × 4 bytes each)
bytes_per_row: Some(texture_width * 16),
rows_per_image: Some(texture_height),
},
wgpu::Extent3d {
width: texture_width,
height: texture_height,
depth_or_array_layers: 1,
},
);
}
}
/// Render `scene` into the provided render pass.
///
/// You must call [`prepare`](Self::prepare) with this scene before
/// calling `render`.
/// The provided pass can be rendering to a surface, or to a "off-screen" buffer.
pub fn render(
&mut self,
scene: &Scene,
render_pass: &mut RenderPass<'_>,
_render_params: &RenderParams,
) {
// If we don't have the required resources, return empty data
let Some(resources) = &self.resources else {
return;
};
let render_data = scene.prepare_render_data();
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &resources.render_bind_group, &[]);
render_pass.set_vertex_buffer(0, resources.strips_buffer.slice(..));
let strips_to_draw = render_data.strips.len();
render_pass.draw(0..4, 0..u32::try_from(strips_to_draw).unwrap());
}
}