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 groups: Vec<super::layout::GroupEntry>,
407 cull_mode: Option<Face>,
409 depth: Option<DepthStencilState>,
411 targets: Vec<ColorTargetState>,
414 polygon_mode: PolygonMode,
416 sample_count: u32,
425}
426
427impl Default for Material {
428 fn default() -> Self {
429 Self {
430 label: None,
431 shader_source: "",
432 vertex_entry: Some("vs_main"),
433 fragment_entry: Some("fs_main"),
434 vertex_layouts: Vec::new(),
435 groups: Vec::new(),
436 cull_mode: Some(Face::Back),
437 depth: None,
438 targets: Vec::new(),
439 polygon_mode: PolygonMode::Fill,
440 sample_count: 1,
441 }
442 }
443}
444
445impl Material {
446 pub fn new(shader_source: &'static str) -> Self {
449 Self { shader_source, ..Self::default() }
450 }
451
452 pub fn label(mut self, label: &'static str) -> Self {
453 self.label = Some(label);
454 self
455 }
456
457 pub fn vertex_entry(mut self, entry: &'static str) -> Self {
458 self.vertex_entry = Some(entry);
459 self
460 }
461
462 pub fn no_vertex_entry(mut self) -> Self {
467 self.vertex_entry = None;
468 self
469 }
470
471 pub fn fragment_entry(mut self, entry: &'static str) -> Self {
472 self.fragment_entry = Some(entry);
473 self
474 }
475
476 pub fn no_fragment_entry(mut self) -> Self {
479 self.fragment_entry = None;
480 self
481 }
482
483 pub fn vertex_layouts(mut self, layouts: Vec<VertexBufferLayout>) -> Self {
484 self.vertex_layouts = layouts;
485 self
486 }
487
488 pub fn entries(mut self, groups: Vec<super::layout::GroupEntry>) -> Self {
505 self.groups = groups;
506 self
507 }
508
509 pub fn cull_mode(mut self, mode: Face) -> Self {
511 self.cull_mode = Some(mode);
512 self
513 }
514
515 pub fn no_cull_mode(mut self) -> Self {
519 self.cull_mode = None;
520 self
521 }
522
523 pub fn depth(mut self, depth: DepthStencilState) -> Self {
524 self.depth = Some(depth);
525 self
526 }
527
528 pub fn targets(mut self, targets: Vec<ColorTargetState>) -> Self {
529 self.targets = targets;
530 self
531 }
532
533 pub fn polygon_mode(mut self, mode: PolygonMode) -> Self {
534 self.polygon_mode = mode;
535 self
536 }
537
538 pub fn sample_count(mut self, count: u32) -> Self {
539 self.sample_count = count;
540 self
541 }
542
543 fn validate(&self) {
548 if self.targets.is_empty() {
549 tracing::warn!(
550 "Material{}: no color targets set — a render pipeline normally writes to at \
551 least one; consider calling .targets(...) (unless this is intentionally a \
552 depth-only pass)",
553 self.label.map(|l| format!(" '{l}'")).unwrap_or_default(),
554 );
555 }
556 }
557
558 pub fn build(self) -> Self {
560 self.validate();
561 self
562 }
563
564 pub fn build_asset(self, name: &str, assets: &mut Assets<Self>) -> Handle<Self> {
567 self.validate();
568 assets.insert(name, self)
569 }
570}
571
572pub fn build_material(
590 backend: &WGPUBackend,
591 desc: &Material,
592 pool: &super::layout::GlobalLayoutPool,
593) -> Option<(RenderPipeline, BindGroupLayout)> {
594 build_material_raw(&backend.device, desc, pool)
595}
596
597fn check_material_limits(device: &wgpu::Device, desc: &Material) {
603 let limits = device.limits();
604 let labeled = || desc.label.map(|l| format!(" '{l}'")).unwrap_or_default();
605
606 let buffer_count = desc.vertex_layouts.len() as u32;
607 if buffer_count > limits.max_vertex_buffers {
608 panic!(
609 "material{}: {buffer_count} vertex buffer layouts exceeds this device's \
610 max_vertex_buffers ({})",
611 labeled(),
612 limits.max_vertex_buffers
613 );
614 }
615
616 let attribute_count: u32 = desc.vertex_layouts.iter().map(|l| l.attributes.len() as u32).sum();
617 if attribute_count > limits.max_vertex_attributes {
618 panic!(
619 "material{}: {attribute_count} vertex attributes (summed across every vertex \
620 layout) exceeds this device's max_vertex_attributes ({})",
621 labeled(),
622 limits.max_vertex_attributes
623 );
624 }
625
626 let target_count = desc.targets.len() as u32;
627 if target_count > limits.max_color_attachments {
628 panic!(
629 "material{}: {target_count} color targets exceeds this device's max_color_attachments ({})",
630 labeled(),
631 limits.max_color_attachments
632 );
633 }
634}
635
636pub(crate) fn build_material_raw(
639 device: &wgpu::Device,
640 desc: &Material,
641 pool: &super::layout::GlobalLayoutPool,
642) -> Option<(RenderPipeline, BindGroupLayout)> {
643 check_material_limits(device, desc);
644
645 let own_entries =
646 super::layout::find_own_entries(desc.label, super::layout::PipelineKind::Material, &desc.groups);
647 for entry in own_entries {
648 if entry.kind.visibility().intersects(ShaderStages::COMPUTE) {
649 panic!(
650 "material{}: entry '{}' is visible to the compute stage — material bind \
651 group entries must not be COMPUTE-visible",
652 desc.label.map(|l| format!(" '{l}'")).unwrap_or_default(),
653 entry.name,
654 );
655 }
656 }
657
658 let layout = BindGroupLayoutBuilder::new()
659 .label(desc.label)
660 .entries(own_entries.iter().cloned())
661 .build_raw(device);
662
663 let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
664 label: desc.label,
665 source: wgpu::ShaderSource::Wgsl(desc.shader_source.into()),
666 });
667
668 let bind_group_layouts = super::layout::assemble_group_layouts(
669 desc.label,
670 &desc.groups,
671 &layout,
672 pool,
673 device.limits().max_bind_groups,
674 )?;
675
676 let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
677 label: desc.label,
678 bind_group_layouts: &bind_group_layouts,
679 immediate_size: 0,
680 });
681
682 let attribute_sets: Vec<Vec<wgpu::VertexAttribute>> = desc
683 .vertex_layouts
684 .iter()
685 .map(|l| l.attributes.iter().map(|a| (*a).into()).collect())
686 .collect();
687 let vertex_buffers: Vec<wgpu::VertexBufferLayout> = desc
688 .vertex_layouts
689 .iter()
690 .zip(attribute_sets.iter())
691 .map(|(l, attrs)| wgpu::VertexBufferLayout {
692 array_stride: l.array_stride,
693 step_mode: l.step_mode.into(),
694 attributes: attrs,
695 })
696 .collect();
697
698 let targets: Vec<Option<wgpu::ColorTargetState>> =
699 desc.targets.iter().cloned().map(|t| Some(t.into())).collect();
700
701 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
702 label: desc.label,
703 layout: Some(&pipeline_layout),
704 vertex: wgpu::VertexState {
705 module: &module,
706 entry_point: desc.vertex_entry,
707 compilation_options: Default::default(),
708 buffers: &vertex_buffers,
709 },
710 primitive: wgpu::PrimitiveState {
711 topology: wgpu::PrimitiveTopology::TriangleList,
712 strip_index_format: None,
713 front_face: wgpu::FrontFace::Ccw,
714 cull_mode: desc.cull_mode.map(Into::into),
715 unclipped_depth: false,
716 polygon_mode: desc.polygon_mode.into(),
717 conservative: false,
718 },
719 depth_stencil: desc.depth.clone().map(Into::into),
720 multisample: wgpu::MultisampleState {
721 count: desc.sample_count,
722 mask: !0,
723 alpha_to_coverage_enabled: false,
724 },
725 fragment: Some(wgpu::FragmentState {
726 module: &module,
727 entry_point: desc.fragment_entry,
728 compilation_options: Default::default(),
729 targets: &targets,
730 }),
731 multiview_mask: None,
732 cache: None,
733 });
734
735 Some((RenderPipeline(pipeline), layout))
736}
737
738pub struct GPUMaterial {
743 pub pipeline: RenderPipeline,
744 layout: BindGroupLayout,
745 entries: Vec<BindingEntry>,
746}
747
748impl super::binding::BindGroupTarget for GPUMaterial {
749 fn bind_group_layout(&self) -> &BindGroupLayout {
750 &self.layout
751 }
752 fn binding_entries(&self) -> &[BindingEntry] {
753 &self.entries
754 }
755}
756
757impl Asset<WGPUBackend> for GPUMaterial {
758 type Source = Material;
759 type Deps<'a> = crate::ecs::system::Res<'a, super::layout::GlobalLayoutPool>;
760
761 fn upload<'a>(
762 source: &Material,
763 backend: &WGPUBackend,
764 pool: &crate::ecs::system::Res<'a, super::layout::GlobalLayoutPool>,
765 ) -> Option<Self> {
766 let (pipeline, layout) = build_material(backend, source, pool)?;
767 let entries =
768 super::layout::find_own_entries(source.label, super::layout::PipelineKind::Material, &source.groups)
769 .to_vec();
770
771 Some(Self { pipeline, layout, entries })
772 }
773}
774
775crate::wgpu::plugin_macros::asset_plugin! {
776 MaterialPlugin, GPUMaterial
781}
782
783#[cfg(test)]
784mod tests {
785 use super::*;
786 use crate::wgpu::binding::{BindingEntry, BindingKind};
787 use crate::wgpu::test_util::with_device;
788 use crate::wgpu::vertex_format::{VertexAttribute, VertexFormat, VertexStepMode};
789
790 const MINIMAL_SHADER: &str = r#"
791 @vertex
792 fn vs_main() -> @builtin(position) vec4<f32> {
793 return vec4<f32>(0.0, 0.0, 0.0, 1.0);
794 }
795 @fragment
796 fn fs_main() -> @location(0) vec4<f32> {
797 return vec4<f32>(1.0, 1.0, 1.0, 1.0);
798 }
799 "#;
800
801 #[test]
802 fn a_compute_visible_own_entry_panics_before_touching_the_device() {
803 with_device!(device, _queue, {
804 let pool = super::super::layout::GlobalLayoutPool::new();
805 let desc = Material::new(MINIMAL_SHADER)
806 .entries(vec![super::super::layout::GroupEntry::Own(vec![BindingEntry {
807 name: "bad",
808 binding: 0,
809 kind: BindingKind::storage_buffer_read_write(ShaderStages::COMPUTE),
810 }])])
811 .targets(DEFAULT_TARGET.to_vec())
812 .build();
813 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
814 build_material_raw(&device, &desc, &pool);
815 }));
816 assert!(result.is_err(), "expected a panic for a COMPUTE-visible material entry");
817 });
818 }
819
820 #[test]
821 fn no_entries_at_all_builds_without_panicking() {
822 with_device!(device, _queue, {
823 let pool = super::super::layout::GlobalLayoutPool::new();
824 let desc = Material::new(MINIMAL_SHADER).targets(DEFAULT_TARGET.to_vec()).build();
825 build_material_raw(&device, &desc, &pool).unwrap();
826 });
827 }
828
829 #[test]
830 fn a_layout_pulled_from_the_global_pool_ends_up_in_the_pipeline_layout() {
831 with_device!(device, _queue, {
832 let mut pool = super::super::layout::GlobalLayoutPool::new();
833 pool.register("camera", crate::wgpu::binding::BindGroupLayoutBuilder::new().build_raw(&device));
834
835 let desc = Material::new(MINIMAL_SHADER)
836 .entries(vec![super::super::layout::GroupEntry::Layout(pool.get("camera").unwrap())])
837 .targets(DEFAULT_TARGET.to_vec())
838 .build();
839
840 build_material_raw(&device, &desc, &pool).unwrap();
841 });
842 }
843
844 #[test]
845 fn a_global_entry_resolves_from_the_pool_at_build_time() {
846 with_device!(device, _queue, {
847 let mut pool = super::super::layout::GlobalLayoutPool::new();
848 pool.register("camera", crate::wgpu::binding::BindGroupLayoutBuilder::new().build_raw(&device));
849
850 let desc = Material::new(MINIMAL_SHADER)
851 .entries(vec![super::super::layout::GroupEntry::Global("camera")])
852 .targets(DEFAULT_TARGET.to_vec())
853 .build();
854
855 build_material_raw(&device, &desc, &pool).unwrap();
856 });
857 }
858
859 #[test]
860 fn a_global_entry_not_yet_registered_returns_none_instead_of_panicking() {
861 with_device!(device, _queue, {
862 let pool = super::super::layout::GlobalLayoutPool::new(); let desc = Material::new(MINIMAL_SHADER)
864 .entries(vec![super::super::layout::GroupEntry::Global("camera")])
865 .targets(DEFAULT_TARGET.to_vec())
866 .build();
867
868 assert!(build_material_raw(&device, &desc, &pool).is_none());
869 });
870 }
871
872 #[test]
873 fn own_and_layout_groups_are_ordered_by_position() {
874 with_device!(device, _queue, {
875 let pool = super::super::layout::GlobalLayoutPool::new();
876 let extra = crate::wgpu::binding::BindGroupLayoutBuilder::new().build_raw(&device);
877 let desc = Material::new(MINIMAL_SHADER)
878 .entries(vec![
879 super::super::layout::GroupEntry::Own(vec![]),
880 super::super::layout::GroupEntry::Layout(extra),
881 ])
882 .targets(DEFAULT_TARGET.to_vec())
883 .build();
884
885 build_material_raw(&device, &desc, &pool).unwrap();
886 });
887 }
888
889 #[test]
890 fn more_than_one_own_group_panics() {
891 with_device!(device, _queue, {
892 let pool = super::super::layout::GlobalLayoutPool::new();
893 let desc = Material::new(MINIMAL_SHADER)
894 .entries(vec![
895 super::super::layout::GroupEntry::Own(vec![]),
896 super::super::layout::GroupEntry::Own(vec![]),
897 ])
898 .targets(DEFAULT_TARGET.to_vec())
899 .build();
900
901 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
902 build_material_raw(&device, &desc, &pool);
903 }));
904 assert!(result.is_err(), "expected a panic for more than one Own group");
905 });
906 }
907
908 #[test]
909 fn exceeding_max_bind_groups_panics() {
910 with_device!(device, _queue, {
911 let pool = super::super::layout::GlobalLayoutPool::new();
912 let groups: Vec<super::super::layout::GroupEntry> = (0..5)
914 .map(|_| {
915 super::super::layout::GroupEntry::Layout(
916 crate::wgpu::binding::BindGroupLayoutBuilder::new().build_raw(&device),
917 )
918 })
919 .collect();
920 let desc =
921 Material::new(MINIMAL_SHADER).entries(groups).targets(DEFAULT_TARGET.to_vec()).build();
922
923 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
924 build_material_raw(&device, &desc, &pool);
925 }));
926 assert!(result.is_err(), "expected a panic for exceeding max_bind_groups");
927 });
928 }
929
930 #[test]
931 fn exceeding_max_vertex_buffers_panics() {
932 with_device!(device, _queue, {
933 let pool = super::super::layout::GlobalLayoutPool::new();
934 let too_many = device.limits().max_vertex_buffers + 1;
935 let layouts: Vec<VertexBufferLayout> = (0..too_many)
936 .map(|_| VertexBufferLayout { array_stride: 4, step_mode: VertexStepMode::Vertex, attributes: vec![] })
937 .collect();
938 let desc = Material::new(MINIMAL_SHADER)
939 .vertex_layouts(layouts)
940 .targets(DEFAULT_TARGET.to_vec())
941 .build();
942
943 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
944 build_material_raw(&device, &desc, &pool);
945 }));
946 assert!(result.is_err(), "expected a panic for exceeding max_vertex_buffers");
947 });
948 }
949
950 #[test]
951 fn exceeding_max_vertex_attributes_panics() {
952 with_device!(device, _queue, {
953 let pool = super::super::layout::GlobalLayoutPool::new();
954 let too_many = device.limits().max_vertex_attributes + 1;
955 let attributes: Vec<VertexAttribute> = (0..too_many)
956 .map(|i| VertexAttribute { format: VertexFormat::Float32, offset: 0, shader_location: i })
957 .collect();
958 let desc = Material::new(MINIMAL_SHADER)
959 .vertex_layouts(vec![VertexBufferLayout {
960 array_stride: 4,
961 step_mode: VertexStepMode::Vertex,
962 attributes,
963 }])
964 .targets(DEFAULT_TARGET.to_vec())
965 .build();
966
967 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
968 build_material_raw(&device, &desc, &pool);
969 }));
970 assert!(result.is_err(), "expected a panic for exceeding max_vertex_attributes");
971 });
972 }
973
974 #[test]
975 fn exceeding_max_color_attachments_panics() {
976 with_device!(device, _queue, {
977 let pool = super::super::layout::GlobalLayoutPool::new();
978 let too_many = device.limits().max_color_attachments + 1;
979 let targets: Vec<ColorTargetState> = (0..too_many).map(|_| DEFAULT_TARGET[0].clone()).collect();
980 let desc = Material::new(MINIMAL_SHADER).targets(targets).build();
981
982 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
983 build_material_raw(&device, &desc, &pool);
984 }));
985 assert!(result.is_err(), "expected a panic for exceeding max_color_attachments");
986 });
987 }
988}