Debian Codegraph @

third_party/rust/wgpu-hal/examples/ray-traced-triangle/main.rs

raw
1 extern crate wgpu_hal as hal;
2
3 use hal::{
4 Adapter as _, CommandEncoder as _, Device as _, Instance as _, Queue as _, Surface as _,
5 };
6 use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
7
8 use glam::{Affine3A, Mat4, Vec3};
9 use std::{
10 borrow::{Borrow, Cow},
11 iter, ptr,
12 time::Instant,
13 };
14 use wgpu_types::Dx12BackendOptions;
15 use winit::window::WindowButtons;
16
17 const DESIRED_MAX_LATENCY: u32 = 2;
18
19 /// [D3D12_RAYTRACING_INSTANCE_DESC](https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html#d3d12_raytracing_instance_desc)
20 /// [VkAccelerationStructureInstanceKHR](https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkAccelerationStructureInstanceKHR.html)
21 #[derive(Clone)]
22 #[repr(C)]
23 struct AccelerationStructureInstance {
24 transform: [f32; 12],
25 custom_index_and_mask: u32,
26 shader_binding_table_record_offset_and_flags: u32,
27 acceleration_structure_reference: u64,
28 }
29
30 impl std::fmt::Debug for AccelerationStructureInstance {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 f.debug_struct("Instance")
33 .field("transform", &self.transform)
34 .field("custom_data()", &self.custom_index())
35 .field("mask()", &self.mask())
36 .field(
37 "shader_binding_table_record_offset()",
38 &self.shader_binding_table_record_offset(),
39 )
40 .field("flags()", &self.flags())
41 .field(
42 "acceleration_structure_reference",
43 &self.acceleration_structure_reference,
44 )
45 .finish()
46 }
47 }
48
49 #[allow(dead_code)]
50 impl AccelerationStructureInstance {
51 const LOW_24_MASK: u32 = 0x00ff_ffff;
52 const MAX_U24: u32 = (1u32 << 24u32) - 1u32;
53
54 #[inline]
55 fn affine_to_rows(mat: &Affine3A) -> [f32; 12] {
56 let row_0 = mat.matrix3.row(0);
57 let row_1 = mat.matrix3.row(1);
58 let row_2 = mat.matrix3.row(2);
59 let translation = mat.translation;
60 [
61 row_0.x,
62 row_0.y,
63 row_0.z,
64 translation.x,
65 row_1.x,
66 row_1.y,
67 row_1.z,
68 translation.y,
69 row_2.x,
70 row_2.y,
71 row_2.z,
72 translation.z,
73 ]
74 }
75
76 #[inline]
77 fn rows_to_affine(rows: &[f32; 12]) -> Affine3A {
78 Affine3A::from_cols_array(&[
79 rows[0], rows[3], rows[6], rows[9], rows[1], rows[4], rows[7], rows[10], rows[2],
80 rows[5], rows[8], rows[11],
81 ])
82 }
83
84 pub fn transform_as_affine(&self) -> Affine3A {
85 Self::rows_to_affine(&self.transform)
86 }
87 pub fn set_transform(&mut self, transform: &Affine3A) {
88 self.transform = Self::affine_to_rows(transform);
89 }
90
91 pub fn custom_index(&self) -> u32 {
92 self.custom_index_and_mask & Self::LOW_24_MASK
93 }
94
95 pub fn mask(&self) -> u8 {
96 (self.custom_index_and_mask >> 24) as u8
97 }
98
99 pub fn shader_binding_table_record_offset(&self) -> u32 {
100 self.shader_binding_table_record_offset_and_flags & Self::LOW_24_MASK
101 }
102
103 pub fn flags(&self) -> u8 {
104 (self.shader_binding_table_record_offset_and_flags >> 24) as u8
105 }
106
107 pub fn set_custom_index(&mut self, custom_index: u32) {
108 debug_assert!(
109 custom_index <= Self::MAX_U24,
110 "custom_index uses more than 24 bits! {custom_index} > {}",
111 Self::MAX_U24
112 );
113 self.custom_index_and_mask =
114 (custom_index & Self::LOW_24_MASK) | (self.custom_index_and_mask & !Self::LOW_24_MASK)
115 }
116
117 pub fn set_mask(&mut self, mask: u8) {
118 self.custom_index_and_mask =
119 (self.custom_index_and_mask & Self::LOW_24_MASK) | (u32::from(mask) << 24)
120 }
121
122 pub fn set_shader_binding_table_record_offset(
123 &mut self,
124 shader_binding_table_record_offset: u32,
125 ) {
126 debug_assert!(
127 shader_binding_table_record_offset <= Self::MAX_U24,
128 "shader_binding_table_record_offset uses more than 24 bits! {} > {}",
129 shader_binding_table_record_offset,
130 Self::MAX_U24
131 );
132 self.shader_binding_table_record_offset_and_flags = (shader_binding_table_record_offset
133 & Self::LOW_24_MASK)
134 | (self.shader_binding_table_record_offset_and_flags & !Self::LOW_24_MASK)
135 }
136
137 pub fn set_flags(&mut self, flags: u8) {
138 self.shader_binding_table_record_offset_and_flags =
139 (self.shader_binding_table_record_offset_and_flags & Self::LOW_24_MASK)
140 | (u32::from(flags) << 24)
141 }
142
143 pub fn new(
144 transform: &Affine3A,
145 custom_index: u32,
146 mask: u8,
147 shader_binding_table_record_offset: u32,
148 flags: u8,
149 acceleration_structure_reference: u64,
150 ) -> Self {
151 debug_assert!(
152 custom_index <= Self::MAX_U24,
153 "custom_index uses more than 24 bits! {custom_index} > {}",
154 Self::MAX_U24
155 );
156 debug_assert!(
157 shader_binding_table_record_offset <= Self::MAX_U24,
158 "shader_binding_table_record_offset uses more than 24 bits! {} > {}",
159 shader_binding_table_record_offset,
160 Self::MAX_U24
161 );
162 AccelerationStructureInstance {
163 transform: Self::affine_to_rows(transform),
164 custom_index_and_mask: (custom_index & Self::MAX_U24) | (u32::from(mask) << 24),
165 shader_binding_table_record_offset_and_flags: (shader_binding_table_record_offset
166 & Self::MAX_U24)
167 | (u32::from(flags) << 24),
168 acceleration_structure_reference,
169 }
170 }
171 }
172
173 struct ExecutionContext<A: hal::Api> {
174 encoder: A::CommandEncoder,
175 fence: A::Fence,
176 fence_value: hal::FenceValue,
177 used_views: Vec<A::TextureView>,
178 used_cmd_bufs: Vec<A::CommandBuffer>,
179 frames_recorded: usize,
180 }
181
182 impl<A: hal::Api> ExecutionContext<A> {
183 unsafe fn wait_and_clear(&mut self, device: &A::Device) {
184 device.wait(&self.fence, self.fence_value, !0).unwrap();
185 self.encoder.reset_all(self.used_cmd_bufs.drain(..));
186 for view in self.used_views.drain(..) {
187 device.destroy_texture_view(view);
188 }
189 self.frames_recorded = 0;
190 }
191 }
192
193 #[allow(dead_code)]
194 struct Example<A: hal::Api> {
195 instance: A::Instance,
196 adapter: A::Adapter,
197 surface: A::Surface,
198 surface_format: wgpu_types::TextureFormat,
199 device: A::Device,
200 queue: A::Queue,
201
202 contexts: Vec<ExecutionContext<A>>,
203 context_index: usize,
204 extent: [u32; 2],
205 start: Instant,
206 pipeline: A::ComputePipeline,
207 bind_group: A::BindGroup,
208 bgl: A::BindGroupLayout,
209 shader_module: A::ShaderModule,
210 texture_view: A::TextureView,
211 uniform_buffer: A::Buffer,
212 pipeline_layout: A::PipelineLayout,
213 vertices_buffer: A::Buffer,
214 indices_buffer: Option<A::Buffer>,
215 texture: A::Texture,
216 instances: [AccelerationStructureInstance; 3],
217 instances_buffer: A::Buffer,
218 blas: A::AccelerationStructure,
219 tlas: A::AccelerationStructure,
220 scratch_buffer: A::Buffer,
221 time: f32,
222 }
223
224 impl<A: hal::Api> Example<A> {
225 fn init(window: &winit::window::Window) -> Result<Self, Box<dyn std::error::Error>> {
226 let mut index_buffer = false;
227
228 for arg in std::env::args() {
229 if arg == "index_buffer" {
230 index_buffer = true;
231 }
232 }
233
234 if index_buffer {
235 log::info!("using index buffer")
236 }
237
238 let instance_desc = hal::InstanceDescriptor {
239 name: "example",
240 flags: wgpu_types::InstanceFlags::default(),
241 memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds::default(),
242 backend_options: wgpu_types::BackendOptions {
243 dx12: Dx12BackendOptions {
244 shader_compiler: wgpu_types::Dx12Compiler::default_dynamic_dxc(),
245 },
246 ..Default::default()
247 },
248 };
249 let instance = unsafe { A::Instance::init(&instance_desc)? };
250 let surface = {
251 let raw_window_handle = window.window_handle()?.as_raw();
252 let raw_display_handle = window.display_handle()?.as_raw();
253
254 unsafe {
255 instance
256 .create_surface(raw_display_handle, raw_window_handle)
257 .unwrap()
258 }
259 };
260
261 let (adapter, features) = unsafe {
262 let mut adapters = instance.enumerate_adapters(Some(&surface));
263 if adapters.is_empty() {
264 panic!("No adapters found");
265 }
266 let exposed = adapters.swap_remove(0);
267 dbg!(exposed.features);
268 (exposed.adapter, exposed.features)
269 };
270 let surface_caps = unsafe { adapter.surface_capabilities(&surface) }
271 .expect("Surface doesn't support presentation");
272 log::info!("Surface caps: {:#?}", surface_caps);
273
274 let hal::OpenDevice { device, queue } = unsafe {
275 adapter
276 .open(
277 features,
278 &wgpu_types::Limits::default(),
279 &wgpu_types::MemoryHints::Performance,
280 )
281 .unwrap()
282 };
283
284 let window_size: (u32, u32) = window.inner_size().into();
285 dbg!(&surface_caps.formats);
286 let surface_format = if surface_caps
287 .formats
288 .contains(&wgpu_types::TextureFormat::Rgba8Unorm)
289 {
290 wgpu_types::TextureFormat::Rgba8Unorm
291 } else {
292 *surface_caps.formats.first().unwrap()
293 };
294 let surface_config = hal::SurfaceConfiguration {
295 maximum_frame_latency: DESIRED_MAX_LATENCY
296 .max(*surface_caps.maximum_frame_latency.start())
297 .min(*surface_caps.maximum_frame_latency.end()),
298 present_mode: wgpu_types::PresentMode::Fifo,
299 composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque,
300 format: surface_format,
301 extent: wgpu_types::Extent3d {
302 width: window_size.0,
303 height: window_size.1,
304 depth_or_array_layers: 1,
305 },
306 usage: wgpu_types::TextureUses::COLOR_TARGET | wgpu_types::TextureUses::COPY_DST,
307 view_formats: vec![surface_format],
308 };
309 unsafe {
310 surface.configure(&device, &surface_config).unwrap();
311 };
312
313 #[allow(dead_code)]
314 struct Uniforms {
315 view_inverse: glam::Mat4,
316 proj_inverse: glam::Mat4,
317 }
318
319 let bgl_desc = hal::BindGroupLayoutDescriptor {
320 label: None,
321 flags: hal::BindGroupLayoutFlags::empty(),
322 entries: &[
323 wgpu_types::BindGroupLayoutEntry {
324 binding: 0,
325 visibility: wgpu_types::ShaderStages::COMPUTE,
326 ty: wgpu_types::BindingType::Buffer {
327 ty: wgpu_types::BufferBindingType::Uniform,
328 has_dynamic_offset: false,
329 min_binding_size: wgpu_types::BufferSize::new(size_of::<Uniforms>() as _),
330 },
331 count: None,
332 },
333 wgpu_types::BindGroupLayoutEntry {
334 binding: 1,
335 visibility: wgpu_types::ShaderStages::COMPUTE,
336 ty: wgpu_types::BindingType::StorageTexture {
337 access: wgpu_types::StorageTextureAccess::WriteOnly,
338 format: wgpu_types::TextureFormat::Rgba8Unorm,
339 view_dimension: wgpu_types::TextureViewDimension::D2,
340 },
341 count: None,
342 },
343 wgpu_types::BindGroupLayoutEntry {
344 binding: 2,
345 visibility: wgpu_types::ShaderStages::COMPUTE,
346 ty: wgpu_types::BindingType::AccelerationStructure {
347 vertex_return: false,
348 },
349 count: None,
350 },
351 ],
352 };
353
354 let bgl = unsafe { device.create_bind_group_layout(&bgl_desc).unwrap() };
355
356 let naga_shader = {
357 let shader_file = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
358 .join("examples")
359 .join("ray-traced-triangle")
360 .join("shader.wgsl");
361 let source = std::fs::read_to_string(shader_file).unwrap();
362 let module = naga::front::wgsl::Frontend::new().parse(&source).unwrap();
363 let info = naga::valid::Validator::new(
364 naga::valid::ValidationFlags::all(),
365 naga::valid::Capabilities::RAY_QUERY,
366 )
367 .validate(&module)
368 .unwrap();
369 hal::NagaShader {
370 module: Cow::Owned(module),
371 info,
372 debug_source: None,
373 }
374 };
375 let shader_desc = hal::ShaderModuleDescriptor {
376 label: None,
377 runtime_checks: wgpu_types::ShaderRuntimeChecks::checked(),
378 };
379 let shader_module = unsafe {
380 device
381 .create_shader_module(&shader_desc, hal::ShaderInput::Naga(naga_shader))
382 .unwrap()
383 };
384
385 let pipeline_layout_desc = hal::PipelineLayoutDescriptor {
386 label: None,
387 flags: hal::PipelineLayoutFlags::empty(),
388 bind_group_layouts: &[&bgl],
389 push_constant_ranges: &[],
390 };
391 let pipeline_layout = unsafe {
392 device
393 .create_pipeline_layout(&pipeline_layout_desc)
394 .unwrap()
395 };
396
397 let pipeline = unsafe {
398 device.create_compute_pipeline(&hal::ComputePipelineDescriptor {
399 label: Some("pipeline"),
400 layout: &pipeline_layout,
401 stage: hal::ProgrammableStage {
402 module: &shader_module,
403 entry_point: "main",
404 constants: &Default::default(),
405 zero_initialize_workgroup_memory: true,
406 },
407 cache: None,
408 })
409 }
410 .unwrap();
411
412 let vertices: [f32; 9] = [1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 0.0, -1.0, 0.0];
413
414 let vertices_size_in_bytes = vertices.len() * 4;
415
416 let indices: [u32; 3] = [0, 1, 2];
417
418 let indices_size_in_bytes = indices.len() * 4;
419
420 let vertices_buffer = unsafe {
421 let vertices_buffer = device
422 .create_buffer(&hal::BufferDescriptor {
423 label: Some("vertices buffer"),
424 size: vertices_size_in_bytes as u64,
425 usage: wgpu_types::BufferUses::MAP_WRITE
426 | wgpu_types::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT,
427 memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT,
428 })
429 .unwrap();
430
431 let mapping = device
432 .map_buffer(&vertices_buffer, 0..vertices_size_in_bytes as u64)
433 .unwrap();
434 ptr::copy_nonoverlapping(
435 vertices.as_ptr() as *const u8,
436 mapping.ptr.as_ptr(),
437 vertices_size_in_bytes,
438 );
439 device.unmap_buffer(&vertices_buffer);
440 assert!(mapping.is_coherent);
441
442 vertices_buffer
443 };
444
445 let indices_buffer = if index_buffer {
446 unsafe {
447 let indices_buffer = device
448 .create_buffer(&hal::BufferDescriptor {
449 label: Some("indices buffer"),
450 size: indices_size_in_bytes as u64,
451 usage: wgpu_types::BufferUses::MAP_WRITE
452 | wgpu_types::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT,
453 memory_flags: hal::MemoryFlags::TRANSIENT
454 | hal::MemoryFlags::PREFER_COHERENT,
455 })
456 .unwrap();
457
458 let mapping = device
459 .map_buffer(&indices_buffer, 0..indices_size_in_bytes as u64)
460 .unwrap();
461 ptr::copy_nonoverlapping(
462 indices.as_ptr() as *const u8,
463 mapping.ptr.as_ptr(),
464 indices_size_in_bytes,
465 );
466 device.unmap_buffer(&indices_buffer);
467 assert!(mapping.is_coherent);
468
469 Some((indices_buffer, indices.len()))
470 }
471 } else {
472 None
473 };
474
475 let blas_triangles = vec![hal::AccelerationStructureTriangles {
476 vertex_buffer: Some(&vertices_buffer),
477 first_vertex: 0,
478 vertex_format: wgpu_types::VertexFormat::Float32x3,
479 // each vertex is 3 floats, and floats are stored raw in the array
480 vertex_count: vertices.len() as u32 / 3,
481 vertex_stride: 3 * 4,
482 indices: indices_buffer.as_ref().map(|(buf, len)| {
483 hal::AccelerationStructureTriangleIndices {
484 buffer: Some(buf),
485 format: wgpu_types::IndexFormat::Uint32,
486 offset: 0,
487 count: *len as u32,
488 }
489 }),
490
491 transform: None,
492 flags: hal::AccelerationStructureGeometryFlags::OPAQUE,
493 }];
494 let blas_entries = hal::AccelerationStructureEntries::Triangles(blas_triangles);
495
496 let mut tlas_entries =
497 hal::AccelerationStructureEntries::Instances(hal::AccelerationStructureInstances {
498 buffer: None,
499 count: 3,
500 offset: 0,
501 });
502
503 let blas_sizes = unsafe {
504 device.get_acceleration_structure_build_sizes(
505 &hal::GetAccelerationStructureBuildSizesDescriptor {
506 entries: &blas_entries,
507 flags: hal::AccelerationStructureBuildFlags::PREFER_FAST_TRACE,
508 },
509 )
510 };
511
512 let tlas_flags = hal::AccelerationStructureBuildFlags::PREFER_FAST_TRACE
513 | hal::AccelerationStructureBuildFlags::ALLOW_UPDATE;
514
515 let tlas_sizes = unsafe {
516 device.get_acceleration_structure_build_sizes(
517 &hal::GetAccelerationStructureBuildSizesDescriptor {
518 entries: &tlas_entries,
519 flags: tlas_flags,
520 },
521 )
522 };
523
524 let blas = unsafe {
525 device.create_acceleration_structure(&hal::AccelerationStructureDescriptor {
526 label: Some("blas"),
527 size: blas_sizes.acceleration_structure_size,
528 format: hal::AccelerationStructureFormat::BottomLevel,
529 allow_compaction: false,
530 })
531 }
532 .unwrap();
533
534 let tlas = unsafe {
535 device.create_acceleration_structure(&hal::AccelerationStructureDescriptor {
536 label: Some("tlas"),
537 size: tlas_sizes.acceleration_structure_size,
538 format: hal::AccelerationStructureFormat::TopLevel,
539 allow_compaction: false,
540 })
541 }
542 .unwrap();
543
544 let uniforms = {
545 let view = Mat4::look_at_rh(Vec3::new(0.0, 0.0, 2.5), Vec3::ZERO, Vec3::Y);
546 let proj = Mat4::perspective_rh(59.0_f32.to_radians(), 1.0, 0.001, 1000.0);
547
548 Uniforms {
549 view_inverse: view.inverse(),
550 proj_inverse: proj.inverse(),
551 }
552 };
553
554 let uniforms_size = size_of::<Uniforms>();
555
556 let uniform_buffer = unsafe {
557 let uniform_buffer = device
558 .create_buffer(&hal::BufferDescriptor {
559 label: Some("uniform buffer"),
560 size: uniforms_size as u64,
561 usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM,
562 memory_flags: hal::MemoryFlags::PREFER_COHERENT,
563 })
564 .unwrap();
565
566 let mapping = device
567 .map_buffer(&uniform_buffer, 0..uniforms_size as u64)
568 .unwrap();
569 ptr::copy_nonoverlapping(
570 &uniforms as *const Uniforms as *const u8,
571 mapping.ptr.as_ptr(),
572 uniforms_size,
573 );
574 device.unmap_buffer(&uniform_buffer);
575 assert!(mapping.is_coherent);
576 uniform_buffer
577 };
578
579 let texture_desc = hal::TextureDescriptor {
580 label: None,
581 size: wgpu_types::Extent3d {
582 width: 512,
583 height: 512,
584 depth_or_array_layers: 1,
585 },
586 mip_level_count: 1,
587 sample_count: 1,
588 dimension: wgpu_types::TextureDimension::D2,
589 format: wgpu_types::TextureFormat::Rgba8Unorm,
590 usage: wgpu_types::TextureUses::STORAGE_READ_WRITE | wgpu_types::TextureUses::COPY_SRC,
591 memory_flags: hal::MemoryFlags::empty(),
592 view_formats: vec![wgpu_types::TextureFormat::Rgba8Unorm],
593 };
594 let texture = unsafe { device.create_texture(&texture_desc).unwrap() };
595
596 let view_desc = hal::TextureViewDescriptor {
597 label: None,
598 format: texture_desc.format,
599 dimension: wgpu_types::TextureViewDimension::D2,
600 usage: wgpu_types::TextureUses::STORAGE_READ_WRITE | wgpu_types::TextureUses::COPY_SRC,
601 range: wgpu_types::ImageSubresourceRange::default(),
602 };
603 let texture_view = unsafe { device.create_texture_view(&texture, &view_desc).unwrap() };
604
605 let bind_group = {
606 let buffer_binding = hal::BufferBinding {
607 buffer: &uniform_buffer,
608 offset: 0,
609 size: None,
610 };
611 let texture_binding = hal::TextureBinding {
612 view: &texture_view,
613 usage: wgpu_types::TextureUses::STORAGE_READ_WRITE,
614 };
615 let group_desc = hal::BindGroupDescriptor {
616 label: Some("bind group"),
617 layout: &bgl,
618 buffers: &[buffer_binding],
619 samplers: &[],
620 textures: &[texture_binding],
621 acceleration_structures: &[&tlas],
622 entries: &[
623 hal::BindGroupEntry {
624 binding: 0,
625 resource_index: 0,
626 count: 1,
627 },
628 hal::BindGroupEntry {
629 binding: 1,
630 resource_index: 0,
631 count: 1,
632 },
633 hal::BindGroupEntry {
634 binding: 2,
635 resource_index: 0,
636 count: 1,
637 },
638 ],
639 };
640 unsafe { device.create_bind_group(&group_desc).unwrap() }
641 };
642
643 let scratch_buffer = unsafe {
644 device
645 .create_buffer(&hal::BufferDescriptor {
646 label: Some("scratch buffer"),
647 size: blas_sizes
648 .build_scratch_size
649 .max(tlas_sizes.build_scratch_size),
650 usage: wgpu_types::BufferUses::ACCELERATION_STRUCTURE_SCRATCH,
651 memory_flags: hal::MemoryFlags::empty(),
652 })
653 .unwrap()
654 };
655
656 let instances = [
657 AccelerationStructureInstance::new(
658 &Affine3A::from_translation(Vec3 {
659 x: 0.0,
660 y: 0.0,
661 z: 0.0,
662 }),
663 0,
664 0xff,
665 0,
666 0,
667 unsafe { device.get_acceleration_structure_device_address(&blas) },
668 ),
669 AccelerationStructureInstance::new(
670 &Affine3A::from_translation(Vec3 {
671 x: -1.0,
672 y: -1.0,
673 z: -2.0,
674 }),
675 0,
676 0xff,
677 0,
678 0,
679 unsafe { device.get_acceleration_structure_device_address(&blas) },
680 ),
681 AccelerationStructureInstance::new(
682 &Affine3A::from_translation(Vec3 {
683 x: 1.0,
684 y: -1.0,
685 z: -2.0,
686 }),
687 0,
688 0xff,
689 0,
690 0,
691 unsafe { device.get_acceleration_structure_device_address(&blas) },
692 ),
693 ];
694
695 let instances_buffer_size = instances.len() * size_of::<AccelerationStructureInstance>();
696
697 let instances_buffer = unsafe {
698 let instances_buffer = device
699 .create_buffer(&hal::BufferDescriptor {
700 label: Some("instances_buffer"),
701 size: instances_buffer_size as u64,
702 usage: wgpu_types::BufferUses::MAP_WRITE
703 | wgpu_types::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
704 memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT,
705 })
706 .unwrap();
707
708 let mapping = device
709 .map_buffer(&instances_buffer, 0..instances_buffer_size as u64)
710 .unwrap();
711 ptr::copy_nonoverlapping(
712 instances.as_ptr() as *const u8,
713 mapping.ptr.as_ptr(),
714 instances_buffer_size,
715 );
716 device.unmap_buffer(&instances_buffer);
717 assert!(mapping.is_coherent);
718
719 instances_buffer
720 };
721
722 if let hal::AccelerationStructureEntries::Instances(ref mut i) = tlas_entries {
723 i.buffer = Some(&instances_buffer);
724 assert!(
725 instances.len() <= i.count as usize,
726 "Tlas allocation to small"
727 );
728 }
729
730 let cmd_encoder_desc = hal::CommandEncoderDescriptor {
731 label: None,
732 queue: &queue,
733 };
734 let mut cmd_encoder = unsafe { device.create_command_encoder(&cmd_encoder_desc).unwrap() };
735
736 unsafe { cmd_encoder.begin_encoding(Some("init")).unwrap() };
737
738 unsafe {
739 cmd_encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
740 usage: hal::StateTransition {
741 from: hal::AccelerationStructureUses::empty(),
742 to: hal::AccelerationStructureUses::BUILD_OUTPUT,
743 },
744 });
745
746 cmd_encoder.build_acceleration_structures(
747 1,
748 [hal::BuildAccelerationStructureDescriptor {
749 mode: hal::AccelerationStructureBuildMode::Build,
750 flags: hal::AccelerationStructureBuildFlags::PREFER_FAST_TRACE,
751 destination_acceleration_structure: &blas,
752 scratch_buffer: &scratch_buffer,
753 entries: &blas_entries,
754 source_acceleration_structure: None,
755 scratch_buffer_offset: 0,
756 }],
757 );
758
759 let scratch_buffer_barrier = hal::BufferBarrier {
760 buffer: &scratch_buffer,
761 usage: hal::StateTransition {
762 from: wgpu_types::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT,
763 to: wgpu_types::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
764 },
765 };
766 cmd_encoder.transition_buffers(iter::once(scratch_buffer_barrier));
767
768 cmd_encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
769 usage: hal::StateTransition {
770 from: hal::AccelerationStructureUses::BUILD_OUTPUT,
771 to: hal::AccelerationStructureUses::BUILD_INPUT,
772 },
773 });
774
775 cmd_encoder.build_acceleration_structures(
776 1,
777 [hal::BuildAccelerationStructureDescriptor {
778 mode: hal::AccelerationStructureBuildMode::Build,
779 flags: tlas_flags,
780 destination_acceleration_structure: &tlas,
781 scratch_buffer: &scratch_buffer,
782 entries: &tlas_entries,
783 source_acceleration_structure: None,
784 scratch_buffer_offset: 0,
785 }],
786 );
787
788 cmd_encoder.place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
789 usage: hal::StateTransition {
790 from: hal::AccelerationStructureUses::BUILD_OUTPUT,
791 to: hal::AccelerationStructureUses::SHADER_INPUT,
792 },
793 });
794
795 let texture_barrier = hal::TextureBarrier {
796 texture: &texture,
797 range: wgpu_types::ImageSubresourceRange::default(),
798 usage: hal::StateTransition {
799 from: wgpu_types::TextureUses::UNINITIALIZED,
800 to: wgpu_types::TextureUses::STORAGE_READ_WRITE,
801 },
802 };
803
804 cmd_encoder.transition_textures(iter::once(texture_barrier));
805 }
806
807 let init_fence_value = 1;
808 let fence = unsafe {
809 let mut fence = device.create_fence().unwrap();
810 let init_cmd = cmd_encoder.end_encoding().unwrap();
811 queue
812 .submit(&[&init_cmd], &[], (&mut fence, init_fence_value))
813 .unwrap();
814 device.wait(&fence, init_fence_value, !0).unwrap();
815 cmd_encoder.reset_all(iter::once(init_cmd));
816 fence
817 };
818
819 Ok(Self {
820 instance,
821 adapter,
822 surface,
823 surface_format: surface_config.format,
824 device,
825 queue,
826 pipeline,
827 contexts: vec![ExecutionContext {
828 encoder: cmd_encoder,
829 fence,
830 fence_value: init_fence_value + 1,
831 used_views: Vec::new(),
832 used_cmd_bufs: Vec::new(),
833 frames_recorded: 0,
834 }],
835 context_index: 0,
836 extent: [window_size.0, window_size.1],
837 start: Instant::now(),
838 pipeline_layout,
839 bind_group,
840 texture,
841 instances,
842 instances_buffer,
843 blas,
844 tlas,
845 scratch_buffer,
846 time: 0.0,
847 indices_buffer: indices_buffer.map(|(buf, _)| buf),
848 vertices_buffer,
849 uniform_buffer,
850 texture_view,
851 bgl,
852 shader_module,
853 })
854 }
855
856 fn update(&mut self, _event: winit::event::WindowEvent) {}
857
858 fn render(&mut self) {
859 let ctx = &mut self.contexts[self.context_index];
860
861 let surface_tex = unsafe {
862 self.surface
863 .acquire_texture(None, &ctx.fence)
864 .unwrap()
865 .unwrap()
866 .texture
867 };
868
869 let target_barrier0 = hal::TextureBarrier {
870 texture: surface_tex.borrow(),
871 range: wgpu_types::ImageSubresourceRange::default(),
872 usage: hal::StateTransition {
873 from: wgpu_types::TextureUses::UNINITIALIZED,
874 to: wgpu_types::TextureUses::COPY_DST,
875 },
876 };
877
878 let instances_buffer_size =
879 self.instances.len() * size_of::<AccelerationStructureInstance>();
880
881 let tlas_flags = hal::AccelerationStructureBuildFlags::PREFER_FAST_TRACE
882 | hal::AccelerationStructureBuildFlags::ALLOW_UPDATE;
883
884 self.time += 1.0 / 60.0;
885
886 self.instances[0].set_transform(&Affine3A::from_rotation_y(self.time));
887
888 unsafe {
889 let mapping = self
890 .device
891 .map_buffer(&self.instances_buffer, 0..instances_buffer_size as u64)
892 .unwrap();
893 ptr::copy_nonoverlapping(
894 self.instances.as_ptr() as *const u8,
895 mapping.ptr.as_ptr(),
896 instances_buffer_size,
897 );
898 self.device.unmap_buffer(&self.instances_buffer);
899 assert!(mapping.is_coherent);
900 }
901
902 unsafe {
903 ctx.encoder.begin_encoding(Some("frame")).unwrap();
904
905 let instances = hal::AccelerationStructureInstances {
906 buffer: Some(&self.instances_buffer),
907 count: self.instances.len() as u32,
908 offset: 0,
909 };
910
911 ctx.encoder
912 .place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
913 usage: hal::StateTransition {
914 from: hal::AccelerationStructureUses::SHADER_INPUT,
915 to: hal::AccelerationStructureUses::BUILD_INPUT,
916 },
917 });
918
919 ctx.encoder.build_acceleration_structures(
920 1,
921 [hal::BuildAccelerationStructureDescriptor {
922 mode: hal::AccelerationStructureBuildMode::Update,
923 flags: tlas_flags,
924 destination_acceleration_structure: &self.tlas,
925 scratch_buffer: &self.scratch_buffer,
926 entries: &hal::AccelerationStructureEntries::Instances(instances),
927 source_acceleration_structure: Some(&self.tlas),
928 scratch_buffer_offset: 0,
929 }],
930 );
931
932 ctx.encoder
933 .place_acceleration_structure_barrier(hal::AccelerationStructureBarrier {
934 usage: hal::StateTransition {
935 from: hal::AccelerationStructureUses::BUILD_OUTPUT,
936 to: hal::AccelerationStructureUses::SHADER_INPUT,
937 },
938 });
939
940 let scratch_buffer_barrier = hal::BufferBarrier {
941 buffer: &self.scratch_buffer,
942 usage: hal::StateTransition {
943 from: wgpu_types::BufferUses::BOTTOM_LEVEL_ACCELERATION_STRUCTURE_INPUT,
944 to: wgpu_types::BufferUses::TOP_LEVEL_ACCELERATION_STRUCTURE_INPUT,
945 },
946 };
947 ctx.encoder
948 .transition_buffers(iter::once(scratch_buffer_barrier));
949
950 ctx.encoder.transition_textures(iter::once(target_barrier0));
951 }
952
953 let surface_view_desc = hal::TextureViewDescriptor {
954 label: None,
955 format: self.surface_format,
956 dimension: wgpu_types::TextureViewDimension::D2,
957 usage: wgpu_types::TextureUses::COPY_DST,
958 range: wgpu_types::ImageSubresourceRange::default(),
959 };
960 let surface_tex_view = unsafe {
961 self.device
962 .create_texture_view(surface_tex.borrow(), &surface_view_desc)
963 .unwrap()
964 };
965 unsafe {
966 ctx.encoder.begin_compute_pass(&hal::ComputePassDescriptor {
967 label: None,
968 timestamp_writes: None,
969 });
970 ctx.encoder.set_compute_pipeline(&self.pipeline);
971 ctx.encoder
972 .set_bind_group(&self.pipeline_layout, 0, &self.bind_group, &[]);
973 ctx.encoder.dispatch([512 / 8, 512 / 8, 1]);
974 }
975
976 ctx.frames_recorded += 1;
977
978 let target_barrier1 = hal::TextureBarrier {
979 texture: surface_tex.borrow(),
980 range: wgpu_types::ImageSubresourceRange::default(),
981 usage: hal::StateTransition {
982 from: wgpu_types::TextureUses::COPY_DST,
983 to: wgpu_types::TextureUses::PRESENT,
984 },
985 };
986 let target_barrier2 = hal::TextureBarrier {
987 texture: &self.texture,
988 range: wgpu_types::ImageSubresourceRange::default(),
989 usage: hal::StateTransition {
990 from: wgpu_types::TextureUses::STORAGE_READ_WRITE,
991 to: wgpu_types::TextureUses::COPY_SRC,
992 },
993 };
994 let target_barrier3 = hal::TextureBarrier {
995 texture: &self.texture,
996 range: wgpu_types::ImageSubresourceRange::default(),
997 usage: hal::StateTransition {
998 from: wgpu_types::TextureUses::COPY_SRC,
999 to: wgpu_types::TextureUses::STORAGE_READ_WRITE,
1000 },
1001 };
1002 unsafe {
1003 ctx.encoder.end_compute_pass();
1004 ctx.encoder.transition_textures(iter::once(target_barrier2));
1005 ctx.encoder.copy_texture_to_texture(
1006 &self.texture,
1007 wgpu_types::TextureUses::COPY_SRC,
1008 surface_tex.borrow(),
1009 std::iter::once(hal::TextureCopy {
1010 src_base: hal::TextureCopyBase {
1011 mip_level: 0,
1012 array_layer: 0,
1013 origin: wgpu_types::Origin3d::ZERO,
1014 aspect: hal::FormatAspects::COLOR,
1015 },
1016 dst_base: hal::TextureCopyBase {
1017 mip_level: 0,
1018 array_layer: 0,
1019 origin: wgpu_types::Origin3d::ZERO,
1020 aspect: hal::FormatAspects::COLOR,
1021 },
1022 size: hal::CopyExtent {
1023 width: 512,
1024 height: 512,
1025 depth: 1,
1026 },
1027 }),
1028 );
1029 ctx.encoder.transition_textures(iter::once(target_barrier1));
1030 ctx.encoder.transition_textures(iter::once(target_barrier3));
1031 }
1032
1033 unsafe {
1034 let cmd_buf = ctx.encoder.end_encoding().unwrap();
1035 self.queue
1036 .submit(
1037 &[&cmd_buf],
1038 &[&surface_tex],
1039 (&mut ctx.fence, ctx.fence_value),
1040 )
1041 .unwrap();
1042 self.queue.present(&self.surface, surface_tex).unwrap();
1043 ctx.used_cmd_bufs.push(cmd_buf);
1044 ctx.used_views.push(surface_tex_view);
1045 };
1046
1047 log::info!("Context switch from {}", self.context_index);
1048 let old_fence_value = ctx.fence_value;
1049 if self.contexts.len() == 1 {
1050 let hal_desc = hal::CommandEncoderDescriptor {
1051 label: None,
1052 queue: &self.queue,
1053 };
1054 self.contexts.push(unsafe {
1055 ExecutionContext {
1056 encoder: self.device.create_command_encoder(&hal_desc).unwrap(),
1057 fence: self.device.create_fence().unwrap(),
1058 fence_value: 0,
1059 used_views: Vec::new(),
1060 used_cmd_bufs: Vec::new(),
1061 frames_recorded: 0,
1062 }
1063 });
1064 }
1065 self.context_index = (self.context_index + 1) % self.contexts.len();
1066 let next = &mut self.contexts[self.context_index];
1067 unsafe {
1068 next.wait_and_clear(&self.device);
1069 }
1070 next.fence_value = old_fence_value + 1;
1071 }
1072
1073 fn exit(mut self) {
1074 unsafe {
1075 {
1076 let ctx = &mut self.contexts[self.context_index];
1077 self.queue
1078 .submit(&[], &[], (&mut ctx.fence, ctx.fence_value))
1079 .unwrap();
1080 }
1081
1082 for mut ctx in self.contexts {
1083 ctx.wait_and_clear(&self.device);
1084 drop(ctx.encoder);
1085 self.device.destroy_fence(ctx.fence);
1086 }
1087
1088 self.device.destroy_bind_group(self.bind_group);
1089 self.device.destroy_buffer(self.scratch_buffer);
1090 self.device.destroy_buffer(self.instances_buffer);
1091 if let Some(buffer) = self.indices_buffer {
1092 self.device.destroy_buffer(buffer);
1093 }
1094 self.device.destroy_buffer(self.vertices_buffer);
1095 self.device.destroy_buffer(self.uniform_buffer);
1096 self.device.destroy_acceleration_structure(self.tlas);
1097 self.device.destroy_acceleration_structure(self.blas);
1098 self.device.destroy_texture_view(self.texture_view);
1099 self.device.destroy_texture(self.texture);
1100 self.device.destroy_compute_pipeline(self.pipeline);
1101 self.device.destroy_pipeline_layout(self.pipeline_layout);
1102 self.device.destroy_bind_group_layout(self.bgl);
1103 self.device.destroy_shader_module(self.shader_module);
1104
1105 self.surface.unconfigure(&self.device);
1106 drop(self.queue);
1107 drop(self.device);
1108 drop(self.surface);
1109 drop(self.adapter);
1110 }
1111 }
1112 }
1113
1114 cfg_if::cfg_if! {
1115 // Apple + Metal
1116 if #[cfg(all(target_vendor = "apple", feature = "metal"))] {
1117 type Api = hal::api::Metal;
1118 }
1119 // Wasm + Vulkan
1120 else if #[cfg(all(not(target_arch = "wasm32"), feature = "vulkan"))] {
1121 type Api = hal::api::Vulkan;
1122 }
1123 // Windows + DX12
1124 else if #[cfg(all(windows, feature = "dx12"))] {
1125 type Api = hal::api::Dx12;
1126 }
1127 // Anything + GLES
1128 else if #[cfg(feature = "gles")] {
1129 type Api = hal::api::Gles;
1130 }
1131 // Fallback
1132 else {
1133 type Api = hal::api::Noop;
1134 }
1135 }
1136
1137 fn main() {
1138 env_logger::init();
1139
1140 let event_loop = winit::event_loop::EventLoop::new().unwrap();
1141 let window = winit::window::WindowBuilder::new()
1142 .with_title("hal-ray-traced-triangle")
1143 .with_inner_size(winit::dpi::PhysicalSize {
1144 width: 512,
1145 height: 512,
1146 })
1147 .with_resizable(false)
1148 .with_enabled_buttons(WindowButtons::CLOSE)
1149 .build(&event_loop)
1150 .unwrap();
1151
1152 let example_result = Example::<Api>::init(&window);
1153 let mut example = Some(example_result.expect("Selected backend is not supported"));
1154
1155 event_loop
1156 .run(move |event, target| {
1157 let _ = &window; // force ownership by the closure
1158 target.set_control_flow(winit::event_loop::ControlFlow::Poll);
1159 match event {
1160 winit::event::Event::WindowEvent { event, .. } => match event {
1161 winit::event::WindowEvent::CloseRequested => {
1162 target.exit();
1163 }
1164 winit::event::WindowEvent::KeyboardInput { event, .. }
1165 if event.physical_key
1166 == winit::keyboard::PhysicalKey::Code(
1167 winit::keyboard::KeyCode::Escape,
1168 ) =>
1169 {
1170 target.exit();
1171 }
1172 winit::event::WindowEvent::RedrawRequested => {
1173 let ex = example.as_mut().unwrap();
1174 ex.render();
1175 }
1176 _ => {
1177 example.as_mut().unwrap().update(event);
1178 }
1179 },
1180 winit::event::Event::LoopExiting => {
1181 example.take().unwrap().exit();
1182 }
1183 winit::event::Event::AboutToWait => {
1184 window.request_redraw();
1185 }
1186 _ => {}
1187 }
1188 })
1189 .unwrap();
1190 }