Skip to content

Commit d714e3d

Browse files
committed
[d3d12,metal,gl] add support for rendering to slices of 3D textures
1 parent 15477b8 commit d714e3d

File tree

11 files changed

+379
-38
lines changed

11 files changed

+379
-38
lines changed

tests/tests/wgpu-gpu/render_target.rs

Lines changed: 186 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use wgpu::{
22
util::{BufferInitDescriptor, DeviceExt},
33
vertex_attr_array,
44
};
5-
use wgpu_test::{gpu_test, GpuTestConfiguration, TestParameters, TestingContext};
5+
use wgpu_test::{gpu_test, FailureCase, GpuTestConfiguration, TestParameters, TestingContext};
66

77
#[gpu_test]
88
static DRAW_TO_2D_VIEW: GpuTestConfiguration = GpuTestConfiguration::new()
@@ -233,3 +233,188 @@ async fn run_test(
233233
let succeeded = data.iter().all(|b| *b == u8::MAX);
234234
assert!(succeeded);
235235
}
236+
237+
#[gpu_test]
238+
static DRAW_TO_3D_VIEW: GpuTestConfiguration = GpuTestConfiguration::new()
239+
.parameters(
240+
TestParameters::default()
241+
.limits(wgpu::Limits {
242+
max_texture_dimension_3d: 512,
243+
..wgpu::Limits::downlevel_webgl2_defaults()
244+
})
245+
.skip(FailureCase::backend(wgpu::Backends::VULKAN)),
246+
)
247+
.run_async(run_test_3d);
248+
249+
async fn run_test_3d(ctx: TestingContext) {
250+
let vertex_buffer_content: &[f32; 12] = &[
251+
// Triangle 1
252+
-1.0, -1.0, // Bottom left
253+
1.0, 1.0, // Top right
254+
-1.0, 1.0, // Top left
255+
// Triangle 2
256+
-1.0, -1.0, // Bottom left
257+
1.0, -1.0, // Bottom right
258+
1.0, 1.0, // Top right
259+
];
260+
let vertex_buffer = ctx.device.create_buffer_init(&BufferInitDescriptor {
261+
label: None,
262+
contents: bytemuck::cast_slice(vertex_buffer_content),
263+
usage: wgpu::BufferUsages::VERTEX,
264+
});
265+
266+
let shader_src = "
267+
@vertex
268+
fn vs_main(@location(0) position: vec2f) -> @builtin(position) vec4f {
269+
return vec4f(position, 0.0, 1.0);
270+
}
271+
272+
@fragment
273+
fn fs_main() -> @location(0) vec4f {
274+
return vec4f(1.0);
275+
}
276+
";
277+
278+
let shader = ctx
279+
.device
280+
.create_shader_module(wgpu::ShaderModuleDescriptor {
281+
label: None,
282+
source: wgpu::ShaderSource::Wgsl(shader_src.into()),
283+
});
284+
285+
let pipeline_desc = wgpu::RenderPipelineDescriptor {
286+
label: None,
287+
layout: None,
288+
vertex: wgpu::VertexState {
289+
buffers: &[wgpu::VertexBufferLayout {
290+
array_stride: 8,
291+
step_mode: wgpu::VertexStepMode::Vertex,
292+
attributes: &vertex_attr_array![0 => Float32x2],
293+
}],
294+
module: &shader,
295+
entry_point: Some("vs_main"),
296+
compilation_options: Default::default(),
297+
},
298+
primitive: wgpu::PrimitiveState::default(),
299+
depth_stencil: None,
300+
multisample: wgpu::MultisampleState::default(),
301+
fragment: Some(wgpu::FragmentState {
302+
module: &shader,
303+
entry_point: Some("fs_main"),
304+
compilation_options: Default::default(),
305+
targets: &[Some(wgpu::ColorTargetState {
306+
format: wgpu::TextureFormat::R8Unorm,
307+
blend: None,
308+
write_mask: wgpu::ColorWrites::ALL,
309+
})],
310+
}),
311+
multiview: None,
312+
cache: None,
313+
};
314+
let pipeline = ctx.device.create_render_pipeline(&pipeline_desc);
315+
316+
const SIZE: u32 = 512;
317+
const DEPTH: u32 = 2;
318+
const MIPS: u32 = 2;
319+
const fn size_for_mips(mips: u32) -> u64 {
320+
let mut out: u64 = 0;
321+
let mut mip = 0;
322+
while mip < mips {
323+
let size = SIZE as u64 >> mip;
324+
let z = DEPTH as u64 >> mip;
325+
out += size * size * z;
326+
327+
mip += 1;
328+
}
329+
out
330+
}
331+
332+
let out_texture = ctx.device.create_texture(&wgpu::TextureDescriptor {
333+
label: None,
334+
size: wgpu::Extent3d {
335+
width: SIZE,
336+
height: SIZE,
337+
depth_or_array_layers: DEPTH,
338+
},
339+
mip_level_count: MIPS,
340+
sample_count: 1,
341+
dimension: wgpu::TextureDimension::D3,
342+
format: wgpu::TextureFormat::R8Unorm,
343+
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
344+
view_formats: &[],
345+
});
346+
347+
let readback_buffer = ctx.device.create_buffer(&wgpu::BufferDescriptor {
348+
label: None,
349+
size: size_for_mips(MIPS),
350+
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
351+
mapped_at_creation: false,
352+
});
353+
354+
let mut encoder = ctx
355+
.device
356+
.create_command_encoder(&wgpu::CommandEncoderDescriptor::default());
357+
358+
for mip in 0..MIPS {
359+
let out_texture_view = out_texture.create_view(&wgpu::TextureViewDescriptor {
360+
base_mip_level: mip,
361+
mip_level_count: Some(1),
362+
..Default::default()
363+
});
364+
for layer in 0..DEPTH >> mip {
365+
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
366+
label: None,
367+
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
368+
view: &out_texture_view,
369+
depth_slice: Some(layer),
370+
resolve_target: None,
371+
ops: wgpu::Operations {
372+
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
373+
store: wgpu::StoreOp::Store,
374+
},
375+
})],
376+
depth_stencil_attachment: None,
377+
timestamp_writes: None,
378+
occlusion_query_set: None,
379+
});
380+
rpass.set_pipeline(&pipeline);
381+
rpass.set_vertex_buffer(0, vertex_buffer.slice(..));
382+
rpass.draw(0..6, 0..1);
383+
}
384+
}
385+
386+
for mip in 0..MIPS {
387+
encoder.copy_texture_to_buffer(
388+
wgpu::TexelCopyTextureInfo {
389+
texture: &out_texture,
390+
mip_level: mip,
391+
origin: wgpu::Origin3d::ZERO,
392+
aspect: wgpu::TextureAspect::All,
393+
},
394+
wgpu::TexelCopyBufferInfo {
395+
buffer: &readback_buffer,
396+
layout: wgpu::TexelCopyBufferLayout {
397+
offset: size_for_mips(mip),
398+
bytes_per_row: Some(SIZE >> mip),
399+
rows_per_image: Some(SIZE >> mip),
400+
},
401+
},
402+
wgpu::Extent3d {
403+
width: SIZE >> mip,
404+
height: SIZE >> mip,
405+
depth_or_array_layers: DEPTH >> mip,
406+
},
407+
);
408+
}
409+
410+
ctx.queue.submit([encoder.finish()]);
411+
412+
let slice = readback_buffer.slice(..);
413+
slice.map_async(wgpu::MapMode::Read, |_| ());
414+
415+
ctx.async_poll(wgpu::PollType::wait()).await.unwrap();
416+
417+
let data = slice.get_mapped_range();
418+
let succeeded = data.iter().all(|b| *b == u8::MAX);
419+
assert!(succeeded);
420+
}

