Skip to main content

wgpu_core/device/trace/
record.rs

1use alloc::{borrow::Cow, string::ToString, sync::Arc, vec::Vec};
2use core::{any::Any, convert::Infallible, marker::PhantomData};
3use std::io::Write as _;
4
5use crate::{
6    command::{
7        ArcCommand, ArcComputeCommand, ArcRayTracingCommand, ArcReferences, ArcRenderCommand,
8        BasePass, ColorAttachments, Command, ComputeCommand, PassTimestampWrites,
9        PointerReferences, RayTracingCommand, RenderCommand, RenderPassColorAttachment,
10        ResolvedRenderPassDepthStencilAttachment,
11    },
12    device::trace::{Data, DataKind, TraceRayTracingPipelineDescriptor},
13    id::{markers, PointerId},
14    storage::StorageItem,
15};
16
17use super::{
18    Action, TraceBindGroupDescriptor, TraceComputePipelineDescriptor,
19    TraceGeneralRenderPipelineDescriptor, FILE_NAME,
20};
21
22pub(crate) fn new_render_bundle_encoder_descriptor(
23    label: crate::Label<'_>,
24    context: &crate::device::RenderPassContext,
25    depth_read_only: bool,
26    stencil_read_only: bool,
27) -> crate::command::RenderBundleEncoderDescriptor<'static> {
28    crate::command::RenderBundleEncoderDescriptor {
29        label: label.map(|l| Cow::from(l.to_string())),
30        color_formats: Cow::from(context.attachments.colors.to_vec()),
31        depth_stencil: context.attachments.depth_stencil.map(|format| {
32            wgt::RenderBundleDepthStencil {
33                format,
34                depth_read_only,
35                stencil_read_only,
36            }
37        }),
38        sample_count: context.sample_count,
39        multiview: context.multiview_mask,
40    }
41}
42
43pub trait Trace: Any + Send + Sync {
44    fn make_binary(&mut self, kind: DataKind, data: &[u8]) -> Data;
45
46    fn make_string(&mut self, kind: DataKind, data: &str) -> Data;
47
48    fn add(&mut self, action: Action<'_, PointerReferences>)
49    where
50        for<'a> Action<'a, PointerReferences>: serde::Serialize;
51}
52
53#[derive(Debug)]
54pub struct DiskTrace {
55    path: std::path::PathBuf,
56    file: std::fs::File,
57    config: ron::ser::PrettyConfig,
58    data_id: usize,
59}
60
61impl DiskTrace {
62    pub fn new(path: std::path::PathBuf) -> Result<Self, std::io::Error> {
63        log::debug!("Tracing into '{path:?}'");
64        let mut file = std::fs::File::create(path.join(FILE_NAME))?;
65        file.write_all(b"[\n")?;
66        Ok(Self {
67            path,
68            file,
69            config: ron::ser::PrettyConfig::default(),
70            data_id: 0,
71        })
72    }
73}
74
75impl Trace for DiskTrace {
76    /// Store `[u8]` data in the trace.
77    ///
78    /// Using a string `kind` is probably a bug, but should work as long as the
79    /// data is UTF-8.
80    fn make_binary(&mut self, kind: DataKind, data: &[u8]) -> Data {
81        self.data_id += 1;
82        let name = std::format!("data{}.{}", self.data_id, kind);
83        let _ = std::fs::write(self.path.join(&name), data);
84        Data::File(name)
85    }
86
87    /// Store `str` data in the trace.
88    ///
89    /// Using a binary `kind` is fine, but it's not clear why not use
90    /// `make_binary` instead.
91    fn make_string(&mut self, kind: DataKind, data: &str) -> Data {
92        self.make_binary(kind, data.as_bytes())
93    }
94
95    fn add(&mut self, action: Action<'_, PointerReferences>)
96    where
97        for<'a> Action<'a, PointerReferences>: serde::Serialize,
98    {
99        match ron::ser::to_string_pretty(&action, self.config.clone()) {
100            Ok(string) => {
101                let _ = writeln!(self.file, "{string},");
102            }
103            Err(e) => {
104                log::warn!("RON serialization failure: {e:?}");
105            }
106        }
107    }
108}
109
110impl Drop for DiskTrace {
111    fn drop(&mut self) {
112        let _ = self.file.write_all(b"]");
113    }
114}
115
116#[derive(Default)]
117pub struct MemoryTrace {
118    actions: Vec<Action<'static, PointerReferences>>,
119}
120
121impl MemoryTrace {
122    pub fn new() -> Self {
123        Self::default()
124    }
125
126    pub fn actions(&self) -> &[Action<'static, PointerReferences>] {
127        &self.actions
128    }
129}
130
131impl Trace for MemoryTrace {
132    /// Store `[u8]` data in the trace.
133    ///
134    /// Using a string `kind` is probably a bug, but should work as long as the
135    /// data is UTF-8.
136    fn make_binary(&mut self, kind: DataKind, data: &[u8]) -> Data {
137        Data::Binary(kind, data.to_vec())
138    }
139
140    /// Store `str` data in the trace.
141    ///
142    /// Using a binary `kind` is fine, but it's not clear why not use
143    /// `make_binary` instead.
144    fn make_string(&mut self, kind: DataKind, data: &str) -> Data {
145        Data::String(kind, data.to_string())
146    }
147
148    fn add(&mut self, action: Action<'_, PointerReferences>)
149    where
150        for<'a> Action<'a, PointerReferences>: serde::Serialize,
151    {
152        self.actions.push(action_to_owned(action))
153    }
154}
155
156pub(crate) trait IntoTrace {
157    type Output;
158    fn into_trace(self) -> Self::Output;
159
160    fn to_trace(&self) -> Self::Output
161    where
162        Self: Sized + Clone,
163    {
164        self.clone().into_trace()
165    }
166}
167
168impl<T: StorageItem> IntoTrace for Arc<T> {
169    type Output = PointerId<T::Marker>;
170    fn into_trace(self) -> Self::Output {
171        self.to_trace()
172    }
173
174    fn to_trace(&self) -> Self::Output {
175        PointerId::from(self)
176    }
177}
178
179/// This will work as expected on heap-allocated types that are not moved around.
180pub(crate) unsafe fn to_trace<T: StorageItem>(t: &T) -> PointerId<T::Marker> {
181    PointerId::PointerId(
182        #[expect(trivial_casts)]
183        core::num::NonZeroUsize::new(t as *const T as usize).unwrap(),
184        PhantomData,
185    )
186}
187
188impl IntoTrace for ArcCommand {
189    type Output = Command<PointerReferences>;
190    fn into_trace(self) -> Self::Output {
191        match self {
192            ArcCommand::CopyBufferToBuffer {
193                src,
194                src_offset,
195                dst,
196                dst_offset,
197                size,
198            } => Command::CopyBufferToBuffer {
199                src: src.to_trace(),
200                src_offset,
201                dst: dst.to_trace(),
202                dst_offset,
203                size,
204            },
205            ArcCommand::CopyBufferToTexture { src, dst, size } => Command::CopyBufferToTexture {
206                src: src.into_trace(),
207                dst: dst.into_trace(),
208                size,
209            },
210            ArcCommand::CopyTextureToBuffer { src, dst, size } => Command::CopyTextureToBuffer {
211                src: src.into_trace(),
212                dst: dst.into_trace(),
213                size,
214            },
215            ArcCommand::CopyTextureToTexture { src, dst, size } => Command::CopyTextureToTexture {
216                src: src.into_trace(),
217                dst: dst.into_trace(),
218                size,
219            },
220            ArcCommand::ClearBuffer { dst, offset, size } => Command::ClearBuffer {
221                dst: dst.to_trace(),
222                offset,
223                size,
224            },
225            ArcCommand::ClearTexture {
226                dst,
227                subresource_range,
228            } => Command::ClearTexture {
229                dst: dst.to_trace(),
230                subresource_range,
231            },
232            ArcCommand::WriteTimestamp {
233                query_set,
234                query_index,
235            } => Command::WriteTimestamp {
236                query_set: query_set.to_trace(),
237                query_index,
238            },
239            ArcCommand::ResolveQuerySet {
240                query_set,
241                start_query,
242                query_count,
243                destination,
244                destination_offset,
245            } => Command::ResolveQuerySet {
246                query_set: query_set.to_trace(),
247                start_query,
248                query_count,
249                destination: destination.to_trace(),
250                destination_offset,
251            },
252            ArcCommand::PushDebugGroup(label) => Command::PushDebugGroup(label),
253            ArcCommand::PopDebugGroup => Command::PopDebugGroup,
254            ArcCommand::InsertDebugMarker(label) => Command::InsertDebugMarker(label),
255            ArcCommand::RunComputePass {
256                pass,
257                timestamp_writes,
258            } => Command::RunComputePass {
259                pass: pass.into_trace(),
260                timestamp_writes: timestamp_writes.map(|tw| tw.into_trace()),
261            },
262            ArcCommand::RunRenderPass {
263                pass,
264                color_attachments,
265                depth_stencil_attachment,
266                timestamp_writes,
267                occlusion_query_set,
268                multiview_mask,
269            } => Command::RunRenderPass {
270                pass: pass.into_trace(),
271                color_attachments: color_attachments.into_trace(),
272                depth_stencil_attachment: depth_stencil_attachment.map(|d| d.into_trace()),
273                timestamp_writes: timestamp_writes.map(|tw| tw.into_trace()),
274                occlusion_query_set: occlusion_query_set.map(|q| q.to_trace()),
275                multiview_mask,
276            },
277            ArcCommand::RunRayTracingPass { pass } => Command::RunRayTracingPass {
278                pass: pass.into_trace(),
279            },
280            ArcCommand::BuildAccelerationStructures { blas, tlas } => {
281                Command::BuildAccelerationStructures {
282                    blas: blas.into_iter().map(|b| b.into_trace()).collect(),
283                    tlas: tlas.into_iter().map(|b| b.into_trace()).collect(),
284                }
285            }
286            ArcCommand::TransitionResources {
287                buffer_transitions: _,
288                texture_transitions: _,
289            } => {
290                // TransitionResources does not exist in Command, so skip or handle as needed.
291                // If you want to ignore, you could panic or return a default.
292                panic!("TransitionResources cannot be converted to Command");
293            }
294        }
295    }
296}
297
298impl<T: IntoTrace> IntoTrace for wgt::TexelCopyBufferInfo<T> {
299    type Output = wgt::TexelCopyBufferInfo<T::Output>;
300    fn into_trace(self) -> Self::Output {
301        wgt::TexelCopyBufferInfo {
302            buffer: self.buffer.into_trace(),
303            layout: self.layout,
304        }
305    }
306}
307
308impl<T: IntoTrace> IntoTrace for wgt::TexelCopyTextureInfo<T> {
309    type Output = wgt::TexelCopyTextureInfo<T::Output>;
310    fn into_trace(self) -> Self::Output {
311        wgt::TexelCopyTextureInfo {
312            texture: self.texture.into_trace(),
313            mip_level: self.mip_level,
314            origin: self.origin,
315            aspect: self.aspect,
316        }
317    }
318}
319
320impl IntoTrace for PassTimestampWrites {
321    type Output = PassTimestampWrites<PointerId<markers::QuerySet>>;
322    fn into_trace(self) -> Self::Output {
323        PassTimestampWrites {
324            query_set: self.query_set.into_trace(),
325            beginning_of_pass_write_index: self.beginning_of_pass_write_index,
326            end_of_pass_write_index: self.end_of_pass_write_index,
327        }
328    }
329}
330
331impl IntoTrace for ColorAttachments {
332    type Output = ColorAttachments<PointerId<markers::TextureView>>;
333    fn into_trace(self) -> Self::Output {
334        self.into_iter()
335            .map(|opt| {
336                opt.map(|att| RenderPassColorAttachment {
337                    view: att.view.into_trace(),
338                    depth_slice: att.depth_slice,
339                    resolve_target: att.resolve_target.map(|r| r.into_trace()),
340                    load_op: att.load_op,
341                    store_op: att.store_op,
342                })
343            })
344            .collect()
345    }
346}
347
348impl<TV: IntoTrace> IntoTrace for ResolvedRenderPassDepthStencilAttachment<TV> {
349    type Output = ResolvedRenderPassDepthStencilAttachment<TV::Output>;
350    fn into_trace(self) -> Self::Output {
351        ResolvedRenderPassDepthStencilAttachment {
352            view: self.view.into_trace(),
353            depth: self.depth,
354            stencil: self.stencil,
355        }
356    }
357}
358
359impl IntoTrace for crate::ray_tracing::OwnedBlasBuildEntry<ArcReferences> {
360    type Output = crate::ray_tracing::OwnedBlasBuildEntry<PointerReferences>;
361    fn into_trace(self) -> Self::Output {
362        crate::ray_tracing::OwnedBlasBuildEntry {
363            blas: self.blas.into_trace(),
364            geometries: self.geometries.into_trace(),
365        }
366    }
367}
368
369impl IntoTrace for crate::ray_tracing::OwnedBlasGeometries<ArcReferences> {
370    type Output = crate::ray_tracing::OwnedBlasGeometries<PointerReferences>;
371    fn into_trace(self) -> Self::Output {
372        match self {
373            crate::ray_tracing::OwnedBlasGeometries::TriangleGeometries(geos) => {
374                crate::ray_tracing::OwnedBlasGeometries::TriangleGeometries(
375                    geos.into_iter().map(|g| g.into_trace()).collect(),
376                )
377            }
378            crate::ray_tracing::OwnedBlasGeometries::AabbGeometries(geos) => {
379                crate::ray_tracing::OwnedBlasGeometries::AabbGeometries(
380                    geos.into_iter().map(|g| g.into_trace()).collect(),
381                )
382            }
383        }
384    }
385}
386
387impl IntoTrace for crate::ray_tracing::OwnedBlasTriangleGeometry<ArcReferences> {
388    type Output = crate::ray_tracing::OwnedBlasTriangleGeometry<PointerReferences>;
389    fn into_trace(self) -> Self::Output {
390        crate::ray_tracing::OwnedBlasTriangleGeometry {
391            size: self.size,
392            vertex_buffer: self.vertex_buffer.into_trace(),
393            index_buffer: self.index_buffer.map(|b| b.into_trace()),
394            transform_buffer: self.transform_buffer.map(|b| b.into_trace()),
395            first_vertex: self.first_vertex,
396            vertex_stride: self.vertex_stride,
397            first_index: self.first_index,
398            transform_buffer_offset: self.transform_buffer_offset,
399        }
400    }
401}
402
403impl IntoTrace for crate::ray_tracing::OwnedBlasAabbGeometry<ArcReferences> {
404    type Output = crate::ray_tracing::OwnedBlasAabbGeometry<PointerReferences>;
405    fn into_trace(self) -> Self::Output {
406        crate::ray_tracing::OwnedBlasAabbGeometry {
407            size: self.size,
408            stride: self.stride,
409            aabb_buffer: self.aabb_buffer.into_trace(),
410            primitive_offset: self.primitive_offset,
411        }
412    }
413}
414
415impl IntoTrace for crate::ray_tracing::OwnedTlasPackage<ArcReferences> {
416    type Output = crate::ray_tracing::OwnedTlasPackage<PointerReferences>;
417    fn into_trace(self) -> Self::Output {
418        crate::ray_tracing::OwnedTlasPackage {
419            tlas: self.tlas.into_trace(),
420            instances: self
421                .instances
422                .into_iter()
423                .map(|opt| opt.map(|inst| inst.into_trace()))
424                .collect(),
425            lowest_unmodified: self.lowest_unmodified,
426        }
427    }
428}
429
430impl IntoTrace for crate::ray_tracing::OwnedTlasInstance<ArcReferences> {
431    type Output = crate::ray_tracing::OwnedTlasInstance<PointerReferences>;
432    fn into_trace(self) -> Self::Output {
433        crate::ray_tracing::OwnedTlasInstance {
434            blas: self.blas.into_trace(),
435            transform: self.transform,
436            custom_data: self.custom_data,
437            mask: self.mask,
438            intersection_index: self.intersection_index,
439        }
440    }
441}
442
443impl<C: IntoTrace> IntoTrace for BasePass<C, Infallible> {
444    type Output = BasePass<C::Output, Infallible>;
445
446    fn into_trace(self) -> Self::Output {
447        BasePass {
448            label: self.label,
449            error: self.error,
450            commands: self
451                .commands
452                .into_iter()
453                .map(|cmd| cmd.into_trace())
454                .collect(),
455            dynamic_offsets: self.dynamic_offsets,
456            string_data: self.string_data,
457        }
458    }
459}
460
461impl IntoTrace for ArcComputeCommand {
462    type Output = ComputeCommand<PointerReferences>;
463    fn into_trace(self) -> Self::Output {
464        use ComputeCommand as C;
465        match self {
466            C::SetBindGroup {
467                index,
468                num_dynamic_offsets,
469                bind_group,
470            } => C::SetBindGroup {
471                index,
472                num_dynamic_offsets,
473                bind_group: bind_group.map(|bg| bg.into_trace()),
474            },
475            C::SetPipeline(id) => C::SetPipeline(id.into_trace()),
476            C::SetImmediate { offset, data } => C::SetImmediate { offset, data },
477            C::DispatchWorkgroups(groups) => C::DispatchWorkgroups(groups),
478            C::DispatchWorkgroupsIndirect { buffer, offset } => C::DispatchWorkgroupsIndirect {
479                buffer: buffer.into_trace(),
480                offset,
481            },
482            C::PushDebugGroup { color, len } => C::PushDebugGroup { color, len },
483            C::PopDebugGroup => C::PopDebugGroup,
484            C::InsertDebugMarker { color, len } => C::InsertDebugMarker { color, len },
485            C::WriteTimestamp {
486                query_set,
487                query_index,
488            } => C::WriteTimestamp {
489                query_set: query_set.into_trace(),
490                query_index,
491            },
492            C::BeginPipelineStatisticsQuery {
493                query_set,
494                query_index,
495            } => C::BeginPipelineStatisticsQuery {
496                query_set: query_set.into_trace(),
497                query_index,
498            },
499            C::EndPipelineStatisticsQuery => C::EndPipelineStatisticsQuery,
500            C::TransitionResources {
501                buffer_transitions,
502                texture_transitions,
503            } => C::TransitionResources {
504                buffer_transitions: buffer_transitions
505                    .into_iter()
506                    .map(|buffer_transition| wgt::BufferTransition {
507                        buffer: buffer_transition.buffer.into_trace(),
508                        state: buffer_transition.state,
509                    })
510                    .collect(),
511                texture_transitions: texture_transitions
512                    .into_iter()
513                    .map(|texture_transition| wgt::TextureTransition {
514                        texture: texture_transition.texture.into_trace(),
515                        selector: texture_transition.selector,
516                        state: texture_transition.state,
517                    })
518                    .collect(),
519            },
520        }
521    }
522}
523
524impl IntoTrace for ArcRenderCommand {
525    type Output = RenderCommand<PointerReferences>;
526    fn into_trace(self) -> Self::Output {
527        use RenderCommand as C;
528        match self {
529            C::SetBindGroup {
530                index,
531                num_dynamic_offsets,
532                bind_group,
533            } => C::SetBindGroup {
534                index,
535                num_dynamic_offsets,
536                bind_group: bind_group.map(|bg| bg.into_trace()),
537            },
538            C::SetPipeline(id) => C::SetPipeline(id.into_trace()),
539            C::SetIndexBuffer {
540                buffer,
541                index_format,
542                offset,
543                size,
544            } => C::SetIndexBuffer {
545                buffer: buffer.into_trace(),
546                index_format,
547                offset,
548                size,
549            },
550            C::SetVertexBuffer {
551                slot,
552                buffer,
553                offset,
554                size,
555            } => C::SetVertexBuffer {
556                slot,
557                buffer: buffer.into_trace(),
558                offset,
559                size,
560            },
561            C::SetBlendConstant(color) => C::SetBlendConstant(color),
562            C::SetStencilReference(val) => C::SetStencilReference(val),
563            C::SetViewport {
564                rect,
565                depth_min,
566                depth_max,
567            } => C::SetViewport {
568                rect,
569                depth_min,
570                depth_max,
571            },
572            C::SetScissor(rect) => C::SetScissor(rect),
573            C::SetImmediate { offset, data } => C::SetImmediate { offset, data },
574            C::Draw {
575                vertex_count,
576                instance_count,
577                first_vertex,
578                first_instance,
579            } => C::Draw {
580                vertex_count,
581                instance_count,
582                first_vertex,
583                first_instance,
584            },
585            C::DrawIndexed {
586                index_count,
587                instance_count,
588                first_index,
589                base_vertex,
590                first_instance,
591            } => C::DrawIndexed {
592                index_count,
593                instance_count,
594                first_index,
595                base_vertex,
596                first_instance,
597            },
598            C::DrawMeshTasks {
599                group_count_x,
600                group_count_y,
601                group_count_z,
602            } => C::DrawMeshTasks {
603                group_count_x,
604                group_count_y,
605                group_count_z,
606            },
607            C::DrawIndirect {
608                buffer,
609                offset,
610                count,
611                family,
612                vertex_or_index_limit,
613                instance_limit,
614            } => C::DrawIndirect {
615                buffer: buffer.into_trace(),
616                offset,
617                count,
618                family,
619                vertex_or_index_limit,
620                instance_limit,
621            },
622            C::MultiDrawIndirectCount {
623                buffer,
624                offset,
625                count_buffer,
626                count_buffer_offset,
627                max_count,
628                family,
629            } => C::MultiDrawIndirectCount {
630                buffer: buffer.into_trace(),
631                offset,
632                count_buffer: count_buffer.into_trace(),
633                count_buffer_offset,
634                max_count,
635                family,
636            },
637            C::PushDebugGroup { color, len } => C::PushDebugGroup { color, len },
638            C::PopDebugGroup => C::PopDebugGroup,
639            C::InsertDebugMarker { color, len } => C::InsertDebugMarker { color, len },
640            C::WriteTimestamp {
641                query_set,
642                query_index,
643            } => C::WriteTimestamp {
644                query_set: query_set.into_trace(),
645                query_index,
646            },
647            C::BeginOcclusionQuery { query_index } => C::BeginOcclusionQuery { query_index },
648            C::EndOcclusionQuery => C::EndOcclusionQuery,
649            C::BeginPipelineStatisticsQuery {
650                query_set,
651                query_index,
652            } => C::BeginPipelineStatisticsQuery {
653                query_set: query_set.into_trace(),
654                query_index,
655            },
656            C::EndPipelineStatisticsQuery => C::EndPipelineStatisticsQuery,
657            C::ExecuteBundle(bundle) => C::ExecuteBundle(bundle.into_trace()),
658        }
659    }
660}
661
662impl IntoTrace for ArcRayTracingCommand {
663    type Output = RayTracingCommand<PointerReferences>;
664    fn into_trace(self) -> Self::Output {
665        use RayTracingCommand as C;
666        match self {
667            C::SetBindGroup {
668                index,
669                num_dynamic_offsets,
670                bind_group,
671            } => C::SetBindGroup {
672                index,
673                num_dynamic_offsets,
674                bind_group: bind_group.map(|bg| bg.into_trace()),
675            },
676            C::SetPipeline(id) => C::SetPipeline(id.into_trace()),
677            C::SetImmediate { offset, data } => C::SetImmediate { offset, data },
678            C::TraceRays(groups) => C::TraceRays(groups),
679            C::PushDebugGroup { color, len } => C::PushDebugGroup { color, len },
680            C::PopDebugGroup => C::PopDebugGroup,
681            C::InsertDebugMarker { color, len } => C::InsertDebugMarker { color, len },
682        }
683    }
684}
685
686impl IntoTrace for crate::binding_model::PipelineLayoutDescriptor<'_> {
687    type Output = crate::binding_model::PipelineLayoutDescriptor<
688        'static,
689        PointerId<markers::BindGroupLayout>,
690    >;
691    fn into_trace(self) -> Self::Output {
692        crate::binding_model::PipelineLayoutDescriptor {
693            label: self.label.map(|l| Cow::Owned(l.into_owned())),
694            bind_group_layouts: self
695                .bind_group_layouts
696                .iter()
697                .map(|bgl| bgl.to_trace())
698                .collect(),
699            immediate_size: self.immediate_size,
700        }
701    }
702}
703
704impl<'a> IntoTrace for &'_ crate::binding_model::BindGroupDescriptor<'a> {
705    type Output = TraceBindGroupDescriptor<'a>;
706
707    fn into_trace(self) -> Self::Output {
708        use crate::binding_model::{BindGroupEntry, BindingResource, BufferBinding};
709        TraceBindGroupDescriptor {
710            label: self.label.clone(),
711            layout: self.layout.to_trace(),
712            entries: Cow::Owned(
713                self.entries
714                    .iter()
715                    .map(|entry| {
716                        let resource = match &entry.resource {
717                            BindingResource::Buffer(buffer_binding) => {
718                                BindingResource::Buffer(BufferBinding {
719                                    buffer: buffer_binding.buffer.to_trace(),
720                                    offset: buffer_binding.offset,
721                                    size: buffer_binding.size,
722                                })
723                            }
724                            BindingResource::BufferArray(buffer_bindings) => {
725                                let resolved_buffers: Vec<_> = buffer_bindings
726                                    .iter()
727                                    .map(|bb| BufferBinding {
728                                        buffer: bb.buffer.to_trace(),
729                                        offset: bb.offset,
730                                        size: bb.size,
731                                    })
732                                    .collect();
733                                BindingResource::BufferArray(Cow::Owned(resolved_buffers))
734                            }
735                            BindingResource::Sampler(sampler_id) => {
736                                BindingResource::Sampler(sampler_id.to_trace())
737                            }
738                            BindingResource::SamplerArray(sampler_ids) => {
739                                let resolved: Vec<_> =
740                                    sampler_ids.iter().map(|id| id.to_trace()).collect();
741                                BindingResource::SamplerArray(Cow::Owned(resolved))
742                            }
743                            BindingResource::TextureView(texture_view_id) => {
744                                BindingResource::TextureView(texture_view_id.to_trace())
745                            }
746                            BindingResource::TextureViewArray(texture_view_ids) => {
747                                let resolved: Vec<_> =
748                                    texture_view_ids.iter().map(|id| id.to_trace()).collect();
749                                BindingResource::TextureViewArray(Cow::Owned(resolved))
750                            }
751                            BindingResource::AccelerationStructure(tlas_id) => {
752                                BindingResource::AccelerationStructure(tlas_id.to_trace())
753                            }
754                            BindingResource::AccelerationStructureArray(tlas_ids) => {
755                                let resolved: Vec<_> =
756                                    tlas_ids.iter().map(|id| id.to_trace()).collect();
757                                BindingResource::AccelerationStructureArray(Cow::Owned(resolved))
758                            }
759                            BindingResource::ExternalTexture(external_texture_id) => {
760                                BindingResource::ExternalTexture(external_texture_id.to_trace())
761                            }
762                        };
763                        BindGroupEntry {
764                            binding: entry.binding,
765                            resource,
766                        }
767                    })
768                    .collect(),
769            ),
770        }
771    }
772}
773
774impl<'a> IntoTrace for crate::pipeline::ResolvedGeneralRenderPipelineDescriptor<'a> {
775    type Output = TraceGeneralRenderPipelineDescriptor<'a>;
776
777    fn into_trace(self) -> Self::Output {
778        TraceGeneralRenderPipelineDescriptor {
779            label: self.label,
780            layout: self.layout.into_trace(),
781            vertex: self.vertex.into_trace(),
782            primitive: self.primitive,
783            depth_stencil: self.depth_stencil,
784            multisample: self.multisample,
785            fragment: self.fragment.map(|f| f.into_trace()),
786            multiview_mask: self.multiview_mask,
787            cache: self.cache.map(|c| c.into_trace()),
788        }
789    }
790}
791
792impl<'a> IntoTrace for crate::pipeline::ComputePipelineDescriptor<'a> {
793    type Output = TraceComputePipelineDescriptor<'a>;
794
795    fn into_trace(self) -> Self::Output {
796        TraceComputePipelineDescriptor {
797            label: self.label,
798            layout: self.layout.into_trace(),
799            stage: self.stage.into_trace(),
800            cache: self.cache.map(|c| c.into_trace()),
801        }
802    }
803}
804
805impl<'a> IntoTrace for crate::ray_tracing_pipeline::RayTracingPipelineDescriptor<'a> {
806    type Output = TraceRayTracingPipelineDescriptor<'a>;
807
808    fn into_trace(self) -> Self::Output {
809        TraceRayTracingPipelineDescriptor {
810            label: self.label,
811            layout: self.layout.into_trace(),
812            ray_generation: self.ray_generation.into_trace(),
813            miss: self.miss.into_trace(),
814            intersections: self
815                .intersections
816                .into_iter()
817                .map(|intersection| match intersection {
818                    crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
819                        closest_hit,
820                        any_hit,
821                    } => crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
822                        closest_hit: closest_hit.into_trace(),
823                        any_hit: any_hit.map(|a| a.into_trace()),
824                    },
825                })
826                .collect(),
827            cache: self.cache.map(|c| c.into_trace()),
828            max_recursion_depth: self.max_recursion_depth,
829        }
830    }
831}
832
833impl<'a> IntoTrace for crate::pipeline::ProgrammableStageDescriptor<'a> {
834    type Output =
835        crate::pipeline::ProgrammableStageDescriptor<'a, PointerId<markers::ShaderModule>>;
836    fn into_trace(self) -> Self::Output {
837        crate::pipeline::ProgrammableStageDescriptor {
838            module: self.module.into_trace(),
839            entry_point: self.entry_point,
840            constants: self.constants,
841            zero_initialize_workgroup_memory: self.zero_initialize_workgroup_memory,
842        }
843    }
844}
845
846impl<'a> IntoTrace
847    for crate::pipeline::RenderPipelineVertexProcessor<'a, Arc<crate::pipeline::ShaderModule>>
848{
849    type Output =
850        crate::pipeline::RenderPipelineVertexProcessor<'a, PointerId<markers::ShaderModule>>;
851    fn into_trace(self) -> Self::Output {
852        match self {
853            crate::pipeline::RenderPipelineVertexProcessor::Vertex(vertex) => {
854                crate::pipeline::RenderPipelineVertexProcessor::Vertex(vertex.into_trace())
855            }
856            crate::pipeline::RenderPipelineVertexProcessor::Mesh(task, mesh) => {
857                crate::pipeline::RenderPipelineVertexProcessor::Mesh(
858                    task.map(|t| t.into_trace()),
859                    mesh.into_trace(),
860                )
861            }
862        }
863    }
864}
865
866impl<'a> IntoTrace for crate::pipeline::TaskState<'a> {
867    type Output = crate::pipeline::TaskState<'a, PointerId<markers::ShaderModule>>;
868    fn into_trace(self) -> Self::Output {
869        crate::pipeline::TaskState {
870            stage: self.stage.into_trace(),
871        }
872    }
873}
874
875impl<'a> IntoTrace for crate::pipeline::MeshState<'a> {
876    type Output = crate::pipeline::MeshState<'a, PointerId<markers::ShaderModule>>;
877    fn into_trace(self) -> Self::Output {
878        crate::pipeline::MeshState {
879            stage: self.stage.into_trace(),
880        }
881    }
882}
883
884impl<'a> IntoTrace for crate::pipeline::VertexState<'a> {
885    type Output = crate::pipeline::VertexState<'a, PointerId<markers::ShaderModule>>;
886    fn into_trace(self) -> Self::Output {
887        crate::pipeline::VertexState {
888            stage: self.stage.into_trace(),
889            buffers: self.buffers,
890        }
891    }
892}
893
894impl<'a> IntoTrace for crate::pipeline::FragmentState<'a> {
895    type Output = crate::pipeline::FragmentState<'a, PointerId<markers::ShaderModule>>;
896    fn into_trace(self) -> Self::Output {
897        crate::pipeline::FragmentState {
898            stage: self.stage.into_trace(),
899            targets: self.targets,
900        }
901    }
902}
903
904impl<T: IntoTrace> IntoTrace for Option<T> {
905    type Output = Option<T::Output>;
906    fn into_trace(self) -> Self::Output {
907        self.map(|v| v.into_trace())
908    }
909}
910
911impl<'a, BGLE> IntoTrace for crate::binding_model::BindGroupLayoutDescriptor<'a, BGLE>
912where
913    BGLE: Copy,
914    BGLE: Into<crate::binding_model::BindGroupLayoutEntry>,
915{
916    type Output = crate::binding_model::BindGroupLayoutDescriptor<
917        'static,
918        crate::binding_model::BindGroupLayoutEntry,
919    >;
920
921    fn into_trace(self) -> Self::Output {
922        crate::binding_model::BindGroupLayoutDescriptor {
923            label: self.label.map(|l| Cow::Owned(l.into_owned())),
924            entries: Cow::Owned(self.entries.iter().map(|&e| e.into()).collect()),
925        }
926    }
927}
928
929/// Return a copy of [`Action`] with `'static` lifetime.
930///
931/// This is used for in-memory tracing.
932fn action_to_owned(action: Action<'_, PointerReferences>) -> Action<'static, PointerReferences> {
933    use Action as A;
934    match action {
935        A::Init { desc, backend } => A::Init {
936            desc: desc.map_label(owned_label),
937            backend,
938        },
939        A::ConfigureSurface(surface, config) => A::ConfigureSurface(surface, config),
940        A::CreateBuffer(buffer, desc) => A::CreateBuffer(buffer, desc.map_label(owned_label)),
941        A::DestroyBuffer(buffer) => A::DestroyBuffer(buffer),
942        A::DropBuffer(buffer) => A::DropBuffer(buffer),
943        A::DestroyTexture(texture) => A::DestroyTexture(texture),
944        A::DropTexture(texture) => A::DropTexture(texture),
945        A::DropTextureView(texture_view) => A::DropTextureView(texture_view),
946        A::DestroyExternalTexture(external_texture) => A::DestroyExternalTexture(external_texture),
947        A::DropExternalTexture(external_texture) => A::DropExternalTexture(external_texture),
948        A::DropSampler(sampler) => A::DropSampler(sampler),
949        A::GetSurfaceTexture { id, parent } => A::GetSurfaceTexture { id, parent },
950        A::Present(surface) => A::Present(surface),
951        A::DiscardSurfaceTexture(surface) => A::DiscardSurfaceTexture(surface),
952        A::ReleaseSurfaceTexture(surface) => A::ReleaseSurfaceTexture(surface),
953        A::DropBindGroupLayout(layout) => A::DropBindGroupLayout(layout),
954        A::GetRenderPipelineBindGroupLayout {
955            id,
956            pipeline,
957            index,
958        } => A::GetRenderPipelineBindGroupLayout {
959            id,
960            pipeline,
961            index,
962        },
963        A::GetComputePipelineBindGroupLayout {
964            id,
965            pipeline,
966            index,
967        } => A::GetComputePipelineBindGroupLayout {
968            id,
969            pipeline,
970            index,
971        },
972        A::GetRayTracingPipelineBindGroupLayout {
973            id,
974            pipeline,
975            index,
976        } => A::GetRayTracingPipelineBindGroupLayout {
977            id,
978            pipeline,
979            index,
980        },
981        A::DropPipelineLayout(layout) => A::DropPipelineLayout(layout),
982        A::DropBindGroup(bind_group) => A::DropBindGroup(bind_group),
983        A::DropShaderModule(shader_module) => A::DropShaderModule(shader_module),
984        A::DropComputePipeline(pipeline) => A::DropComputePipeline(pipeline),
985        A::DropRenderPipeline(pipeline) => A::DropRenderPipeline(pipeline),
986        A::DropRayTracingPipeline(pipeline) => A::DropRayTracingPipeline(pipeline),
987        A::DropPipelineCache(cache) => A::DropPipelineCache(cache),
988        A::DropRenderBundle(render_bundle) => A::DropRenderBundle(render_bundle),
989        A::DestroyQuerySet(query_set) => A::DestroyQuerySet(query_set),
990        A::DropQuerySet(query_set) => A::DropQuerySet(query_set),
991        A::WriteBuffer {
992            id,
993            data,
994            offset,
995            size,
996            queued,
997        } => A::WriteBuffer {
998            id,
999            data,
1000            offset,
1001            size,
1002            queued,
1003        },
1004        A::WriteTexture {
1005            to,
1006            data,
1007            layout,
1008            size,
1009        } => A::WriteTexture {
1010            to,
1011            data,
1012            layout,
1013            size,
1014        },
1015        A::Submit(index, commands) => A::Submit(index, commands),
1016        A::FailedCommands {
1017            commands,
1018            failed_at_submit,
1019            error,
1020        } => A::FailedCommands {
1021            commands,
1022            failed_at_submit,
1023            error,
1024        },
1025        A::DropBlas(blas) => A::DropBlas(blas),
1026        A::DropTlas(tlas) => A::DropTlas(tlas),
1027
1028        A::CreateTexture(id, desc) => A::CreateTexture(id, desc.map_label(owned_label)),
1029        A::CreateTextureError(id, desc) => A::CreateTextureError(id, desc.map_label(owned_label)),
1030        A::CreateTextureView { id, parent, desc } => A::CreateTextureView {
1031            id,
1032            parent,
1033            desc: crate::resource::TextureViewDescriptor {
1034                label: owned_label(&desc.label),
1035                format: desc.format,
1036                dimension: desc.dimension,
1037                usage: desc.usage,
1038                range: desc.range,
1039                swizzle: desc.swizzle,
1040            },
1041        },
1042        A::CreateExternalTexture { id, desc, planes } => A::CreateExternalTexture {
1043            id,
1044            desc: desc.map_label(owned_label),
1045            planes,
1046        },
1047        A::CreateSampler(id, desc) => A::CreateSampler(
1048            id,
1049            crate::resource::SamplerDescriptor {
1050                label: owned_label(&desc.label),
1051                address_modes: desc.address_modes,
1052                mag_filter: desc.mag_filter,
1053                min_filter: desc.min_filter,
1054                mipmap_filter: desc.mipmap_filter,
1055                lod_min_clamp: desc.lod_min_clamp,
1056                lod_max_clamp: desc.lod_max_clamp,
1057                compare: desc.compare,
1058                anisotropy_clamp: desc.anisotropy_clamp,
1059                border_color: desc.border_color,
1060            },
1061        ),
1062        A::CreateBindGroupLayout(id, desc) => A::CreateBindGroupLayout(
1063            id,
1064            crate::binding_model::BindGroupLayoutDescriptor {
1065                label: owned_label(&desc.label),
1066                entries: Cow::Owned(desc.entries.into_owned()),
1067            },
1068        ),
1069        A::CreatePipelineLayout(id, desc) => A::CreatePipelineLayout(
1070            id,
1071            crate::binding_model::PipelineLayoutDescriptor {
1072                label: owned_label(&desc.label),
1073                bind_group_layouts: Cow::Owned(desc.bind_group_layouts.into_owned()),
1074                immediate_size: desc.immediate_size,
1075            },
1076        ),
1077        A::CreateBindGroup(id, desc) => A::CreateBindGroup(
1078            id,
1079            crate::binding_model::BindGroupDescriptor {
1080                label: owned_label(&desc.label),
1081                layout: desc.layout,
1082                entries: desc
1083                    .entries
1084                    .iter()
1085                    .map(|e| crate::binding_model::BindGroupEntry {
1086                        binding: e.binding,
1087                        resource: match &e.resource {
1088                            crate::binding_model::BindingResource::Buffer(buffer_binding) => {
1089                                crate::binding_model::BindingResource::Buffer(
1090                                    buffer_binding.clone(),
1091                                )
1092                            }
1093                            crate::binding_model::BindingResource::BufferArray(cow) => {
1094                                crate::binding_model::BindingResource::BufferArray(Cow::Owned(
1095                                    cow.clone().into_owned(),
1096                                ))
1097                            }
1098                            crate::binding_model::BindingResource::Sampler(sampler) => {
1099                                crate::binding_model::BindingResource::Sampler(*sampler)
1100                            }
1101                            crate::binding_model::BindingResource::SamplerArray(cow) => {
1102                                crate::binding_model::BindingResource::SamplerArray(Cow::Owned(
1103                                    cow.clone().into_owned(),
1104                                ))
1105                            }
1106                            crate::binding_model::BindingResource::TextureView(texture_view) => {
1107                                crate::binding_model::BindingResource::TextureView(*texture_view)
1108                            }
1109                            crate::binding_model::BindingResource::TextureViewArray(cow) => {
1110                                crate::binding_model::BindingResource::TextureViewArray(Cow::Owned(
1111                                    cow.clone().into_owned(),
1112                                ))
1113                            }
1114                            crate::binding_model::BindingResource::AccelerationStructure(
1115                                acceleration_structure,
1116                            ) => crate::binding_model::BindingResource::AccelerationStructure(
1117                                *acceleration_structure,
1118                            ),
1119                            crate::binding_model::BindingResource::AccelerationStructureArray(
1120                                cow,
1121                            ) => crate::binding_model::BindingResource::AccelerationStructureArray(
1122                                Cow::Owned(cow.clone().into_owned()),
1123                            ),
1124                            crate::binding_model::BindingResource::ExternalTexture(
1125                                external_texture,
1126                            ) => crate::binding_model::BindingResource::ExternalTexture(
1127                                *external_texture,
1128                            ),
1129                        },
1130                    })
1131                    .collect(),
1132            },
1133        ),
1134        A::CreateShaderModule { id, desc, data } => A::CreateShaderModule {
1135            id,
1136            desc: crate::pipeline::ShaderModuleDescriptor {
1137                label: owned_label(&desc.label),
1138                runtime_checks: desc.runtime_checks,
1139            },
1140            data,
1141        },
1142        A::CreateShaderModulePassthrough {
1143            id,
1144            data,
1145            label,
1146            entry_points,
1147        } => A::CreateShaderModulePassthrough {
1148            id,
1149            data,
1150            label: owned_label(&label),
1151            entry_points: entry_points
1152                .iter()
1153                .map(|ep| wgt::PassthroughShaderEntryPoint {
1154                    name: Cow::Owned(ep.name.to_string()),
1155                    workgroup_size: ep.workgroup_size,
1156                })
1157                .collect(),
1158        },
1159        A::CreateComputePipeline { id, desc } => A::CreateComputePipeline {
1160            id,
1161            desc: crate::pipeline::ComputePipelineDescriptor {
1162                label: owned_label(&desc.label),
1163                layout: desc.layout,
1164                stage: owned_stage(desc.stage),
1165                cache: desc.cache,
1166            },
1167        },
1168        A::CreateGeneralRenderPipeline { id, desc } => A::CreateGeneralRenderPipeline {
1169            id,
1170            desc: crate::pipeline::GeneralRenderPipelineDescriptor {
1171                label: owned_label(&desc.label),
1172                layout: desc.layout,
1173                vertex: match desc.vertex {
1174                    crate::pipeline::RenderPipelineVertexProcessor::Vertex(
1175                        crate::pipeline::VertexState { stage, buffers },
1176                    ) => crate::pipeline::RenderPipelineVertexProcessor::Vertex(
1177                        crate::pipeline::VertexState {
1178                            stage: owned_stage(stage),
1179                            buffers: buffers
1180                                .iter()
1181                                .map(|b| {
1182                                    b.clone().map(|buffer| crate::pipeline::VertexBufferLayout {
1183                                        array_stride: buffer.array_stride,
1184                                        step_mode: buffer.step_mode,
1185                                        attributes: Cow::Owned(buffer.attributes.into_owned()),
1186                                    })
1187                                })
1188                                .collect(),
1189                        },
1190                    ),
1191                    crate::pipeline::RenderPipelineVertexProcessor::Mesh(task, mesh) => {
1192                        crate::pipeline::RenderPipelineVertexProcessor::Mesh(
1193                            task.map(|t| crate::pipeline::TaskState {
1194                                stage: owned_stage(t.stage),
1195                            }),
1196                            crate::pipeline::MeshState {
1197                                stage: owned_stage(mesh.stage),
1198                            },
1199                        )
1200                    }
1201                },
1202                primitive: desc.primitive,
1203                depth_stencil: desc.depth_stencil,
1204                multisample: desc.multisample,
1205                fragment: desc.fragment.map(|f| crate::pipeline::FragmentState {
1206                    stage: owned_stage(f.stage),
1207                    targets: Cow::Owned(f.targets.into_owned()),
1208                }),
1209                multiview_mask: desc.multiview_mask,
1210                cache: desc.cache,
1211            },
1212        },
1213        A::CreateRayTracingPipeline { id, desc } => A::CreateRayTracingPipeline {
1214            id,
1215            desc: crate::ray_tracing_pipeline::RayTracingPipelineDescriptor {
1216                label: owned_label(&desc.label),
1217                layout: desc.layout,
1218                ray_generation: owned_stage(desc.ray_generation),
1219                miss: owned_stage(desc.miss),
1220                intersections: desc
1221                    .intersections
1222                    .into_iter()
1223                    .map(|i| match i {
1224                        crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
1225                            closest_hit,
1226                            any_hit,
1227                        } => crate::ray_tracing_pipeline::RayTracingIntersectionDescriptor::Triangle {
1228                            closest_hit: owned_stage(closest_hit),
1229                            any_hit: any_hit.map(owned_stage),
1230                        },
1231                    })
1232                    .collect::<Vec<_>>(),
1233                max_recursion_depth: desc.max_recursion_depth,
1234                cache: desc.cache,
1235            },
1236        },
1237        A::CreatePipelineCache { id, desc } => A::CreatePipelineCache {
1238            id,
1239            desc: crate::pipeline::PipelineCacheDescriptor {
1240                label: owned_label(&desc.label),
1241                data: desc.data.map(|d| Cow::Owned(d.to_vec())),
1242                fallback: desc.fallback,
1243            },
1244        },
1245        A::CreateRenderBundle { id, desc, base } => A::CreateRenderBundle {
1246            id,
1247            desc: crate::command::RenderBundleEncoderDescriptor {
1248                label: owned_label(&desc.label),
1249                color_formats: Cow::Owned(desc.color_formats.into_owned()),
1250                depth_stencil: desc.depth_stencil,
1251                sample_count: desc.sample_count,
1252                multiview: desc.multiview,
1253            },
1254            base,
1255        },
1256        A::CreateQuerySet { id, desc } => A::CreateQuerySet {
1257            id,
1258            desc: desc.map_label(owned_label),
1259        },
1260        A::CreateBlas { id, desc, sizes } => A::CreateBlas {
1261            id,
1262            desc: desc.map_label(owned_label),
1263            sizes,
1264        },
1265        A::CreateTlas { id, desc } => A::CreateTlas {
1266            id,
1267            desc: desc.map_label(owned_label),
1268        },
1269    }
1270}
1271
1272fn owned_stage<SM>(
1273    stage: crate::pipeline::ProgrammableStageDescriptor<'_, SM>,
1274) -> crate::pipeline::ProgrammableStageDescriptor<'static, SM> {
1275    crate::pipeline::ProgrammableStageDescriptor {
1276        module: stage.module,
1277        entry_point: owned_label(&stage.entry_point),
1278        constants: stage.constants,
1279        zero_initialize_workgroup_memory: stage.zero_initialize_workgroup_memory,
1280    }
1281}
1282
1283fn owned_label(l: &Option<Cow<'_, str>>) -> Option<Cow<'static, str>> {
1284    l.as_ref().map(|l| Cow::Owned(l.to_string()))
1285}