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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
use {
super::{
DescriptorBindingMap, Device, DriverError, PipelineDescriptorInfo, SampleCount, Shader,
SpecializationInfo,
},
crate::graph::AttachmentIndex,
archery::{SharedPointer, SharedPointerKind},
ash::vk,
derive_builder::Builder,
log::{trace, warn},
ordered_float::OrderedFloat,
std::{cmp::Ordering, collections::HashSet, ffi::CString, thread::panicking},
};
const RGBA_COLOR_COMPONENTS: vk::ColorComponentFlags = vk::ColorComponentFlags::from_raw(
vk::ColorComponentFlags::R.as_raw()
| vk::ColorComponentFlags::G.as_raw()
| vk::ColorComponentFlags::B.as_raw()
| vk::ColorComponentFlags::A.as_raw(),
);
#[derive(Builder, Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[builder(
build_fn(private, name = "fallible_build"),
derive(Debug),
pattern = "owned"
)]
pub struct BlendMode {
#[builder(default = "false")]
pub blend_enable: bool,
#[builder(default = "vk::BlendFactor::SRC_COLOR")]
pub src_color_blend_factor: vk::BlendFactor,
#[builder(default = "vk::BlendFactor::ONE_MINUS_DST_COLOR")]
pub dst_color_blend_factor: vk::BlendFactor,
#[builder(default = "vk::BlendOp::ADD")]
pub color_blend_op: vk::BlendOp,
#[builder(default = "vk::BlendFactor::ZERO")]
pub src_alpha_blend_factor: vk::BlendFactor,
#[builder(default = "vk::BlendFactor::ZERO")]
pub dst_alpha_blend_factor: vk::BlendFactor,
#[builder(default = "vk::BlendOp::ADD")]
pub alpha_blend_op: vk::BlendOp,
#[builder(default = "RGBA_COLOR_COMPONENTS")]
pub color_write_mask: vk::ColorComponentFlags,
}
impl BlendModeBuilder {
pub fn build(self) -> BlendMode {
self.fallible_build().unwrap()
}
}
impl BlendMode {
#[allow(non_upper_case_globals)]
#[deprecated = "use uppercase const"]
pub const Replace: Self = Self::REPLACE;
#[allow(non_upper_case_globals)]
#[deprecated = "use uppercase const"]
pub const Alpha: Self = Self::ALPHA;
#[allow(non_upper_case_globals)]
#[deprecated = "use uppercase const"]
pub const PreMultipliedAlpha: Self = Self::PRE_MULTIPLIED_ALPHA;
pub const REPLACE: Self = Self {
blend_enable: false,
src_color_blend_factor: vk::BlendFactor::SRC_COLOR,
dst_color_blend_factor: vk::BlendFactor::ONE_MINUS_DST_COLOR,
color_blend_op: vk::BlendOp::ADD,
src_alpha_blend_factor: vk::BlendFactor::ZERO,
dst_alpha_blend_factor: vk::BlendFactor::ZERO,
alpha_blend_op: vk::BlendOp::ADD,
color_write_mask: RGBA_COLOR_COMPONENTS,
};
pub const ALPHA: Self = Self {
blend_enable: true,
src_color_blend_factor: vk::BlendFactor::SRC_ALPHA,
dst_color_blend_factor: vk::BlendFactor::ONE_MINUS_SRC_ALPHA,
color_blend_op: vk::BlendOp::ADD,
src_alpha_blend_factor: vk::BlendFactor::SRC_ALPHA,
dst_alpha_blend_factor: vk::BlendFactor::ONE_MINUS_SRC_ALPHA,
alpha_blend_op: vk::BlendOp::ADD,
color_write_mask: RGBA_COLOR_COMPONENTS,
};
pub const PRE_MULTIPLIED_ALPHA: Self = Self {
blend_enable: true,
src_color_blend_factor: vk::BlendFactor::SRC_ALPHA,
dst_color_blend_factor: vk::BlendFactor::ONE_MINUS_SRC_ALPHA,
color_blend_op: vk::BlendOp::ADD,
src_alpha_blend_factor: vk::BlendFactor::ONE,
dst_alpha_blend_factor: vk::BlendFactor::ONE,
alpha_blend_op: vk::BlendOp::ADD,
color_write_mask: RGBA_COLOR_COMPONENTS,
};
#[allow(clippy::new_ret_no_self)]
pub fn new() -> BlendModeBuilder {
BlendModeBuilder::default()
}
pub fn into_vk(&self) -> vk::PipelineColorBlendAttachmentState {
vk::PipelineColorBlendAttachmentState {
blend_enable: if self.blend_enable {
vk::TRUE
} else {
vk::FALSE
},
src_color_blend_factor: self.src_color_blend_factor,
dst_color_blend_factor: self.dst_color_blend_factor,
color_blend_op: self.color_blend_op,
src_alpha_blend_factor: self.src_alpha_blend_factor,
dst_alpha_blend_factor: self.dst_alpha_blend_factor,
alpha_blend_op: self.alpha_blend_op,
color_write_mask: self.color_write_mask,
}
}
}
impl Default for BlendMode {
fn default() -> Self {
Self::REPLACE
}
}
#[derive(Builder, Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[builder(
build_fn(private, name = "fallible_build"),
derive(Debug),
pattern = "owned"
)]
pub struct DepthStencilMode {
pub back: StencilMode,
pub bounds_test: bool,
pub compare_op: vk::CompareOp,
pub depth_test: bool,
pub depth_write: bool,
pub front: StencilMode,
pub min: OrderedFloat<f32>,
pub max: OrderedFloat<f32>,
pub stencil_test: bool,
}
impl DepthStencilMode {
#[allow(clippy::new_ret_no_self)]
pub fn new() -> DepthStencilModeBuilder {
DepthStencilModeBuilder::default()
}
pub(super) fn into_vk(self) -> vk::PipelineDepthStencilStateCreateInfo {
vk::PipelineDepthStencilStateCreateInfo {
back: self.back.into_vk(),
depth_bounds_test_enable: self.bounds_test as _,
depth_compare_op: self.compare_op,
depth_test_enable: self.depth_test as _,
depth_write_enable: self.depth_write as _,
front: self.front.into_vk(),
max_depth_bounds: *self.max,
min_depth_bounds: *self.min,
stencil_test_enable: self.stencil_test as _,
..Default::default()
}
}
}
impl DepthStencilModeBuilder {
pub fn build(mut self) -> DepthStencilMode {
if self.back.is_none() {
self.back = Some(Default::default());
}
if self.bounds_test.is_none() {
self.bounds_test = Some(Default::default());
}
if self.compare_op.is_none() {
self.compare_op = Some(Default::default());
}
if self.depth_test.is_none() {
self.depth_test = Some(Default::default());
}
if self.depth_write.is_none() {
self.depth_write = Some(Default::default());
}
if self.front.is_none() {
self.front = Some(Default::default());
}
if self.min.is_none() {
self.min = Some(Default::default());
}
if self.max.is_none() {
self.max = Some(Default::default());
}
if self.stencil_test.is_none() {
self.stencil_test = Some(Default::default());
}
self.fallible_build()
.expect("All required fields set at initialization")
}
}
#[derive(Debug)]
pub struct GraphicPipeline<P>
where
P: SharedPointerKind,
{
pub descriptor_bindings: DescriptorBindingMap,
pub descriptor_info: PipelineDescriptorInfo<P>,
device: SharedPointer<Device<P>, P>,
pub info: GraphicPipelineInfo,
pub input_attachments: HashSet<AttachmentIndex>,
pub layout: vk::PipelineLayout,
pub push_constants: Vec<vk::PushConstantRange>,
shader_modules: Vec<vk::ShaderModule>,
stage_flags: vk::ShaderStageFlags,
pub state: GraphicPipelineState,
pub write_attachments: HashSet<AttachmentIndex>,
}
impl<P> GraphicPipeline<P>
where
P: SharedPointerKind,
{
pub fn create<S>(
device: &SharedPointer<Device<P>, P>,
info: impl Into<GraphicPipelineInfo>,
shaders: impl IntoIterator<Item = S>,
) -> Result<Self, DriverError>
where
S: Into<Shader>,
{
trace!("create");
let device = SharedPointer::clone(device);
let info = info.into();
let shaders = shaders
.into_iter()
.map(|shader| shader.into())
.collect::<Vec<Shader>>();
let vertex_input = shaders
.iter()
.find(|shader| shader.stage == vk::ShaderStageFlags::VERTEX)
.expect("vertex shader not found")
.vertex_input();
let has_fragment_stage = shaders
.iter()
.any(|shader| shader.stage.contains(vk::ShaderStageFlags::FRAGMENT));
let has_tesselation_stage = shaders.iter().any(|shader| {
shader
.stage
.contains(vk::ShaderStageFlags::TESSELLATION_CONTROL)
}) && shaders.iter().any(|shader| {
shader
.stage
.contains(vk::ShaderStageFlags::TESSELLATION_EVALUATION)
});
let has_geometry_stage = shaders
.iter()
.any(|shader| shader.stage.contains(vk::ShaderStageFlags::GEOMETRY));
debug_assert!(
has_fragment_stage || has_tesselation_stage || has_geometry_stage,
"invalid shader stage combination"
);
let mut descriptor_bindings = Shader::merge_descriptor_bindings(
shaders
.iter()
.map(|shader| shader.descriptor_bindings(&device)),
);
for (descriptor_info, _) in descriptor_bindings.values_mut() {
if descriptor_info.binding_count() == 0 {
descriptor_info.set_binding_count(info.bindless_descriptor_count);
}
}
let descriptor_info = PipelineDescriptorInfo::create(&device, &descriptor_bindings)?;
let descriptor_sets_layouts = descriptor_info
.layouts
.iter()
.map(|(_, descriptor_set_layout)| **descriptor_set_layout)
.collect::<Box<[_]>>();
let mut push_constants = shaders
.iter()
.map(|shader| shader.push_constant_range())
.filter_map(|mut push_const| push_const.take())
.collect::<Vec<_>>();
let (input_attachments, write_attachments) = {
let (input, write) = shaders
.iter()
.find(|shader| shader.stage == vk::ShaderStageFlags::FRAGMENT)
.expect("fragment shader not found")
.attachments();
let (input, write) = (input.collect(), write.collect());
for input in &input {
trace!("detected input attachment {input}");
}
for write in &write {
trace!("detected write attachment {write}");
}
(input, write)
};
unsafe {
let layout = device
.create_pipeline_layout(
&vk::PipelineLayoutCreateInfo::builder()
.set_layouts(&descriptor_sets_layouts)
.push_constant_ranges(&push_constants),
None,
)
.map_err(|err| {
warn!("{err}");
DriverError::Unsupported
})?;
let shader_info = shaders
.into_iter()
.map(|shader| {
let shader_module_create_info = vk::ShaderModuleCreateInfo {
code_size: shader.spirv.len(),
p_code: shader.spirv.as_ptr() as *const u32,
..Default::default()
};
let shader_module = device
.create_shader_module(&shader_module_create_info, None)
.map_err(|err| {
warn!("{err}");
DriverError::Unsupported
})?;
let shader_stage = Stage {
flags: shader.stage,
module: shader_module,
name: CString::new(shader.entry_name.as_str()).unwrap(),
specialization_info: shader.specialization_info,
};
Result::<_, DriverError>::Ok((shader_module, shader_stage))
})
.collect::<Result<Vec<_>, _>>()?;
let mut shader_modules = vec![];
let mut stages = vec![];
shader_info
.into_iter()
.for_each(|(shader_module, shader_stage)| {
shader_modules.push(shader_module);
stages.push(shader_stage);
});
let rasterization = RasterizationState {
two_sided: info.two_sided,
};
let multisample = MultisampleState {
rasterization_samples: info.samples,
..Default::default()
};
let stage_flags = stages
.iter()
.map(|stage| stage.flags)
.reduce(|j, k| j | k)
.unwrap_or_default();
if push_constants.len() > 1 {
push_constants.sort_unstable_by(|lhs, rhs| match lhs.offset.cmp(&rhs.offset) {
Ordering::Equal => lhs.size.cmp(&rhs.size),
res => res,
});
let mut idx = 0;
while idx + 1 < push_constants.len() {
let curr = push_constants[idx];
let next = push_constants[idx + 1];
let curr_end = curr.offset + curr.size;
if curr_end > next.offset {
push_constants[idx].stage_flags |= next.stage_flags;
idx += 1;
push_constants[idx].offset = curr_end;
push_constants[idx].size -= curr_end - next.offset;
}
idx += 1;
}
for pcr in &push_constants {
trace!(
"effective push constants: {:?} {}..{}",
pcr.stage_flags,
pcr.offset,
pcr.offset + pcr.size
);
}
} else {
for pcr in &push_constants {
trace!(
"detected push constants: {:?} {}..{}",
pcr.stage_flags,
pcr.offset,
pcr.offset + pcr.size
);
}
}
Ok(Self {
descriptor_bindings,
descriptor_info,
device,
info,
input_attachments,
layout,
push_constants,
shader_modules,
stage_flags,
state: GraphicPipelineState {
layout,
multisample,
rasterization,
stages,
vertex_input,
},
write_attachments,
})
}
}
pub fn stages(&self) -> vk::ShaderStageFlags {
self.stage_flags
}
}
impl<P> Drop for GraphicPipeline<P>
where
P: SharedPointerKind,
{
fn drop(&mut self) {
if panicking() {
return;
}
unsafe {
self.device.destroy_pipeline_layout(self.layout, None);
}
for shader_module in self.shader_modules.drain(..) {
unsafe {
self.device.destroy_shader_module(shader_module, None);
}
}
}
}
#[derive(Builder, Clone, Debug, Eq, Hash, PartialEq)]
#[builder(
build_fn(private, name = "fallible_build"),
derive(Clone, Debug),
pattern = "owned"
)]
pub struct GraphicPipelineInfo {
#[builder(default)]
pub blend: BlendMode,
#[builder(default = "8192")]
pub bindless_descriptor_count: u32,
#[builder(default = "vk::CullModeFlags::BACK")]
pub cull_mode: vk::CullModeFlags,
#[builder(default, setter(strip_option))]
pub depth_stencil: Option<DepthStencilMode>,
#[builder(default = "vk::FrontFace::COUNTER_CLOCKWISE")]
pub front_face: vk::FrontFace,
#[builder(default, setter(strip_option))]
pub name: Option<String>,
#[builder(default = "vk::PolygonMode::FILL")]
pub polygon_mode: vk::PolygonMode,
#[builder(default = "SampleCount::X1")]
pub samples: SampleCount,
#[builder(default)]
pub two_sided: bool,
}
impl GraphicPipelineInfo {
#[allow(clippy::new_ret_no_self)]
pub fn new() -> GraphicPipelineInfoBuilder {
GraphicPipelineInfoBuilder::default()
}
}
impl GraphicPipelineInfoBuilder {
pub fn build(self) -> GraphicPipelineInfo {
self.fallible_build()
.expect("All required fields set at initialization")
}
}
impl Default for GraphicPipelineInfo {
fn default() -> Self {
Self::new().build()
}
}
impl From<GraphicPipelineInfoBuilder> for GraphicPipelineInfo {
fn from(info: GraphicPipelineInfoBuilder) -> Self {
info.build()
}
}
#[derive(Debug)]
pub struct GraphicPipelineState {
pub layout: vk::PipelineLayout,
pub multisample: MultisampleState,
pub rasterization: RasterizationState,
pub stages: Vec<Stage>,
pub vertex_input: VertexInputState,
}
#[derive(Debug, Default)]
pub struct MultisampleState {
pub alpha_to_coverage_enable: bool,
pub alpha_to_one_enable: bool,
pub flags: vk::PipelineMultisampleStateCreateFlags,
pub min_sample_shading: f32,
pub rasterization_samples: SampleCount,
pub sample_mask: Vec<u32>,
pub sample_shading_enable: bool,
}
#[derive(Debug, Default)]
pub struct RasterizationState {
pub two_sided: bool,
}
#[derive(Debug)]
pub struct Stage {
pub flags: vk::ShaderStageFlags,
pub module: vk::ShaderModule,
pub name: CString,
pub specialization_info: Option<SpecializationInfo>,
}
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum StencilMode {
Noop,
}
impl StencilMode {
fn into_vk(self) -> vk::StencilOpState {
match self {
Self::Noop => vk::StencilOpState {
fail_op: vk::StencilOp::KEEP,
pass_op: vk::StencilOp::KEEP,
depth_fail_op: vk::StencilOp::KEEP,
compare_op: vk::CompareOp::ALWAYS,
..Default::default()
},
}
}
}
impl Default for StencilMode {
fn default() -> Self {
Self::Noop
}
}
#[derive(Debug, Default)]
pub struct VertexInputState {
pub vertex_binding_descriptions: Vec<vk::VertexInputBindingDescription>,
pub vertex_attribute_descriptions: Vec<vk::VertexInputAttributeDescription>,
}