wgpu-core/src/command/render.rs

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::command::{
1414
};
1515
use crate::init_tracker::BufferInitTrackerAction;
1616
use crate::pipeline::{RenderPipeline, VertexStep};
17-
use crate::resource::InvalidResourceError;
17+
use crate::resource::{InvalidResourceError, ResourceErrorIdent};
1818
use crate::snatch::SnatchGuard;
1919
use crate::{
2020
api_log,
@@ -621,6 +621,18 @@ pub enum ColorAttachmentError {
621621
TooMany { given: usize, limit: usize },
622622
#[error("The total number of bytes per sample in color attachments {total} exceeds the limit {limit}")]
623623
TooManyBytesPerSample { total: u32, limit: u32 },
624+
#[error("Depth slice must be less than {limit} but is {given}")]
625+
DepthSliceLimit { given: u32, limit: u32 },
626+
#[error("Color attachment's view is 3D and requires depth slice to be provided")]
627+
MissingDepthSlice,
628+
#[error("Depth slice was provided but the color attachment's view is not 3D")]
629+
UnneededDepthSlice,
630+
#[error("{view}'s subresource at mip {mip_level} and depth/array layer {depth_or_array_layer} is already attached to this render pass")]
631+
SubresourceOverlap {
632+
view: ResourceErrorIdent,
633+
mip_level: u32,
634+
depth_or_array_layer: u32,
635+
},
624636
}
625637

626638
#[derive(Clone, Debug, Error)]
@@ -1096,6 +1108,8 @@ impl<'d> RenderPassInfo<'d> {
10961108
});
10971109
}
10981110

