-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathencoder.rs
More file actions
1293 lines (1165 loc) · 39.7 KB
/
encoder.rs
File metadata and controls
1293 lines (1165 loc) · 39.7 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
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! High-level command encoding for GPU work submission.
//!
//! This module provides `CommandEncoder` for recording GPU commands and
//! `RenderPassEncoder` for recording render pass commands. These types wrap
//! the platform layer and provide validation, high-level type safety, and a
//! clean API for the engine.
//!
//! Command encoders are created per-frame and not reused across frames, which
//! matches wgpu best practices and avoids stale state issues.
//!
//! # Usage
//!
//! The encoder uses a callback-based API for render passes to ensure proper
//! lifetime management (wgpu's `RenderPass` borrows from the encoder):
//!
//! ```ignore
//! let mut encoder = CommandEncoder::new(&render_context, "frame-encoder");
//! encoder.with_render_pass(
//! &pass,
//! RenderPassDestinationInfo { color_format: None, depth_format: None },
//! &mut attachments,
//! depth,
//! |rp_encoder| {
//! rp_encoder.set_pipeline(&pipeline)?;
//! rp_encoder.draw(0..3, 0..1)?;
//! Ok(())
//! })?;
//! encoder.finish(&render_context);
//! ```
use std::{
collections::{
BTreeSet,
HashSet,
},
ops::Range,
};
use lambda_platform::wgpu as platform;
use logging;
use super::{
bind::BindGroup,
buffer::{
Buffer,
BufferType,
},
color_attachments::RenderColorAttachments,
command::IndexFormat,
pipeline::RenderPipeline,
render_pass::RenderPass,
texture::{
DepthFormat,
DepthTexture,
TextureFormat,
},
validation,
viewport::Viewport,
RenderContext,
};
use crate::util;
// ---------------------------------------------------------------------------
// CommandEncoder
// ---------------------------------------------------------------------------
/// Destination metadata needed for render-target compatibility validation.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RenderPassDestinationInfo {
pub(crate) color_format: Option<TextureFormat>,
pub(crate) depth_format: Option<DepthFormat>,
}
/// High-level command encoder for recording GPU work.
///
/// Created per-frame via `CommandEncoder::new()`. Commands are recorded by
/// beginning render passes (and in the future, compute passes and copy ops).
/// Call `finish()` to submit the recorded work.
///
/// The encoder owns the underlying platform encoder and manages its lifetime.
pub struct CommandEncoder {
inner: platform::command::CommandEncoder,
}
impl CommandEncoder {
/// Create a new command encoder for recording GPU work.
///
/// The encoder is tied to the current frame and should not be reused across
/// frames.
pub fn new(render_context: &RenderContext, label: &str) -> Self {
let inner = platform::command::CommandEncoder::new(
render_context.gpu().platform(),
Some(label),
);
return CommandEncoder { inner };
}
/// Execute a render pass with the provided configuration.
///
/// This method begins a render pass, executes the provided closure with a
/// `RenderPassEncoder`, and automatically ends the pass when the closure
/// returns. This ensures proper resource cleanup and lifetime management.
///
/// # Arguments
/// * `pass` - The high-level render pass configuration.
/// * `color_attachments` - Color attachment views for the pass.
/// * `depth_texture` - Optional depth texture for depth/stencil operations.
/// * `func` - Closure that records commands to the render pass encoder.
///
/// # Type Parameters
/// * `'pass` - Lifetime of resources borrowed during the render pass.
/// * `PassFn` - The closure type that records commands to the pass.
/// * `Output` - The return type of the closure.
///
/// # Returns
/// The result of the closure, or any render pass error encountered.
pub(crate) fn with_render_pass<'pass, PassFn, Output>(
&'pass mut self,
pass: &'pass RenderPass,
destination_info: RenderPassDestinationInfo,
color_attachments: &'pass mut RenderColorAttachments<'pass>,
depth_texture: Option<&'pass DepthTexture>,
func: PassFn,
) -> Result<Output, RenderPassError>
where
PassFn:
FnOnce(&mut RenderPassEncoder<'_>) -> Result<Output, RenderPassError>,
{
let pass_encoder = RenderPassEncoder::new(
&mut self.inner,
pass,
destination_info,
color_attachments,
depth_texture,
);
return func(&mut { pass_encoder });
}
/// Finish recording and submit the command buffer to the GPU.
///
/// This consumes the encoder and submits the recorded commands for
/// execution.
pub fn finish(self, render_context: &RenderContext) {
let buffer = self.inner.finish();
render_context
.gpu()
.platform()
.submit(std::iter::once(buffer));
}
}
impl std::fmt::Debug for CommandEncoder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return f.debug_struct("CommandEncoder").finish_non_exhaustive();
}
}
// ---------------------------------------------------------------------------
// RenderPassEncoder
// ---------------------------------------------------------------------------
/// High-level render pass encoder for recording render commands.
///
/// Created by `CommandEncoder::with_render_pass()`. Records draw commands,
/// pipeline bindings, and resource bindings within the closure scope.
///
/// The encoder borrows the command encoder for the duration of the pass and
/// performs validation on all operations.
///
/// When instancing validation is enabled, the encoder caches which per-instance
/// vertex buffer slots are still missing for the active pipeline. This keeps
/// repeated `draw*` validation constant-time even when a pass issues many
/// draws.
///
/// # Type Parameters
/// * `'pass` - The lifetime of the render pass, tied to the borrowed encoder
/// and attachments.
pub struct RenderPassEncoder<'pass> {
/// Platform render pass for issuing GPU commands.
pass: platform::render_pass::RenderPass<'pass>,
/// Whether the pass uses color attachments.
uses_color: bool,
/// Whether the pass has a depth attachment.
has_depth_attachment: bool,
/// Whether the pass has stencil operations.
has_stencil: bool,
/// Sample count for MSAA validation.
sample_count: u32,
/// Destination color format when the pass has color output.
destination_color_format: Option<TextureFormat>,
/// Destination depth format when a depth attachment is present.
destination_depth_format: Option<DepthFormat>,
// Validation state (compiled out in release without features)
#[cfg(any(
debug_assertions,
feature = "render-validation-encoder",
feature = "render-validation-instancing"
))]
current_pipeline: Option<CurrentPipeline>,
#[cfg(any(debug_assertions, feature = "render-validation-encoder"))]
bound_index_buffer: Option<BoundIndexBuffer>,
#[cfg(any(debug_assertions, feature = "render-validation-instancing"))]
bound_vertex_slots: HashSet<u32>,
#[cfg(any(
debug_assertions,
feature = "render-validation-depth",
feature = "render-validation-stencil"
))]
warned_no_stencil_for_pipeline: HashSet<usize>,
#[cfg(any(
debug_assertions,
feature = "render-validation-depth",
feature = "render-validation-stencil"
))]
warned_no_depth_for_pipeline: HashSet<usize>,
}
/// Tracks the currently bound pipeline for validation.
#[cfg(any(
debug_assertions,
feature = "render-validation-encoder",
feature = "render-validation-instancing"
))]
struct CurrentPipeline {
label: String,
#[cfg(any(debug_assertions, feature = "render-validation-instancing"))]
missing_instance_slots: BTreeSet<u32>,
}
/// Tracks the currently bound index buffer for validation.
#[cfg(any(debug_assertions, feature = "render-validation-encoder"))]
struct BoundIndexBuffer {
max_indices: u32,
}
impl<'pass> RenderPassEncoder<'pass> {
/// Create a new render pass encoder (internal).
fn new(
encoder: &'pass mut platform::command::CommandEncoder,
pass: &'pass RenderPass,
destination_info: RenderPassDestinationInfo,
color_attachments: &'pass mut RenderColorAttachments<'pass>,
depth_texture: Option<&'pass DepthTexture>,
) -> Self {
// Build the platform render pass
let mut rp_builder = platform::render_pass::RenderPassBuilder::new();
// Map color operations from the high-level RenderPass
let (color_load_op, color_store_op) = pass.color_operations().to_platform();
rp_builder = rp_builder
.with_color_load_op(color_load_op)
.with_store_op(color_store_op);
// Map depth and stencil operations from the high-level RenderPass
let platform_depth_ops =
pass.depth_operations().map(|dop| dop.to_platform());
let platform_stencil_ops =
pass.stencil_operations().map(|sop| sop.to_platform());
let depth_view = depth_texture.map(|dt| dt.platform_view_ref());
let has_depth_attachment = depth_texture.is_some();
let has_stencil = pass.stencil_operations().is_some();
let platform_pass = rp_builder.build(
encoder,
color_attachments.as_platform_attachments_mut(),
depth_view,
platform_depth_ops,
platform_stencil_ops,
pass.label(),
);
return RenderPassEncoder {
pass: platform_pass,
uses_color: pass.uses_color(),
has_depth_attachment,
has_stencil,
sample_count: pass.sample_count(),
destination_color_format: destination_info.color_format,
destination_depth_format: destination_info.depth_format,
#[cfg(any(
debug_assertions,
feature = "render-validation-encoder",
feature = "render-validation-instancing"
))]
current_pipeline: None,
#[cfg(any(debug_assertions, feature = "render-validation-encoder"))]
bound_index_buffer: None,
#[cfg(any(debug_assertions, feature = "render-validation-instancing"))]
bound_vertex_slots: HashSet::new(),
#[cfg(any(
debug_assertions,
feature = "render-validation-depth",
feature = "render-validation-stencil"
))]
warned_no_stencil_for_pipeline: HashSet::new(),
#[cfg(any(
debug_assertions,
feature = "render-validation-depth",
feature = "render-validation-stencil"
))]
warned_no_depth_for_pipeline: HashSet::new(),
};
}
/// Set the active render pipeline.
///
/// Returns an error if the pipeline is incompatible with the current pass
/// configuration (e.g., color target mismatch).
///
/// When instancing validation is enabled, this also computes the currently
/// missing per-instance vertex buffer slots once so subsequent draw
/// validation can reuse cached state.
pub fn set_pipeline(
&mut self,
pipeline: &RenderPipeline,
) -> Result<(), RenderPassError> {
// Validation
#[cfg(any(
debug_assertions,
feature = "render-validation-pass-compat",
feature = "render-validation-encoder"
))]
{
let label = pipeline.pipeline().label().unwrap_or("unnamed");
if !self.uses_color && pipeline.has_color_targets() {
return Err(RenderPassError::PipelineIncompatible(format!(
"Render pipeline '{}' declares color targets but the current pass \
has no color attachments",
label
)));
}
if self.uses_color && !pipeline.has_color_targets() {
return Err(RenderPassError::PipelineIncompatible(format!(
"Render pipeline '{}' has no color targets but the current pass \
declares color attachments",
label
)));
}
if !self.has_depth_attachment && pipeline.expects_depth_stencil() {
return Err(RenderPassError::PipelineIncompatible(format!(
"Render pipeline '{}' expects a depth/stencil attachment but the \
current pass has none",
label
)));
}
}
#[cfg(any(debug_assertions, feature = "render-validation-render-targets",))]
{
let label = pipeline.pipeline().label().unwrap_or("unnamed");
if pipeline.sample_count() != self.sample_count {
return Err(RenderPassError::PipelineIncompatible(format!(
"Render pipeline '{}' has sample_count={} but pass sample_count={}",
label,
pipeline.sample_count(),
self.sample_count
)));
}
if self.uses_color {
if let Some(dest_format) = self.destination_color_format {
if pipeline.color_target_format() != Some(dest_format) {
return Err(RenderPassError::PipelineIncompatible(format!(
"Render pipeline '{}' color format {:?} does not match destination color format {:?}",
label,
pipeline.color_target_format(),
dest_format
)));
}
}
}
if self.has_depth_attachment && pipeline.expects_depth_stencil() {
if let Some(dest_depth_format) = self.destination_depth_format {
if pipeline.depth_format() != Some(dest_depth_format) {
return Err(RenderPassError::PipelineIncompatible(format!(
"Render pipeline '{}' depth format {:?} does not match destination depth format {:?}",
label,
pipeline.depth_format(),
dest_depth_format
)));
}
}
}
}
// Track current pipeline for draw validation
#[cfg(any(
debug_assertions,
feature = "render-validation-encoder",
feature = "render-validation-instancing"
))]
{
let label = pipeline.pipeline().label().unwrap_or("unnamed").to_string();
self.current_pipeline = Some(CurrentPipeline {
label,
#[cfg(any(
debug_assertions,
feature = "render-validation-instancing"
))]
missing_instance_slots: pipeline
.per_instance_slots()
.iter()
.enumerate()
.filter_map(|(slot, is_instance)| {
if !is_instance || self.bound_vertex_slots.contains(&(slot as u32))
{
return None;
}
Some(slot as u32)
})
.collect(),
});
}
// Advisory warnings
#[cfg(any(
debug_assertions,
feature = "render-validation-depth",
feature = "render-validation-stencil"
))]
{
let label = pipeline.pipeline().label().unwrap_or("unnamed");
let pipeline_id = pipeline as *const _ as usize;
if self.has_stencil
&& !pipeline.uses_stencil()
&& self.warned_no_stencil_for_pipeline.insert(pipeline_id)
{
let key = format!("stencil:no_test:{}", label);
let msg = format!(
"Pass provides stencil ops but pipeline '{}' has no stencil test; \
stencil will not affect rendering",
label
);
util::warn_once(&key, &msg);
}
if !self.has_stencil && pipeline.uses_stencil() {
let key = format!("stencil:pass_no_operations:{}", label);
let msg = format!(
"Pipeline '{}' enables stencil but pass has no stencil ops \
configured; stencil reference/tests may be ineffective",
label
);
util::warn_once(&key, &msg);
}
if self.has_depth_attachment
&& !pipeline.expects_depth_stencil()
&& self.warned_no_depth_for_pipeline.insert(pipeline_id)
{
let key = format!("depth:no_test:{}", label);
let msg = format!(
"Pass has depth attachment but pipeline '{}' does not enable depth \
testing; depth values will not be tested/written",
label
);
util::warn_once(&key, &msg);
}
}
self.pass.set_pipeline(pipeline.pipeline());
return Ok(());
}
/// Set the viewport for subsequent draw commands.
pub fn set_viewport(&mut self, viewport: &Viewport) {
let (x, y, width, height, min_depth, max_depth) = viewport.viewport_f32();
self
.pass
.set_viewport(x, y, width, height, min_depth, max_depth);
let (sx, sy, sw, sh) = viewport.scissor_u32();
self.pass.set_scissor_rect(sx, sy, sw, sh);
}
/// Set only the scissor rectangle.
pub fn set_scissor(&mut self, viewport: &Viewport) {
let (x, y, width, height) = viewport.scissor_u32();
self.pass.set_scissor_rect(x, y, width, height);
}
/// Set the stencil reference value.
pub fn set_stencil_reference(&mut self, reference: u32) {
self.pass.set_stencil_reference(reference);
}
/// Bind a bind group with optional dynamic offsets.
pub fn set_bind_group(
&mut self,
set: u32,
group: &BindGroup,
dynamic_offsets: &[u32],
min_uniform_buffer_offset_alignment: u32,
) -> Result<(), RenderPassError> {
validation::validate_dynamic_offsets(
group.dynamic_binding_count(),
dynamic_offsets,
min_uniform_buffer_offset_alignment,
set,
)
.map_err(RenderPassError::Validation)?;
self
.pass
.set_bind_group(set, group.platform_group(), dynamic_offsets);
return Ok(());
}
/// Bind a vertex buffer to a slot.
///
/// When instancing validation is enabled, this updates the cached set of
/// missing per-instance slots for the active pipeline.
pub fn set_vertex_buffer(&mut self, slot: u32, buffer: &Buffer) {
#[cfg(any(debug_assertions, feature = "render-validation-instancing"))]
{
self.bound_vertex_slots.insert(slot);
if let Some(current_pipeline) = self.current_pipeline.as_mut() {
current_pipeline.missing_instance_slots.remove(&slot);
}
}
self.pass.set_vertex_buffer(slot, buffer.raw());
}
/// Bind an index buffer with the specified format.
pub fn set_index_buffer(
&mut self,
buffer: &Buffer,
format: IndexFormat,
) -> Result<(), RenderPassError> {
#[cfg(any(debug_assertions, feature = "render-validation-encoder"))]
{
if buffer.buffer_type() != BufferType::Index {
return Err(RenderPassError::Validation(format!(
"Binding buffer as index but logical type is {:?}; expected \
BufferType::Index",
buffer.buffer_type()
)));
}
let element_size = match format {
IndexFormat::Uint16 => 2u64,
IndexFormat::Uint32 => 4u64,
};
let stride = buffer.stride();
if stride != element_size {
return Err(RenderPassError::Validation(format!(
"Index buffer has element stride {} bytes but format {:?} requires \
{} bytes",
stride, format, element_size
)));
}
let buffer_size = buffer.raw().size();
if !buffer_size.is_multiple_of(element_size) {
return Err(RenderPassError::Validation(format!(
"Index buffer size {} bytes is not a multiple of element size {} \
for format {:?}",
buffer_size, element_size, format
)));
}
let max_indices =
(buffer_size / element_size).min(u32::MAX as u64) as u32;
self.bound_index_buffer = Some(BoundIndexBuffer { max_indices });
}
self
.pass
.set_index_buffer(buffer.raw(), format.to_platform());
return Ok(());
}
/// Issue a non-indexed draw call.
pub fn draw(
&mut self,
vertices: Range<u32>,
instances: Range<u32>,
) -> Result<(), RenderPassError> {
#[cfg(any(debug_assertions, feature = "render-validation-encoder"))]
{
if self.current_pipeline.is_none() {
return Err(RenderPassError::NoPipeline(
"Draw command encountered before any pipeline was set".to_string(),
));
}
}
#[cfg(any(debug_assertions, feature = "render-validation-instancing"))]
{
if let Some(ref pipeline) = self.current_pipeline {
if let Some(slot) = pipeline.missing_instance_slots.iter().next() {
return Err(RenderPassError::Validation(
validation::missing_instance_binding_message(
&pipeline.label,
*slot,
),
));
}
validation::validate_instance_range("Draw", &instances)
.map_err(RenderPassError::Validation)?;
}
if instances.start == instances.end {
logging::debug!(
"Skipping Draw with empty instance range {}..{}",
instances.start,
instances.end
);
return Ok(());
}
}
self.pass.draw(vertices, instances);
return Ok(());
}
/// Issue an indexed draw call.
pub fn draw_indexed(
&mut self,
indices: Range<u32>,
base_vertex: i32,
instances: Range<u32>,
) -> Result<(), RenderPassError> {
#[cfg(any(debug_assertions, feature = "render-validation-encoder"))]
{
if self.current_pipeline.is_none() {
return Err(RenderPassError::NoPipeline(
"DrawIndexed command encountered before any pipeline was set"
.to_string(),
));
}
match &self.bound_index_buffer {
None => {
return Err(RenderPassError::NoIndexBuffer(
"DrawIndexed command encountered without a bound index buffer"
.to_string(),
));
}
Some(bound) => {
if indices.start > indices.end {
return Err(RenderPassError::Validation(format!(
"DrawIndexed index range start {} is greater than end {}",
indices.start, indices.end
)));
}
if indices.end > bound.max_indices {
return Err(RenderPassError::Validation(format!(
"DrawIndexed index range {}..{} exceeds index buffer capacity {}",
indices.start, indices.end, bound.max_indices
)));
}
}
}
}
#[cfg(any(debug_assertions, feature = "render-validation-instancing"))]
{
if let Some(ref pipeline) = self.current_pipeline {
if let Some(slot) = pipeline.missing_instance_slots.iter().next() {
return Err(RenderPassError::Validation(
validation::missing_instance_binding_message(
&pipeline.label,
*slot,
),
));
}
validation::validate_instance_range("DrawIndexed", &instances)
.map_err(RenderPassError::Validation)?;
}
if instances.start == instances.end {
logging::debug!(
"Skipping DrawIndexed with empty instance range {}..{}",
instances.start,
instances.end
);
return Ok(());
}
}
self.pass.draw_indexed(indices, base_vertex, instances);
return Ok(());
}
/// Set immediate data for subsequent draw calls.
///
/// The `offset` and `data` length MUST be multiples of 4 bytes
/// (IMMEDIATE_DATA_ALIGNMENT). The data bytes are passed directly to the
/// GPU for use by shaders that declare `push_constant` uniform blocks
/// (the GLSL syntax remains unchanged).
pub fn set_immediates(&mut self, offset: u32, data: &[u8]) {
self.pass.set_immediates(offset, data);
}
}
impl std::fmt::Debug for RenderPassEncoder<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return f
.debug_struct("RenderPassEncoder")
.field("uses_color", &self.uses_color)
.field("has_depth_attachment", &self.has_depth_attachment)
.field("has_stencil", &self.has_stencil)
.field("sample_count", &self.sample_count)
.finish_non_exhaustive();
}
}
// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------
/// Errors that can occur during render pass encoding.
#[derive(Debug, Clone)]
pub enum RenderPassError {
/// Pipeline is incompatible with the current pass configuration.
PipelineIncompatible(String),
/// No pipeline has been set before a draw call.
NoPipeline(String),
/// No index buffer has been bound before an indexed draw call.
NoIndexBuffer(String),
/// Validation error (offsets, ranges, types, etc.).
Validation(String),
}
impl std::fmt::Display for RenderPassError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
return match self {
RenderPassError::PipelineIncompatible(s) => write!(f, "{}", s),
RenderPassError::NoPipeline(s) => write!(f, "{}", s),
RenderPassError::NoIndexBuffer(s) => write!(f, "{}", s),
RenderPassError::Validation(s) => write!(f, "{}", s),
};
}
}
impl std::error::Error for RenderPassError {}
#[cfg(test)]
pub(crate) fn new_render_pass_encoder_for_tests<'pass>(
encoder: &'pass mut platform::command::CommandEncoder,
pass: &'pass RenderPass,
destination_info: RenderPassDestinationInfo,
color_attachments: &'pass mut RenderColorAttachments<'pass>,
depth_texture: Option<&'pass DepthTexture>,
) -> RenderPassEncoder<'pass> {
return RenderPassEncoder::new(
encoder,
pass,
destination_info,
color_attachments,
depth_texture,
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::render::{
bind::{
BindGroupBuilder,
BindGroupLayoutBuilder,
BindingVisibility,
},
buffer::{
BufferBuilder,
BufferType,
Properties,
Usage,
},
pipeline::RenderPipelineBuilder,
render_pass::RenderPassBuilder,
shader::{
ShaderBuilder,
ShaderKind,
VirtualShader,
},
texture::{
DepthFormat,
DepthTextureBuilder,
TextureBuilder,
TextureFormat,
},
vertex::{
ColorFormat,
VertexAttribute,
VertexElement,
},
viewport::Viewport,
};
fn compile_triangle_shaders(
) -> (crate::render::shader::Shader, crate::render::shader::Shader) {
let vert_path = format!(
"{}/assets/shaders/triangle.vert",
env!("CARGO_MANIFEST_DIR")
);
let frag_path = format!(
"{}/assets/shaders/triangle.frag",
env!("CARGO_MANIFEST_DIR")
);
let mut builder = ShaderBuilder::new();
let vs = builder.build(VirtualShader::File {
path: vert_path,
kind: ShaderKind::Vertex,
name: "triangle-vert".to_string(),
entry_point: "main".to_string(),
});
let fs = builder.build(VirtualShader::File {
path: frag_path,
kind: ShaderKind::Fragment,
name: "triangle-frag".to_string(),
entry_point: "main".to_string(),
});
return (vs, fs);
}
/// Build a minimal pipeline that declares one per-instance vertex buffer.
///
/// This helper exists for encoder tests that need instancing validation
/// without depending on additional render state. The returned pipeline uses
/// the shared triangle shaders and declares slot `0` as a per-instance
/// buffer so tests can exercise cached instance-slot tracking.
///
/// # Arguments
/// - `gpu`: The test GPU used to allocate the instance buffer and create the
/// pipeline.
/// - `pass`: The render pass the pipeline must be compatible with.
///
/// # Returns
/// Returns a `RenderPipeline` configured with one per-instance vertex buffer
/// bound at slot `0`.
fn build_instanced_test_pipeline(
gpu: &crate::render::gpu::Gpu,
pass: &RenderPass,
) -> RenderPipeline {
let (vs, fs) = compile_triangle_shaders();
let instance_buffer = BufferBuilder::new()
.with_label("encoder-test-instance-layout")
.with_usage(Usage::VERTEX)
.with_properties(Properties::CPU_VISIBLE)
.with_buffer_type(BufferType::Vertex)
.build(gpu, vec![[0.0f32; 3]])
.expect("build instance layout buffer");
let instance_attributes = vec![VertexAttribute {
location: 0,
offset: 0,
element: VertexElement {
format: ColorFormat::Rgb32Sfloat,
offset: 0,
},
}];
return RenderPipelineBuilder::new()
.with_label("instanced-pipeline")
.with_instance_buffer(instance_buffer, instance_attributes)
.build(
gpu,
TextureFormat::Rgba8Unorm,
DepthFormat::Depth24Plus,
pass,
&vs,
Some(&fs),
);
}
/// Ensures the `Display` implementation for `RenderPassError` forwards the
/// underlying message without modification.
#[test]
fn render_pass_error_display_is_passthrough() {
let err = RenderPassError::NoPipeline("oops".to_string());
assert_eq!(err.to_string(), "oops");
}
/// Validates the encoder reports an error when a draw is issued before
/// setting a pipeline (when validation is enabled).
#[test]
fn render_pass_encoder_draw_requires_pipeline_when_validation_enabled() {
let Some(gpu) = crate::render::gpu::create_test_gpu("lambda-encoder-test")
else {
return;
};
let resolve = TextureBuilder::new_2d(TextureFormat::Rgba8Unorm)
.with_size(4, 4)
.for_render_target()
.build(&gpu)
.expect("build resolve texture");
let pass = RenderPassBuilder::new()
.with_label("no-pipeline-pass")
.build(&gpu, TextureFormat::Rgba8Unorm, DepthFormat::Depth24Plus);
let mut encoder = platform::command::CommandEncoder::new(
gpu.platform(),
Some("lambda-no-pipeline-encoder"),
);
let mut attachments = RenderColorAttachments::for_offscreen_pass(
pass.uses_color(),
pass.sample_count(),
None,
resolve.view_ref(),
);
let mut rp = RenderPassEncoder::new(
&mut encoder,
&pass,
RenderPassDestinationInfo {
color_format: Some(TextureFormat::Rgba8Unorm),
depth_format: None,
},
&mut attachments,
None,
);
let result = rp.draw(0..3, 0..1);
if cfg!(any(debug_assertions, feature = "render-validation-encoder")) {
let err = result.expect_err("draw must error without a pipeline");
assert!(matches!(err, RenderPassError::NoPipeline(_)));
} else {
result.expect("draw ok without validation");
}
drop(rp);
let _ = encoder.finish();
}
/// In debug builds, checks the engine's pipeline/pass compatibility checks
/// fire before provoking underlying wgpu validation errors.
#[test]
fn render_pass_encoder_validates_pipeline_compatibility_in_debug() {
if !cfg!(debug_assertions) {
// The explicit pass/pipeline compatibility checks are debug- or
// feature-gated; don't attempt to provoke wgpu validation in release.
return;
}
let Some(gpu) = crate::render::gpu::create_test_gpu("lambda-encoder-test")
else {
return;
};
let (vs, fs) = compile_triangle_shaders();
let pass = RenderPassBuilder::new()
.with_label("depth-only-pass")
.without_color()
.with_depth()
.build(&gpu, TextureFormat::Rgba8Unorm, DepthFormat::Depth24Plus);
let pipeline = RenderPipelineBuilder::new()
.with_label("color-pipeline")
.build(
&gpu,
TextureFormat::Rgba8Unorm,
DepthFormat::Depth24Plus,
&pass,
&vs,
Some(&fs),
);
let mut encoder = platform::command::CommandEncoder::new(
gpu.platform(),
Some("lambda-pass-compat-encoder"),
);
let mut attachments = RenderColorAttachments::new();
let depth_texture = DepthTextureBuilder::new()
.with_label("lambda-pass-compat-depth")
.with_size(1, 1)
.with_format(DepthFormat::Depth24Plus)
.build(&gpu);
let mut rp = RenderPassEncoder::new(
&mut encoder,
&pass,
RenderPassDestinationInfo {
color_format: None,
depth_format: Some(DepthFormat::Depth24Plus),
},
&mut attachments,
Some(&depth_texture),
);
let err = rp
.set_pipeline(&pipeline)
.expect_err("pipeline with color targets must be incompatible");
assert!(matches!(err, RenderPassError::PipelineIncompatible(_)));
drop(rp);