-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmod.rs
More file actions
1133 lines (1026 loc) · 34.3 KB
/
mod.rs
File metadata and controls
1133 lines (1026 loc) · 34.3 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 rendering API for cross‑platform windowed applications.
//!
//! The rendering module provides a small set of stable, engine‑facing types
//! that assemble a frame using explicit commands.
//!
//! Concepts
//! - `RenderContext`: owns the graphics instance, presentation surface, and
//! GPU device/queue for a single window. It is the submit point for per‑frame
//! command encoding.
//! - `RenderPass` and `RenderPipeline`: immutable descriptions used when
//! beginning a pass and binding a pipeline. Pipelines declare their vertex
//! inputs, immediate data, and layout (bind group layouts).
//! - `Buffer`, `BindGroupLayout`, and `BindGroup`: GPU resources created via
//! builders and attached to the context, then referenced by small integer
//! handles when encoding commands.
//! - `RenderCommand`: an explicit, validated sequence that begins with
//! `BeginRenderPass`, binds state, draws, and ends with `EndRenderPass`.
//!
//! Minimal flow
//! 1) Create a window and a `RenderContext` with `RenderContextBuilder`.
//! 2) Build resources (buffers, bind group layouts, shaders, pipelines).
//! 3) Record a `Vec<RenderCommand>` each frame and pass it to
//! `RenderContext::render`.
//!
//! See runnable demos under `demos/render/src/bin/` for end‑to‑end snippets.
// Module Exports
pub mod bind;
pub mod buffer;
pub mod command;
pub mod encoder;
pub mod gpu;
pub mod instance;
pub mod mesh;
pub mod pipeline;
pub mod render_pass;
pub mod scene_math;
pub mod shader;
pub mod targets;
pub mod texture;
pub mod validation;
pub mod vertex;
pub mod viewport;
pub mod window;
// Internal modules
mod color_attachments;
use std::{
collections::HashSet,
rc::Rc,
};
use logging;
use self::{
command::{
RenderCommand,
RenderDestination,
},
encoder::{
CommandEncoder,
RenderPassDestinationInfo,
RenderPassError,
},
pipeline::RenderPipeline,
render_pass::RenderPass as RenderPassDesc,
targets::surface::RenderTarget,
};
/// High-level presentation mode selection for window surfaces.
///
/// The selected mode is validated against the adapter's surface capabilities
/// during `RenderContextBuilder::build`. If the requested mode is not
/// supported, Lambda selects a supported fallback.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PresentMode {
/// VSync enabled, capped to display refresh rate (FIFO).
Vsync,
/// VSync disabled, immediate presentation (may tear).
Immediate,
/// Triple buffering, low latency without tearing if supported.
Mailbox,
}
impl Default for PresentMode {
fn default() -> Self {
return PresentMode::Vsync;
}
}
/// Builder for configuring a `RenderContext` tied to one window.
///
/// Purpose
/// - Construct the graphics `Instance`, presentation `Surface`, and logical
/// `Gpu` using the platform layer.
/// - Configure the surface with sane defaults (sRGB when available,
/// `Fifo`/vsync‑compatible present mode, `RENDER_ATTACHMENT` usage).
///
/// Usage
/// - Create with a human‑readable name used in debug labels.
/// - Optionally adjust timeouts, then `build(window)` to obtain a
/// `RenderContext`.
///
/// Typical use is in an application runtime immediately after creating a
/// window. The returned `RenderContext` owns all GPU objects required to render
/// to that window.
pub struct RenderContextBuilder {
name: String,
/// Reserved for future timeout handling during rendering (nanoseconds).
/// Not currently enforced; kept for forward compatibility with runtime controls.
_render_timeout: u64,
present_mode: Option<PresentMode>,
}
impl RenderContextBuilder {
/// Create a new builder tagged with a human‑readable `name` used in labels.
pub fn new(name: &str) -> Self {
Self {
name: name.to_string(),
_render_timeout: 1_000_000_000,
present_mode: None,
}
}
/// Set how long rendering may take before timing out (nanoseconds).
pub fn with_render_timeout(mut self, render_timeout: u64) -> Self {
self._render_timeout = render_timeout;
self
}
/// Enable or disable vertical sync.
///
/// When enabled, the builder requests `PresentMode::Vsync` (FIFO).
///
/// When disabled, the builder requests a non‑vsync mode (immediate
/// presentation) and falls back to a supported low-latency mode if needed.
pub fn with_vsync(mut self, enabled: bool) -> Self {
self.present_mode = Some(if enabled {
PresentMode::Vsync
} else {
PresentMode::Immediate
});
return self;
}
/// Explicitly select a presentation mode.
///
/// The requested mode is validated against the adapter's surface
/// capabilities. If unsupported, the renderer falls back to a supported
/// mode with similar behavior.
pub fn with_present_mode(mut self, mode: PresentMode) -> Self {
self.present_mode = Some(mode);
return self;
}
/// Build a `RenderContext` for the provided `window` and configure the
/// presentation surface.
///
/// Errors are returned instead of panicking to allow callers to surface
/// actionable initialization failures.
pub fn build(
self,
window: &window::Window,
) -> Result<RenderContext, RenderContextError> {
let RenderContextBuilder {
name, present_mode, ..
} = self;
let instance = instance::InstanceBuilder::new()
.with_label(&format!("{} Instance", name))
.build();
let mut surface = targets::surface::WindowSurface::new(&instance, window)
.map_err(|e| {
RenderContextError::SurfaceCreate(format!(
"Failed to create rendering surface: {:?}",
e
))
})?;
let gpu = gpu::GpuBuilder::new()
.with_label(&format!("{} Device", name))
.build(&instance, Some(&surface))
.map_err(|e| {
RenderContextError::GpuCreate(format!(
"Failed to create GPU device: {:?}",
e
))
})?;
let size = window.dimensions();
let platform_present_mode =
resolve_surface_present_mode(present_mode, window.vsync_requested());
surface
.configure_with_defaults(
&gpu,
size,
platform_present_mode,
texture::TextureUsages::RENDER_ATTACHMENT,
)
.map_err(|e| {
RenderContextError::SurfaceConfig(format!(
"Failed to configure surface: {:?}",
e
))
})?;
let config = surface.configuration().ok_or_else(|| {
RenderContextError::SurfaceConfig(
"Surface was not configured".to_string(),
)
})?;
let texture_usage = config.usage;
let config = config.clone();
// Initialize the render context with an engine-level depth format.
let depth_format = texture::DepthFormat::Depth32Float;
let mut render_context = RenderContext {
label: name,
instance,
surface,
gpu,
config,
texture_usage,
size,
depth_texture: None,
depth_format,
depth_sample_count: 1,
msaa_color: None,
msaa_sample_count: 1,
offscreen_targets: vec![],
render_passes: vec![],
render_pipelines: vec![],
bind_group_layouts: vec![],
bind_groups: vec![],
buffers: vec![],
seen_error_messages: HashSet::new(),
};
// Initialize a depth texture matching the surface size using the
// high-level depth texture builder.
let depth_texture = texture::DepthTextureBuilder::new()
.with_size(size.0.max(1), size.1.max(1))
.with_format(depth_format)
.with_label("lambda-depth")
.build(render_context.gpu());
render_context.depth_texture = Some(depth_texture);
return Ok(render_context);
}
}
fn resolve_surface_present_mode(
builder_mode: Option<PresentMode>,
window_vsync: bool,
) -> targets::surface::PresentMode {
let requested = builder_mode.unwrap_or(if window_vsync {
PresentMode::Vsync
} else {
PresentMode::Immediate
});
return match requested {
PresentMode::Vsync => targets::surface::PresentMode::Fifo,
PresentMode::Immediate => targets::surface::PresentMode::Immediate,
PresentMode::Mailbox => targets::surface::PresentMode::Mailbox,
};
}
/// High‑level rendering context for a single window.
///
/// Purpose
/// - Own the platform `Instance`, presentation `Surface`, and logical `Gpu`
/// objects bound to one window.
/// - Host immutable resources (`RenderPass`, `RenderPipeline`, bind layouts,
/// bind groups, and buffers) and expose small integer handles to reference
/// them when recording commands.
/// - Encode and submit per‑frame work based on an explicit `RenderCommand`
/// list.
///
/// Behavior
/// - All methods avoid panics unless explicitly documented; recoverable errors
/// are logged and dropped to keep the app running where possible.
/// - Surface loss or outdated configuration triggers transparent
/// reconfiguration with preserved present mode and usage.
pub struct RenderContext {
label: String,
#[allow(dead_code)]
instance: instance::Instance,
surface: targets::surface::WindowSurface,
gpu: gpu::Gpu,
config: targets::surface::SurfaceConfig,
texture_usage: texture::TextureUsages,
size: (u32, u32),
depth_texture: Option<texture::DepthTexture>,
depth_format: texture::DepthFormat,
depth_sample_count: u32,
msaa_color: Option<texture::ColorAttachmentTexture>,
msaa_sample_count: u32,
offscreen_targets: Vec<targets::offscreen::OffscreenTarget>,
render_passes: Vec<RenderPassDesc>,
render_pipelines: Vec<RenderPipeline>,
bind_group_layouts: Vec<bind::BindGroupLayout>,
bind_groups: Vec<bind::BindGroup>,
buffers: Vec<Rc<buffer::Buffer>>,
seen_error_messages: HashSet<String>,
}
/// Opaque handle used to refer to resources attached to a `RenderContext`.
pub type ResourceId = usize;
impl RenderContext {
/// Optional label assigned when constructing the context.
pub fn label(&self) -> &str {
return self.label.as_str();
}
/// Current surface size in pixels.
///
/// This reflects the most recent configured surface dimensions and is used
/// as a default for render‑target creation and viewport setup.
pub fn surface_size(&self) -> (u32, u32) {
return self.size;
}
/// Attach a render pipeline and return a handle for use in commands.
pub fn attach_pipeline(&mut self, pipeline: RenderPipeline) -> ResourceId {
let id = self.render_pipelines.len();
self.render_pipelines.push(pipeline);
return id;
}
/// Attach a render pass and return a handle for use in commands.
pub fn attach_render_pass(
&mut self,
render_pass: RenderPassDesc,
) -> ResourceId {
let id = self.render_passes.len();
self.render_passes.push(render_pass);
return id;
}
/// Attach an offscreen target and return a handle for use in destinations.
pub fn attach_offscreen_target(
&mut self,
target: targets::offscreen::OffscreenTarget,
) -> ResourceId {
let id = self.offscreen_targets.len();
self.offscreen_targets.push(target);
return id;
}
/// Replace an attached offscreen target in-place.
///
/// Returns an error when `id` does not refer to an attached offscreen
/// target.
pub fn replace_offscreen_target(
&mut self,
id: ResourceId,
target: targets::offscreen::OffscreenTarget,
) -> Result<(), String> {
let slot = match self.offscreen_targets.get_mut(id) {
Some(slot) => slot,
None => return Err(format!("Unknown offscreen target id {}", id)),
};
*slot = target;
return Ok(());
}
/// Attach a bind group layout and return a handle for use in pipeline layout composition.
pub fn attach_bind_group_layout(
&mut self,
layout: bind::BindGroupLayout,
) -> ResourceId {
let id = self.bind_group_layouts.len();
self.bind_group_layouts.push(layout);
return id;
}
/// Attach a bind group and return a handle for use in render commands.
pub fn attach_bind_group(&mut self, group: bind::BindGroup) -> ResourceId {
let id = self.bind_groups.len();
self.bind_groups.push(group);
return id;
}
/// Replace an attached bind group in-place.
pub fn replace_bind_group(
&mut self,
id: ResourceId,
group: bind::BindGroup,
) -> Result<(), String> {
let slot = match self.bind_groups.get_mut(id) {
Some(slot) => slot,
None => return Err(format!("Unknown bind group id {}", id)),
};
*slot = group;
return Ok(());
}
/// Attach a generic GPU buffer and return a handle for render commands.
pub fn attach_buffer(&mut self, buffer: buffer::Buffer) -> ResourceId {
let id = self.buffers.len();
self.buffers.push(Rc::new(buffer));
return id;
}
/// Explicitly destroy the context. Dropping also releases resources.
pub fn destroy(self) {
drop(self);
}
/// Render a list of commands. No‑ops when the list is empty.
///
/// Expectations
/// - The sequence MUST begin a render pass before issuing draw‑related
/// commands and MUST terminate that pass with `EndRenderPass`.
/// - Referenced resource handles (passes, pipelines, buffers, bind groups)
/// MUST have been attached to this context.
///
/// Error handling
/// - Errors are logged and do not panic (e.g., lost/outdated surface,
/// missing resources, invalid dynamic offsets). See `RenderError`.
pub fn render(&mut self, commands: Vec<RenderCommand>) {
if commands.is_empty() {
return;
}
if let Err(err) = self.render_internal(commands) {
let key = format!("{:?}", err);
if self.seen_error_messages.insert(key) {
logging::error!("Render error: {:?}", err);
}
}
}
/// Resize the surface and update surface configuration.
pub fn resize(&mut self, width: u32, height: u32) {
if width == 0 || height == 0 {
return;
}
self.size = (width, height);
if let Err(err) = self.reconfigure_surface(self.size) {
logging::error!("Failed to resize surface: {:?}", err);
}
// Recreate depth texture to match new size.
self.depth_texture = Some(
texture::DepthTextureBuilder::new()
.with_size(self.size.0.max(1), self.size.1.max(1))
.with_format(self.depth_format)
.with_sample_count(self.depth_sample_count)
.with_label("lambda-depth")
.build(&self.gpu),
);
// Drop MSAA color target so it is rebuilt on demand with the new size.
self.msaa_color = None;
}
/// Borrow a previously attached render pass by id.
///
/// Panics if `id` does not refer to an attached pass.
pub fn get_render_pass(&self, id: ResourceId) -> &RenderPassDesc {
return &self.render_passes[id];
}
/// Borrow a previously attached render pipeline by id.
///
/// Panics if `id` does not refer to an attached pipeline.
pub fn get_render_pipeline(&self, id: ResourceId) -> &RenderPipeline {
return &self.render_pipelines[id];
}
/// Borrow a previously attached offscreen target by id.
///
/// Panics if `id` does not refer to an attached offscreen target.
pub fn get_offscreen_target(
&self,
id: ResourceId,
) -> &targets::offscreen::OffscreenTarget {
return &self.offscreen_targets[id];
}
/// Access the GPU device for resource creation.
///
/// Use this to pass to resource builders (buffers, textures, bind groups,
/// etc.) when creating GPU resources.
pub fn gpu(&self) -> &gpu::Gpu {
return &self.gpu;
}
/// The texture format of the render surface.
pub fn surface_format(&self) -> texture::TextureFormat {
return self.config.format;
}
/// The depth texture format used for depth/stencil operations.
pub fn depth_format(&self) -> texture::DepthFormat {
return self.depth_format;
}
/// Device limit: maximum bytes that can be bound for a single uniform buffer binding.
pub fn limit_max_uniform_buffer_binding_size(&self) -> u64 {
return self.gpu.limit_max_uniform_buffer_binding_size();
}
/// Device limit: number of bind groups that can be used by a pipeline layout.
pub fn limit_max_bind_groups(&self) -> u32 {
return self.gpu.limit_max_bind_groups();
}
/// Device limit: maximum number of vertex buffers that can be bound.
pub fn limit_max_vertex_buffers(&self) -> u32 {
return self.gpu.limit_max_vertex_buffers();
}
/// Device limit: maximum number of vertex attributes that can be declared.
pub fn limit_max_vertex_attributes(&self) -> u32 {
return self.gpu.limit_max_vertex_attributes();
}
/// Device limit: required alignment in bytes for dynamic uniform buffer offsets.
pub fn limit_min_uniform_buffer_offset_alignment(&self) -> u32 {
return self.gpu.limit_min_uniform_buffer_offset_alignment();
}
/// Ensure the MSAA color attachment texture exists with the given sample
/// count, recreating it if necessary. Returns the texture view reference.
///
/// This method manages the lifecycle of the internal MSAA texture, creating
/// or recreating it when the sample count changes.
fn ensure_msaa_color_texture(
&mut self,
sample_count: u32,
) -> targets::surface::TextureView<'_> {
let need_recreate = match &self.msaa_color {
Some(_) => self.msaa_sample_count != sample_count,
None => true,
};
if need_recreate {
self.msaa_color = Some(
texture::ColorAttachmentTextureBuilder::new(self.config.format)
.with_size(self.size.0.max(1), self.size.1.max(1))
.with_sample_count(sample_count)
.with_label("lambda-msaa-color")
.build(&self.gpu),
);
self.msaa_sample_count = sample_count;
}
return self
.msaa_color
.as_ref()
.expect("MSAA color attachment should exist")
.view_ref();
}
/// Encode and submit GPU work for a single frame.
fn render_internal(
&mut self,
commands: Vec<RenderCommand>,
) -> Result<(), RenderError> {
if self.size.0 == 0 || self.size.1 == 0 {
return Ok(());
}
let frame = match self.surface.acquire_frame() {
Ok(frame) => frame,
Err(err) => match err {
targets::surface::SurfaceError::Lost
| targets::surface::SurfaceError::Outdated => {
self.reconfigure_surface(self.size)?;
self.surface.acquire_frame().map_err(RenderError::Surface)?
}
_ => return Err(RenderError::Surface(err)),
},
};
let view = frame.texture_view();
let mut encoder =
CommandEncoder::new(self, "lambda-render-command-encoder");
let mut command_iter = commands.into_iter();
while let Some(command) = command_iter.next() {
match command {
RenderCommand::BeginRenderPass {
render_pass,
viewport,
} => {
self.encode_surface_render_pass(
&mut encoder,
&mut command_iter,
render_pass,
viewport,
view,
)?;
}
RenderCommand::BeginRenderPassTo {
render_pass,
viewport,
destination,
} => match destination {
RenderDestination::Surface => {
self.encode_surface_render_pass(
&mut encoder,
&mut command_iter,
render_pass,
viewport,
view,
)?;
}
RenderDestination::Offscreen(target_id) => {
self.encode_offscreen_render_pass(
&mut encoder,
&mut command_iter,
render_pass,
viewport,
target_id,
)?;
}
},
other => {
logging::warn!(
"Ignoring render command outside of a render pass: {:?}",
other
);
}
}
}
encoder.finish(self);
frame.present();
return Ok(());
}
fn encode_surface_render_pass<'view>(
&mut self,
encoder: &mut CommandEncoder,
command_iter: &mut std::vec::IntoIter<RenderCommand>,
render_pass: ResourceId,
viewport: viewport::Viewport,
surface_view: targets::surface::TextureView<'view>,
) -> Result<(), RenderError> {
// Clone the render pass descriptor to avoid borrowing self while we need
// mutable access for MSAA texture creation.
let pass = self
.render_passes
.get(render_pass)
.ok_or_else(|| {
RenderError::Configuration(format!("Unknown render pass {render_pass}"))
})?
.clone();
// Ensure MSAA texture exists if needed.
let sample_count = pass.sample_count();
let uses_color = pass.uses_color();
if uses_color && sample_count > 1 {
self.ensure_msaa_color_texture(sample_count);
}
// Create color attachments for the surface pass. The MSAA view is
// retrieved here after the mutable borrow for texture creation ends.
let msaa_view = if sample_count > 1 {
self.msaa_color.as_ref().map(|t| t.view_ref())
} else {
None
};
let mut color_attachments =
color_attachments::RenderColorAttachments::for_surface_pass(
uses_color,
sample_count,
msaa_view,
surface_view,
);
// Depth/stencil attachment when either depth or stencil requested.
let want_depth_attachment = Self::has_depth_attachment(
pass.depth_operations(),
pass.stencil_operations(),
);
// Prepare depth texture if needed.
if want_depth_attachment {
// Ensure depth texture exists, with proper sample count and format.
let desired_samples = sample_count.max(1);
// If stencil is requested on the pass, ensure we use a stencil-capable format.
if pass.stencil_operations().is_some()
&& self.depth_format != texture::DepthFormat::Depth24PlusStencil8
{
#[cfg(any(debug_assertions, feature = "render-validation-stencil",))]
logging::error!(
"Render pass has stencil ops but depth format {:?} lacks stencil; upgrading to Depth24PlusStencil8",
self.depth_format
);
self.depth_format = texture::DepthFormat::Depth24PlusStencil8;
}
let format_mismatch = self
.depth_texture
.as_ref()
.map(|dt| dt.format() != self.depth_format)
.unwrap_or(true);
if self.depth_texture.is_none()
|| self.depth_sample_count != desired_samples
|| format_mismatch
{
self.depth_texture = Some(
texture::DepthTextureBuilder::new()
.with_size(self.size.0.max(1), self.size.1.max(1))
.with_format(self.depth_format)
.with_sample_count(desired_samples)
.with_label("lambda-depth")
.build(&self.gpu),
);
self.depth_sample_count = desired_samples;
}
}
let depth_texture_ref = if want_depth_attachment {
self.depth_texture.as_ref()
} else {
None
};
let min_uniform_buffer_offset_alignment =
self.limit_min_uniform_buffer_offset_alignment();
let render_pipelines = &self.render_pipelines;
let bind_groups = &self.bind_groups;
let buffers = &self.buffers;
encoder.with_render_pass(
&pass,
RenderPassDestinationInfo {
color_format: if uses_color {
Some(self.surface_format())
} else {
None
},
depth_format: if want_depth_attachment {
Some(self.depth_format())
} else {
None
},
},
&mut color_attachments,
depth_texture_ref,
|rp_encoder| {
return Self::encode_active_render_pass_commands(
command_iter,
rp_encoder,
&viewport,
render_pipelines,
bind_groups,
buffers,
min_uniform_buffer_offset_alignment,
);
},
)?;
return Ok(());
}
fn encode_offscreen_render_pass(
&mut self,
encoder: &mut CommandEncoder,
command_iter: &mut std::vec::IntoIter<RenderCommand>,
render_pass: ResourceId,
viewport: viewport::Viewport,
target_id: ResourceId,
) -> Result<(), RenderError> {
let pass = self
.render_passes
.get(render_pass)
.ok_or_else(|| {
RenderError::Configuration(format!("Unknown render pass {render_pass}"))
})?
.clone();
let target = self.offscreen_targets.get(target_id).ok_or_else(|| {
RenderError::Configuration(format!(
"Unknown offscreen target {target_id}"
))
})?;
let pass_samples = pass.sample_count();
let target_samples = target.sample_count();
if pass_samples != target_samples {
return Err(RenderError::Configuration(format!(
"Pass sample_count={} does not match offscreen target sample_count={}",
pass_samples, target_samples
)));
}
let uses_color = pass.uses_color();
let mut color_attachments =
color_attachments::RenderColorAttachments::for_offscreen_pass(
uses_color,
target_samples,
target.msaa_view(),
target.resolve_view(),
);
let want_depth_attachment = Self::has_depth_attachment(
pass.depth_operations(),
pass.stencil_operations(),
);
if want_depth_attachment && target.depth_texture().is_none() {
return Err(RenderError::Configuration(
"Render pass requests depth/stencil operations but the selected offscreen target has no depth attachment"
.to_string(),
));
}
if pass.stencil_operations().is_some()
&& target.depth_format()
!= Some(texture::DepthFormat::Depth24PlusStencil8)
{
return Err(RenderError::Configuration(
"Render pass requests stencil operations but the selected offscreen target depth format lacks stencil"
.to_string(),
));
}
let depth_texture_ref = if want_depth_attachment {
target.depth_texture()
} else {
None
};
let min_uniform_buffer_offset_alignment =
self.limit_min_uniform_buffer_offset_alignment();
let render_pipelines = &self.render_pipelines;
let bind_groups = &self.bind_groups;
let buffers = &self.buffers;
encoder.with_render_pass(
&pass,
RenderPassDestinationInfo {
color_format: if uses_color {
Some(target.color_format())
} else {
None
},
depth_format: if want_depth_attachment {
target.depth_format()
} else {
None
},
},
&mut color_attachments,
depth_texture_ref,
|rp_encoder| {
return Self::encode_active_render_pass_commands(
command_iter,
rp_encoder,
&viewport,
render_pipelines,
bind_groups,
buffers,
min_uniform_buffer_offset_alignment,
);
},
)?;
return Ok(());
}
fn validate_pipeline_exists(
render_pipelines: &[RenderPipeline],
pipeline: usize,
) -> Result<(), RenderPassError> {
if render_pipelines.get(pipeline).is_none() {
return Err(RenderPassError::Validation(format!(
"Unknown pipeline {pipeline}"
)));
}
return Ok(());
}
fn encode_active_render_pass_commands(
command_iter: &mut std::vec::IntoIter<RenderCommand>,
rp_encoder: &mut encoder::RenderPassEncoder<'_>,
initial_viewport: &viewport::Viewport,
render_pipelines: &[RenderPipeline],
bind_groups: &[bind::BindGroup],
buffers: &[Rc<buffer::Buffer>],
min_uniform_buffer_offset_alignment: u32,
) -> Result<(), RenderPassError> {
rp_encoder.set_viewport(initial_viewport);
for cmd in command_iter.by_ref() {
match cmd {
RenderCommand::EndRenderPass => return Ok(()),
RenderCommand::SetStencilReference { reference } => {
rp_encoder.set_stencil_reference(reference);
}
RenderCommand::SetPipeline { pipeline } => {
let pipeline_ref =
render_pipelines.get(pipeline).ok_or_else(|| {
RenderPassError::Validation(format!(
"Unknown pipeline {pipeline}"
))
})?;
rp_encoder.set_pipeline(pipeline_ref)?;
}
RenderCommand::SetViewports { viewports, .. } => {
for vp in viewports {
rp_encoder.set_viewport(&vp);
}
}
RenderCommand::SetScissors { viewports, .. } => {
for vp in viewports {
rp_encoder.set_scissor(&vp);
}
}
RenderCommand::SetBindGroup {
set,
group,
dynamic_offsets,
} => {
let group_ref = bind_groups.get(group).ok_or_else(|| {
RenderPassError::Validation(format!("Unknown bind group {group}"))
})?;
rp_encoder.set_bind_group(
set,
group_ref,
&dynamic_offsets,
min_uniform_buffer_offset_alignment,
)?;
}
RenderCommand::BindVertexBuffer { pipeline, buffer } => {
let pipeline_ref =
render_pipelines.get(pipeline).ok_or_else(|| {
RenderPassError::Validation(format!(
"Unknown pipeline {pipeline}"
))
})?;
let buffer_ref =
pipeline_ref.buffers().get(buffer as usize).ok_or_else(|| {
RenderPassError::Validation(format!(
"Vertex buffer index {buffer} not found for pipeline {pipeline}"
))
})?;
rp_encoder.set_vertex_buffer(buffer, buffer_ref);
}
RenderCommand::BindIndexBuffer { buffer, format } => {
let buffer_ref = buffers.get(buffer).ok_or_else(|| {
RenderPassError::Validation(format!(
"Index buffer id {} not found",
buffer
))
})?;
rp_encoder.set_index_buffer(buffer_ref, format)?;
}
RenderCommand::Immediates {
pipeline,
offset,
bytes,
} => {
Self::validate_pipeline_exists(render_pipelines, pipeline)?;
// Convert the u32 words to a byte slice for set_immediates.
let byte_slice = unsafe {
std::slice::from_raw_parts(
bytes.as_ptr() as *const u8,
bytes.len() * std::mem::size_of::<u32>(),
)
};
rp_encoder.set_immediates(offset, byte_slice);
}
RenderCommand::Draw {
vertices,
instances,
} => {
rp_encoder.draw(vertices, instances)?;
}
RenderCommand::DrawIndexed {
indices,
base_vertex,
instances,
} => {
rp_encoder.draw_indexed(indices, base_vertex, instances)?;
}
RenderCommand::BeginRenderPass { .. }
| RenderCommand::BeginRenderPassTo { .. } => {
return Err(RenderPassError::Validation(
"Nested render passes are not supported.".to_string(),
));
}
}
}
return Err(RenderPassError::Validation(