1111+
let mut attachment_set = crate::FastHashSet::default();
1112+
10991113
let mut color_attachments_hal =
11001114
ArrayVec::<Option<hal::ColorAttachment<_>>, { hal::MAX_COLOR_ATTACHMENTS }>::new();
11011115
for (index, attachment) in color_attachments.iter().enumerate() {
@@ -1126,6 +1140,71 @@ impl<'d> RenderPassInfo<'d> {
11261140
));
11271141
}
11281142

1143+
if color_view.desc.dimension == TextureViewDimension::D3 {
1144+
if let Some(depth_slice) = at.depth_slice {
1145+
let mip = color_view.desc.range.base_mip_level;
1146+
let mip_size = color_view
1147+
.parent
1148+
.desc
1149+
.size
1150+
.mip_level_size(mip, color_view.parent.desc.dimension);
1151+
let limit = mip_size.depth_or_array_layers;
1152+
if depth_slice >= limit {
1153+
return Err(RenderPassErrorInner::ColorAttachment(
1154+
ColorAttachmentError::DepthSliceLimit {
1155+
given: depth_slice,
1156+
limit,
1157+
},
1158+
));
1159+
}
1160+
} else {
1161+
return Err(RenderPassErrorInner::ColorAttachment(
1162+
ColorAttachmentError::MissingDepthSlice,
1163+
));
1164+
}
1165+
} else if at.depth_slice.is_some() {
1166+
return Err(RenderPassErrorInner::ColorAttachment(
1167+
ColorAttachmentError::UnneededDepthSlice,
1168+
));
1169+
}
1170+
1171+
fn check_attachment_overlap(
1172+
attachment_set: &mut crate::FastHashSet<(crate::track::TrackerIndex, u32, u32)>,
1173+
view: &TextureView,
1174+
depth_slice: Option<u32>,
1175+
) -> Result<(), ColorAttachmentError> {
1176+
let mut insert = |slice| {
1177+
let mip_level = view.desc.range.base_mip_level;
1178+
if attachment_set.insert((view.tracking_data.tracker_index(), mip_level, slice))
1179+
{
1180+
Ok(())
1181+
} else {
1182+
Err(ColorAttachmentError::SubresourceOverlap {
1183+
view: view.error_ident(),
1184+
mip_level,
1185+
depth_or_array_layer: slice,
1186+
})
1187+
}
1188+
};
1189+
match view.desc.dimension {
1190+
TextureViewDimension::D2 => {
1191+
insert(view.desc.range.base_array_layer)?;
1192+
}
1193+
TextureViewDimension::D2Array => {
1194+
for layer in view.selector.layers.clone() {
1195+
insert(layer)?;
1196+
}
1197+
}
1198+
TextureViewDimension::D3 => {
1199+
insert(depth_slice.unwrap())?;
1200+
}
1201+
_ => unreachable!(),
1202+
};
1203+
Ok(())
1204+
}
1205+
1206+
check_attachment_overlap(&mut attachment_set, color_view, at.depth_slice)?;
1207+
11291208
Self::add_pass_texture_init_actions(
11301209
at.load_op,
11311210
at.store_op,
@@ -1141,6 +1220,8 @@ impl<'d> RenderPassInfo<'d> {
11411220
resolve_view.same_device(device)?;
11421221
check_multiview(resolve_view)?;
11431222

1223+
check_attachment_overlap(&mut attachment_set, resolve_view, None)?;
1224+
11441225
let resolve_location = AttachmentErrorLocation::Color {
11451226
index,
11461227
resolve: true,

wgpu-core/src/device/resource.rs

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -929,8 +929,11 @@ impl Device {
929929
desc.format,
930930
));
931931
}
932-
// Renderable textures can only be 2D
933-
if desc.usage.contains(wgt::TextureUsages::RENDER_ATTACHMENT) {
932+
933+
// Renderable textures can only be 2D on Vulkan (until we implement 3D support)
934+
if self.backend() == wgt::Backend::Vulkan
935+
&& desc.usage.contains(wgt::TextureUsages::RENDER_ATTACHMENT)
936+
{
934937
return Err(CreateTextureError::InvalidDimensionUsages(
935938
wgt::TextureUsages::RENDER_ATTACHMENT,
936939
desc.dimension,
@@ -948,6 +951,14 @@ impl Device {
948951
desc.format,
949952
));
950953
}
954+
955+
// Renderable textures can only be 2D or 3D
956+
if desc.usage.contains(wgt::TextureUsages::RENDER_ATTACHMENT) {
957+
return Err(CreateTextureError::InvalidDimensionUsages(
958+
wgt::TextureUsages::RENDER_ATTACHMENT,
959+
desc.dimension,
960+
));
961+
}
951962
}
952963

953964
if desc.format.is_compressed() {
@@ -1124,17 +1135,13 @@ impl Device {
11241135

11251136
let clear_mode = if hal_usage
11261137
.intersects(wgt::TextureUses::DEPTH_STENCIL_WRITE | wgt::TextureUses::COLOR_TARGET)
1138+
&& desc.dimension == wgt::TextureDimension::D2
11271139
{
11281140
let (is_color, usage) = if desc.format.is_depth_stencil_format() {
11291141
(false, wgt::TextureUses::DEPTH_STENCIL_WRITE)
11301142
} else {
11311143
(true, wgt::TextureUses::COLOR_TARGET)
11321144
};
1133-
let dimension = match desc.dimension {
1134-
wgt::TextureDimension::D1 => TextureViewDimension::D1,
1135-
wgt::TextureDimension::D2 => TextureViewDimension::D2,
1136-
wgt::TextureDimension::D3 => unreachable!(),
1137-
};
11381145

11391146
let clear_label = hal_label(
11401147
Some("(wgpu internal) clear texture view"),
@@ -1149,7 +1156,7 @@ impl Device {
11491156
let desc = hal::TextureViewDescriptor {
11501157
label: clear_label,
11511158
format: $format,
1152-
dimension,
1159+
dimension: TextureViewDimension::D2,
11531160
usage,
11541161
range: wgt::ImageSubresourceRange {
11551162
aspect: $aspect,
@@ -1420,9 +1427,12 @@ impl Device {
14201427
break 'error Err(TextureViewNotRenderableReason::Usage(resolved_usage));
14211428
}
14221429

1423-
if !(resolved_dimension == TextureViewDimension::D2
1424-
|| resolved_dimension == TextureViewDimension::D2Array)
1425-
{
1430+
let allowed_view_dimensions = [
1431+
TextureViewDimension::D2,
1432+
TextureViewDimension::D2Array,
1433+
TextureViewDimension::D3,
1434+
];
1435+
if !allowed_view_dimensions.contains(&resolved_dimension) {
14261436
break 'error Err(TextureViewNotRenderableReason::Dimension(
14271437
resolved_dimension,
14281438
));

0 commit comments

Comments
 (0)