1use crate::{
2 assets::{handle::Handle, storage::Assets, upload::Asset},
3 wgpu::{
4 backend::WGPUBackend,
5 binding::{BindGroupLayout, BindGroupLayoutBuilder, BindingEntry},
6 flags::ShaderStages,
7 texture_format::TextureFormat,
8 vertex_format::VertexBufferLayout,
9 },
10};
11
12pub struct RenderPipeline(wgpu::RenderPipeline);
19
20impl RenderPipeline {
21 pub(crate) fn raw(&self) -> &wgpu::RenderPipeline {
22 &self.0
23 }
24}
25
26#[derive(Copy, Clone, PartialEq, Eq, Hash)]
28pub enum Face {
29 Front,
30 Back,
31}
32
33impl From<Face> for wgpu::Face {
34 fn from(value: Face) -> Self {
35 match value {
36 Face::Front => Self::Front,
37 Face::Back => Self::Back,
38 }
39 }
40}
41
42#[derive(Copy, Clone, PartialEq, Eq, Hash)]
44pub enum PolygonMode {
45 Fill,
46 Line,
47 Point,
48}
49
50impl From<PolygonMode> for wgpu::PolygonMode {
51 fn from(value: PolygonMode) -> Self {
52 match value {
53 PolygonMode::Fill => Self::Fill,
54 PolygonMode::Line => Self::Line,
55 PolygonMode::Point => Self::Point,
56 }
57 }
58}
59
60#[derive(Copy, Clone, PartialEq, Eq, Hash)]
62pub enum BlendFactor {
63 Zero,
64 One,
65 Src,
66 OneMinusSrc,
67 SrcAlpha,
68 OneMinusSrcAlpha,
69 Dst,
70 OneMinusDst,
71 DstAlpha,
72 OneMinusDstAlpha,
73 SrcAlphaSaturated,
74 Constant,
75 OneMinusConstant,
76 Src1,
77 OneMinusSrc1,
78 Src1Alpha,
79 OneMinusSrc1Alpha,
80}
81
82impl From<BlendFactor> for wgpu::BlendFactor {
83 fn from(value: BlendFactor) -> Self {
84 match value {
85 BlendFactor::Zero => Self::Zero,
86 BlendFactor::One => Self::One,
87 BlendFactor::Src => Self::Src,
88 BlendFactor::OneMinusSrc => Self::OneMinusSrc,
89 BlendFactor::SrcAlpha => Self::SrcAlpha,
90 BlendFactor::OneMinusSrcAlpha => Self::OneMinusSrcAlpha,
91 BlendFactor::Dst => Self::Dst,
92 BlendFactor::OneMinusDst => Self::OneMinusDst,
93 BlendFactor::DstAlpha => Self::DstAlpha,
94 BlendFactor::OneMinusDstAlpha => Self::OneMinusDstAlpha,
95 BlendFactor::SrcAlphaSaturated => Self::SrcAlphaSaturated,
96 BlendFactor::Constant => Self::Constant,
97 BlendFactor::OneMinusConstant => Self::OneMinusConstant,
98 BlendFactor::Src1 => Self::Src1,
99 BlendFactor::OneMinusSrc1 => Self::OneMinusSrc1,
100 BlendFactor::Src1Alpha => Self::Src1Alpha,
101 BlendFactor::OneMinusSrc1Alpha => Self::OneMinusSrc1Alpha,
102 }
103 }
104}
105
106#[derive(Copy, Clone, PartialEq, Eq, Hash)]
108pub enum BlendOperation {
109 Add,
110 Subtract,
111 ReverseSubtract,
112 Min,
113 Max,
114}
115
116impl From<BlendOperation> for wgpu::BlendOperation {
117 fn from(value: BlendOperation) -> Self {
118 match value {
119 BlendOperation::Add => Self::Add,
120 BlendOperation::Subtract => Self::Subtract,
121 BlendOperation::ReverseSubtract => Self::ReverseSubtract,
122 BlendOperation::Min => Self::Min,
123 BlendOperation::Max => Self::Max,
124 }
125 }
126}
127
128#[derive(Copy, Clone, PartialEq, Eq, Hash)]
130pub struct BlendComponent {
131 pub src_factor: BlendFactor,
132 pub dst_factor: BlendFactor,
133 pub operation: BlendOperation,
134}
135
136impl BlendComponent {
137 pub const REPLACE: Self = Self {
139 src_factor: BlendFactor::One,
140 dst_factor: BlendFactor::Zero,
141 operation: BlendOperation::Add,
142 };
143
144 pub const OVER: Self = Self {
146 src_factor: BlendFactor::One,
147 dst_factor: BlendFactor::OneMinusSrcAlpha,
148 operation: BlendOperation::Add,
149 };
150}
151
152impl From<BlendComponent> for wgpu::BlendComponent {
153 fn from(value: BlendComponent) -> Self {
154 Self {
155 src_factor: value.src_factor.into(),
156 dst_factor: value.dst_factor.into(),
157 operation: value.operation.into(),
158 }
159 }
160}
161
162#[derive(Copy, Clone, PartialEq, Eq, Hash)]
164pub struct BlendState {
165 pub color: BlendComponent,
166 pub alpha: BlendComponent,
167}
168
169impl BlendState {
170 pub const REPLACE: Self = Self { color: BlendComponent::REPLACE, alpha: BlendComponent::REPLACE };
172
173 pub const ALPHA_BLENDING: Self = Self {
175 color: BlendComponent {
176 src_factor: BlendFactor::SrcAlpha,
177 dst_factor: BlendFactor::OneMinusSrcAlpha,
178 operation: BlendOperation::Add,
179 },
180 alpha: BlendComponent::OVER,
181 };
182
183 pub const PREMULTIPLIED_ALPHA_BLENDING: Self =
185 Self { color: BlendComponent::OVER, alpha: BlendComponent::OVER };
186}
187
188impl From<BlendState> for wgpu::BlendState {
189 fn from(value: BlendState) -> Self {
190 Self { color: value.color.into(), alpha: value.alpha.into() }
191 }
192}
193
194#[derive(Clone, PartialEq, Eq, Hash)]
197pub struct ColorTargetState {
198 pub format: TextureFormat,
200 pub blend: Option<BlendState>,
202 pub write_mask: super::flags::ColorWrites,
204}
205
206impl From<ColorTargetState> for wgpu::ColorTargetState {
207 fn from(value: ColorTargetState) -> Self {
208 Self {
209 format: value.format.into(),
210 blend: value.blend.map(Into::into),
211 write_mask: value.write_mask.into(),
212 }
213 }
214}
215
216pub const DEFAULT_TARGET: [ColorTargetState; 1] = [ColorTargetState {
223 format: TextureFormat::Rgba8Unorm,
224 blend: None,
225 write_mask: super::flags::ColorWrites::ALL,
226}];
227
228#[derive(Copy, Clone, PartialEq, Eq, Hash)]
231pub enum CompareFunction {
232 Never,
233 Less,
234 Equal,
235 LessEqual,
236 Greater,
237 NotEqual,
238 GreaterEqual,
239 Always,
240}
241
242impl From<CompareFunction> for wgpu::CompareFunction {
243 fn from(value: CompareFunction) -> Self {
244 match value {
245 CompareFunction::Never => Self::Never,
246 CompareFunction::Less => Self::Less,
247 CompareFunction::Equal => Self::Equal,
248 CompareFunction::LessEqual => Self::LessEqual,
249 CompareFunction::Greater => Self::Greater,
250 CompareFunction::NotEqual => Self::NotEqual,
251 CompareFunction::GreaterEqual => Self::GreaterEqual,
252 CompareFunction::Always => Self::Always,
253 }
254 }
255}
256
257#[derive(Copy, Clone, PartialEq, Eq, Hash)]
259pub enum StencilOperation {
260 Keep,
261 Zero,
262 Replace,
263 Invert,
264 IncrementClamp,
265 DecrementClamp,
266 IncrementWrap,
267 DecrementWrap,
268}
269
270impl From<StencilOperation> for wgpu::StencilOperation {
271 fn from(value: StencilOperation) -> Self {
272 match value {
273 StencilOperation::Keep => Self::Keep,
274 StencilOperation::Zero => Self::Zero,
275 StencilOperation::Replace => Self::Replace,
276 StencilOperation::Invert => Self::Invert,
277 StencilOperation::IncrementClamp => Self::IncrementClamp,
278 StencilOperation::DecrementClamp => Self::DecrementClamp,
279 StencilOperation::IncrementWrap => Self::IncrementWrap,
280 StencilOperation::DecrementWrap => Self::DecrementWrap,
281 }
282 }
283}
284
285#[derive(Copy, Clone, PartialEq, Eq, Hash)]
289pub struct StencilFaceState {
290 pub compare: CompareFunction,
291 pub fail_op: StencilOperation,
292 pub depth_fail_op: StencilOperation,
293 pub pass_op: StencilOperation,
294}
295
296impl StencilFaceState {
297 pub const IGNORE: Self = Self {
298 compare: CompareFunction::Always,
299 fail_op: StencilOperation::Keep,
300 depth_fail_op: StencilOperation::Keep,
301 pass_op: StencilOperation::Keep,
302 };
303}
304
305impl Default for StencilFaceState {
306 fn default() -> Self {
307 Self::IGNORE
308 }
309}
310
311impl From<StencilFaceState> for wgpu::StencilFaceState {
312 fn from(value: StencilFaceState) -> Self {
313 Self {
314 compare: value.compare.into(),
315 fail_op: value.fail_op.into(),
316 depth_fail_op: value.depth_fail_op.into(),
317 pass_op: value.pass_op.into(),
318 }
319 }
320}
321
322#[derive(Copy, Clone, PartialEq, Eq, Hash, Default)]
325pub struct StencilState {
326 pub front: StencilFaceState,
327 pub back: StencilFaceState,
328 pub read_mask: u32,
329 pub write_mask: u32,
330}
331
332impl From<StencilState> for wgpu::StencilState {
333 fn from(value: StencilState) -> Self {
334 Self {
335 front: value.front.into(),
336 back: value.back.into(),
337 read_mask: value.read_mask,
338 write_mask: value.write_mask,
339 }
340 }
341}
342
343#[derive(Copy, Clone, PartialEq, Default)]
346pub struct DepthBiasState {
347 pub constant: i32,
348 pub slope_scale: f32,
349 pub clamp: f32,
350}
351
352impl From<DepthBiasState> for wgpu::DepthBiasState {
353 fn from(value: DepthBiasState) -> Self {
354 Self { constant: value.constant, slope_scale: value.slope_scale, clamp: value.clamp }
355 }
356}
357
358#[derive(Clone, PartialEq)]
360pub struct DepthStencilState {
361 pub format: TextureFormat,
364 pub depth_write_enabled: Option<bool>,
366 pub depth_compare: Option<CompareFunction>,
368 pub stencil: StencilState,
370 pub bias: DepthBiasState,
372}
373
374impl From<DepthStencilState> for wgpu::DepthStencilState {
375 fn from(value: DepthStencilState) -> Self {
376 Self {
377 format: value.format.into(),
378 depth_write_enabled: value.depth_write_enabled,
379 depth_compare: value.depth_compare.map(Into::into),
380 stencil: value.stencil.into(),
381 bias: value.bias.into(),
382 }
383 }
384}
385
386pub struct Material {
392 label: Option<&'static str>,
395 shader_source: &'static str,
397 vertex_entry: Option<&'static str>,
399 fragment_entry: Option<&'static str>,
401 vertex_layouts: Vec<VertexBufferLayout>,
404 entries: Vec<BindingEntry>,
409 cull_mode: Option<Face>,
411 depth: Option<DepthStencilState>,
413 targets: Vec<ColorTargetState>,
416 polygon_mode: PolygonMode,
418 sample_count: u32,
427 own_group: Option<u32>,
430 extra_layouts: Vec<super::layout::OwnedGroupLayout>,
435}
436
437impl Default for Material {
438 fn default() -> Self {
439 Self {
440 label: None,
441 shader_source: "",
442 vertex_entry: Some("vs_main"),
443 fragment_entry: Some("fs_main"),
444 vertex_layouts: Vec::new(),
445 entries: Vec::new(),
446 cull_mode: Some(Face::Back),
447 depth: None,
448 targets: Vec::new(),
449 own_group: Some(0),
450 extra_layouts: Vec::new(),
451 polygon_mode: PolygonMode::Fill,
452 sample_count: 1,
453 }
454 }
455}
456
457impl Material {
458 pub fn new(shader_source: &'static str) -> Self {
461 Self { shader_source, ..Self::default() }
462 }
463
464 pub fn label(mut self, label: &'static str) -> Self {
465 self.label = Some(label);
466 self
467 }
468
469 pub fn vertex_entry(mut self, entry: &'static str) -> Self {
470 self.vertex_entry = Some(entry);
471 self
472 }
473
474 pub fn fragment_entry(mut self, entry: &'static str) -> Self {
475 self.fragment_entry = Some(entry);
476 self
477 }
478
479 pub fn vertex_layouts(mut self, layouts: Vec<VertexBufferLayout>) -> Self {
480 self.vertex_layouts = layouts;
481 self
482 }
483
484 pub fn entries(mut self, entries: Vec<BindingEntry>) -> Self {
485 self.entries = entries;
486 self
487 }
488
489 pub fn cull_mode(mut self, mode: Option<Face>) -> Self {
490 self.cull_mode = mode;
491 self
492 }
493
494 pub fn depth(mut self, depth: DepthStencilState) -> Self {
495 self.depth = Some(depth);
496 self
497 }
498
499 pub fn targets(mut self, targets: Vec<ColorTargetState>) -> Self {
500 self.targets = targets;
501 self
502 }
503
504 pub fn polygon_mode(mut self, mode: PolygonMode) -> Self {
505 self.polygon_mode = mode;
506 self
507 }
508
509 pub fn sample_count(mut self, count: u32) -> Self {
510 self.sample_count = count;
511 self
512 }
513
514 pub fn own_group(mut self, group: u32) -> Self {
515 self.own_group = Some(group);
516 self
517 }
518
519 pub fn no_own_group(mut self) -> Self {
523 self.own_group = None;
524 self
525 }
526
527 pub fn extra_layouts(mut self, layouts: Vec<super::layout::OwnedGroupLayout>) -> Self {
528 self.extra_layouts = layouts;
529 self
530 }
531
532 fn validate(&self) {
537 if self.targets.is_empty() {
538 tracing::warn!(
539 "Material{}: no color targets set — a render pipeline normally writes to at \
540 least one; consider calling .targets(...) (unless this is intentionally a \
541 depth-only pass)",
542 self.label.map(|l| format!(" '{l}'")).unwrap_or_default(),
543 );
544 }
545 }
546
547 pub fn build(self) -> Self {
549 self.validate();
550 self
551 }
552
553 pub fn build_asset(self, name: &str, assets: &mut Assets<Self>) -> Handle<Self> {
556 self.validate();
557 assets.insert(name, self)
558 }
559}
560
561pub fn build_material(backend: &WGPUBackend, desc: &Material) -> (RenderPipeline, BindGroupLayout) {
576 build_material_raw(&backend.device, desc)
577}
578
579pub(crate) fn build_material_raw(
582 device: &wgpu::Device,
583 desc: &Material,
584) -> (RenderPipeline, BindGroupLayout) {
585 for entry in &desc.entries {
586 if entry.kind.visibility().intersects(ShaderStages::COMPUTE) {
587 panic!(
588 "material{}: entry '{}' is visible to the compute stage — material bind \
589 group entries must not be COMPUTE-visible",
590 desc.label.map(|l| format!(" '{l}'")).unwrap_or_default(),
591 entry.name,
592 );
593 }
594 }
595
596 let layout = BindGroupLayoutBuilder::new()
597 .label(desc.label)
598 .entries(desc.entries.iter().cloned())
599 .build_raw(device);
600
601 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
602 label: desc.label,
603 source: wgpu::ShaderSource::Wgsl(desc.shader_source.into()),
604 });
605
606 let mut slots: Vec<super::layout::GroupLayout> = desc
607 .extra_layouts
608 .iter()
609 .map(|g| super::layout::GroupLayout { group: g.group, layout: &g.layout })
610 .collect();
611 if let Some(own_group) = desc.own_group {
612 slots.push(super::layout::GroupLayout { group: own_group, layout: &layout });
613 }
614 let bind_group_layouts = super::layout::assemble_bind_group_layouts(desc.label, slots);
615
616 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
617 label: desc.label,
618 bind_group_layouts: &bind_group_layouts,
619 immediate_size: 0,
620 });
621
622 let attribute_sets: Vec<Vec<wgpu::VertexAttribute>> = desc
623 .vertex_layouts
624 .iter()
625 .map(|l| l.attributes.iter().map(|a| (*a).into()).collect())
626 .collect();
627 let vertex_buffers: Vec<wgpu::VertexBufferLayout> = desc
628 .vertex_layouts
629 .iter()
630 .zip(attribute_sets.iter())
631 .map(|(l, attrs)| wgpu::VertexBufferLayout {
632 array_stride: l.array_stride,
633 step_mode: l.step_mode.into(),
634 attributes: attrs,
635 })
636 .collect();
637
638 let targets: Vec<Option<wgpu::ColorTargetState>> =
639 desc.targets.iter().cloned().map(|t| Some(t.into())).collect();
640
641 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
642 label: desc.label,
643 layout: Some(&pipeline_layout),
644 vertex: wgpu::VertexState {
645 module: &module,
646 entry_point: desc.vertex_entry,
647 compilation_options: Default::default(),
648 buffers: &vertex_buffers,
649 },
650 primitive: wgpu::PrimitiveState {
651 topology: wgpu::PrimitiveTopology::TriangleList,
652 strip_index_format: None,
653 front_face: wgpu::FrontFace::Ccw,
654 cull_mode: desc.cull_mode.map(Into::into),
655 unclipped_depth: false,
656 polygon_mode: desc.polygon_mode.into(),
657 conservative: false,
658 },
659 depth_stencil: desc.depth.clone().map(Into::into),
660 multisample: wgpu::MultisampleState {
661 count: desc.sample_count,
662 mask: !0,
663 alpha_to_coverage_enabled: false,
664 },
665 fragment: Some(wgpu::FragmentState {
666 module: &module,
667 entry_point: desc.fragment_entry,
668 compilation_options: Default::default(),
669 targets: &targets,
670 }),
671 multiview_mask: None,
672 cache: None,
673 });
674
675 (RenderPipeline(pipeline), layout)
676}
677
678pub struct GPUMaterial {
683 pub pipeline: RenderPipeline,
684 layout: BindGroupLayout,
685 entries: Vec<BindingEntry>,
686}
687
688impl super::binding::BindGroupTarget for GPUMaterial {
689 fn bind_group_layout(&self) -> &BindGroupLayout {
690 &self.layout
691 }
692 fn binding_entries(&self) -> &[BindingEntry] {
693 &self.entries
694 }
695}
696
697impl Asset<WGPUBackend> for GPUMaterial {
698 type Source = Material;
699 type Deps<'a> = ();
700
701 fn upload<'a>(source: &Material, backend: &WGPUBackend, _deps: &()) -> Option<Self> {
702 let (pipeline, layout) = build_material(backend, source);
703
704 Some(Self {
705 pipeline,
706 layout,
707 entries: source.entries.to_vec(),
708 })
709 }
710}
711
712crate::wgpu::plugin_macros::asset_plugin! {
713 MaterialPlugin, GPUMaterial
718}
719
720#[cfg(test)]
721mod tests {
722 use super::*;
723 use crate::wgpu::binding::{BindingEntry, BindingKind};
724 use crate::wgpu::test_util::with_device;
725
726 const MINIMAL_SHADER: &str = r#"
727 @vertex
728 fn vs_main() -> @builtin(position) vec4<f32> {
729 return vec4<f32>(0.0, 0.0, 0.0, 1.0);
730 }
731 @fragment
732 fn fs_main() -> @location(0) vec4<f32> {
733 return vec4<f32>(1.0, 1.0, 1.0, 1.0);
734 }
735 "#;
736
737 #[test]
738 fn a_compute_visible_entry_panics_before_touching_the_device() {
739 with_device!(device, _queue, {
740 let desc = Material {
741 shader_source: MINIMAL_SHADER,
742 entries: vec![BindingEntry {
743 name: "bad",
744 binding: 0,
745 kind: BindingKind::storage_buffer_read_write(ShaderStages::COMPUTE),
746 }],
747 targets: DEFAULT_TARGET.to_vec(),
748 ..Default::default()
749 };
750 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
751 build_material_raw(&device, &desc);
752 }));
753 assert!(result.is_err(), "expected a panic for a COMPUTE-visible material entry");
754 });
755 }
756
757 #[test]
758 fn a_fragment_visible_entry_builds_without_panicking() {
759 with_device!(device, _queue, {
760 let desc = Material {
761 shader_source: MINIMAL_SHADER,
762 entries: vec![],
763 own_group: None,
764 targets: DEFAULT_TARGET.to_vec(),
765 ..Default::default()
766 };
767 build_material_raw(&device, &desc);
768 });
769 }
770}