1use alloc::{
2 borrow::Cow::{self, Borrowed},
3 boxed::Box,
4 format,
5 string::{String, ToString as _},
6 sync::Arc,
7 vec,
8 vec::Vec,
9};
10use core::{
11 error::Error,
12 fmt,
13 future::ready,
14 ops::{Deref, Range},
15 pin::Pin,
16 ptr::NonNull,
17 slice,
18};
19use hashbrown::HashMap;
20
21use arrayvec::ArrayVec;
22use smallvec::SmallVec;
23use wgc::{
24 error::ContextErrorSource, pipeline::CreateShaderModuleError,
25 resource::BlasPrepareCompactResult,
26};
27use wgt::{
28 error::{ErrorType, WebGpuError},
29 WasmNotSendSync,
30};
31
32use crate::{
33 api,
34 dispatch::{self, BlasCompactCallback, BufferMappedRangeInterface},
35 BindingResource, Blas, BufferBinding, BufferDescriptor, CompilationInfo, CompilationMessage,
36 CompilationMessageType, ErrorSource, Features, Label, LoadOp, MapMode, Operations,
37 ShaderSource, SurfaceTargetUnsafe, TextureDescriptor, Tlas, WriteOnly,
38};
39use crate::{dispatch::DispatchAdapter, util::Mutex};
40
41mod thread_id;
42
43#[derive(Clone)]
44pub struct ContextWgpuCore(Arc<wgc::global::Global>);
45
46impl Drop for ContextWgpuCore {
47 fn drop(&mut self) {
48 }
50}
51
52impl fmt::Debug for ContextWgpuCore {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 f.debug_struct("ContextWgpuCore")
55 .field("type", &"Native")
56 .finish()
57 }
58}
59
60impl ContextWgpuCore {
61 pub unsafe fn from_hal_instance<A: hal::Api>(hal_instance: A::Instance) -> Self {
62 Self(unsafe {
63 Arc::new(wgc::global::Global::from_hal_instance::<A>(
64 "wgpu",
65 hal_instance,
66 ))
67 })
68 }
69
70 pub unsafe fn instance_as_hal<A: hal::Api>(&self) -> Option<&A::Instance> {
74 unsafe { self.0.instance_as_hal::<A>() }
75 }
76
77 pub unsafe fn from_core_instance(core_instance: wgc::instance::Instance) -> Self {
78 Self(unsafe { Arc::new(wgc::global::Global::from_instance(core_instance)) })
79 }
80
81 #[cfg(wgpu_core)]
82 pub fn enumerate_adapters(&self, backends: wgt::Backends) -> Vec<wgc::id::AdapterId> {
83 self.0
84 .enumerate_adapters(backends, false )
85 }
86
87 pub unsafe fn create_adapter_from_hal<A: hal::Api>(
88 &self,
89 hal_adapter: hal::ExposedAdapter<A>,
90 ) -> wgc::id::AdapterId {
91 unsafe { self.0.create_adapter_from_hal(hal_adapter.into(), None) }
92 }
93
94 pub unsafe fn adapter_as_hal<A: hal::Api>(
95 &self,
96 adapter: &CoreAdapter,
97 ) -> Option<impl Deref<Target = A::Adapter> + WasmNotSendSync> {
98 unsafe { self.0.adapter_as_hal::<A>(adapter.id) }
99 }
100
101 pub unsafe fn buffer_as_hal<A: hal::Api>(
102 &self,
103 buffer: &CoreBuffer,
104 ) -> Option<impl Deref<Target = A::Buffer>> {
105 unsafe { self.0.buffer_as_hal::<A>(buffer.id) }
106 }
107
108 pub unsafe fn create_device_from_hal<A: hal::Api>(
109 &self,
110 adapter: &CoreAdapter,
111 hal_device: hal::OpenDevice<A>,
112 desc: &crate::DeviceDescriptor<'_>,
113 ) -> Result<(CoreDevice, CoreQueue), crate::RequestDeviceError> {
114 let (device_id, queue_id) = unsafe {
115 self.0.create_device_from_hal(
116 adapter.id,
117 hal_device.into(),
118 &desc.map_label(|l| l.map(Borrowed)),
119 None,
120 None,
121 )
122 }?;
123 let error_sink = Arc::new(Mutex::new(ErrorSinkRaw::new()));
124 let device = CoreDevice {
125 context: self.clone(),
126 id: device_id,
127 error_sink: error_sink.clone(),
128 features: desc.required_features,
129 };
130 let queue = CoreQueue {
131 context: self.clone(),
132 id: queue_id,
133 error_sink,
134 };
135 Ok((device, queue))
136 }
137
138 pub unsafe fn create_texture_from_hal<A: hal::Api>(
139 &self,
140 hal_texture: A::Texture,
141 device: &CoreDevice,
142 desc: &TextureDescriptor<'_>,
143 initial_state: wgt::TextureUses,
144 ) -> CoreTexture {
145 let descriptor = desc.map_label_and_view_formats(|l| l.map(Borrowed), |v| v.to_vec());
146 let (id, error) = unsafe {
147 self.0.create_texture_from_hal(
148 Box::new(hal_texture),
149 device.id,
150 &descriptor,
151 initial_state,
152 None,
153 )
154 };
155 if let Some(cause) = error {
156 self.handle_error(
157 &device.error_sink,
158 cause,
159 desc.label,
160 "Device::create_texture_from_hal",
161 );
162 }
163 CoreTexture {
164 context: self.clone(),
165 id,
166 error_sink: Arc::clone(&device.error_sink),
167 }
168 }
169
170 pub unsafe fn create_buffer_from_hal<A: hal::Api>(
177 &self,
178 hal_buffer: A::Buffer,
179 device: &CoreDevice,
180 desc: &BufferDescriptor<'_>,
181 ) -> CoreBuffer {
182 let (id, error) = unsafe {
183 self.0.create_buffer_from_hal::<A>(
184 hal_buffer,
185 device.id,
186 &desc.map_label(|l| l.map(Borrowed)),
187 None,
188 )
189 };
190 if let Some(cause) = error {
191 self.handle_error(
192 &device.error_sink,
193 cause,
194 desc.label,
195 "Device::create_buffer_from_hal",
196 );
197 }
198 CoreBuffer {
199 context: self.clone(),
200 id,
201 error_sink: Arc::clone(&device.error_sink),
202 }
203 }
204
205 pub unsafe fn device_as_hal<A: hal::Api>(
206 &self,
207 device: &CoreDevice,
208 ) -> Option<impl Deref<Target = A::Device>> {
209 unsafe { self.0.device_as_hal::<A>(device.id) }
210 }
211
212 pub unsafe fn surface_as_hal<A: hal::Api>(
213 &self,
214 surface: &CoreSurface,
215 ) -> Option<impl Deref<Target = A::Surface>> {
216 unsafe { self.0.surface_as_hal::<A>(surface.id) }
217 }
218
219 pub unsafe fn texture_as_hal<A: hal::Api>(
220 &self,
221 texture: &CoreTexture,
222 ) -> Option<impl Deref<Target = A::Texture>> {
223 unsafe { self.0.texture_as_hal::<A>(texture.id) }
224 }
225
226 pub unsafe fn texture_view_as_hal<A: hal::Api>(
227 &self,
228 texture_view: &CoreTextureView,
229 ) -> Option<impl Deref<Target = A::TextureView>> {
230 unsafe { self.0.texture_view_as_hal::<A>(texture_view.id) }
231 }
232
233 pub unsafe fn command_encoder_as_hal_mut<
235 A: hal::Api,
236 F: FnOnce(Option<&mut A::CommandEncoder>) -> R,
237 R,
238 >(
239 &self,
240 command_encoder: &CoreCommandEncoder,
241 hal_command_encoder_callback: F,
242 ) -> R {
243 unsafe {
244 self.0.command_encoder_as_hal_mut::<A, F, R>(
245 command_encoder.id,
246 hal_command_encoder_callback,
247 )
248 }
249 }
250
251 pub unsafe fn blas_as_hal<A: hal::Api>(
252 &self,
253 blas: &CoreBlas,
254 ) -> Option<impl Deref<Target = A::AccelerationStructure>> {
255 unsafe { self.0.blas_as_hal::<A>(blas.id) }
256 }
257
258 pub unsafe fn tlas_as_hal<A: hal::Api>(
259 &self,
260 tlas: &CoreTlas,
261 ) -> Option<impl Deref<Target = A::AccelerationStructure>> {
262 unsafe { self.0.tlas_as_hal::<A>(tlas.id) }
263 }
264
265 pub fn generate_report(&self) -> wgc::global::GlobalReport {
266 self.0.generate_report()
267 }
268
269 #[cold]
270 #[track_caller]
271 #[inline(never)]
272 fn handle_error_inner(
273 &self,
274 sink_mutex: &Mutex<ErrorSinkRaw>,
275 error_type: ErrorType,
276 source: ContextErrorSource,
277 label: Label<'_>,
278 fn_ident: &'static str,
279 ) {
280 let source: ErrorSource = Box::new(wgc::error::ContextError {
281 fn_ident,
282 source,
283 label: label.unwrap_or_default().to_string(),
284 });
285 let final_error_handling = {
286 let mut sink = sink_mutex.lock();
287 let description = || self.format_error(&*source);
288 let error = match error_type {
289 ErrorType::Internal => {
290 let description = description();
291 crate::Error::Internal {
292 source,
293 description,
294 }
295 }
296 ErrorType::OutOfMemory => crate::Error::OutOfMemory { source },
297 ErrorType::Validation => {
298 let description = description();
299 crate::Error::Validation {
300 source,
301 description,
302 }
303 }
304 ErrorType::DeviceLost => return, };
306 sink.handle_error_or_return_handler(error)
307 };
308
309 if let Some(f) = final_error_handling {
310 f();
314 }
315 }
316
317 #[inline]
318 #[track_caller]
319 fn handle_error(
320 &self,
321 sink_mutex: &Mutex<ErrorSinkRaw>,
322 source: impl WebGpuError + WasmNotSendSync + 'static,
323 label: Label<'_>,
324 fn_ident: &'static str,
325 ) {
326 let error_type = source.webgpu_error_type();
327 self.handle_error_inner(sink_mutex, error_type, Box::new(source), label, fn_ident)
328 }
329
330 #[inline]
331 #[track_caller]
332 fn handle_error_nolabel(
333 &self,
334 sink_mutex: &Mutex<ErrorSinkRaw>,
335 source: impl WebGpuError + WasmNotSendSync + 'static,
336 fn_ident: &'static str,
337 ) {
338 let error_type = source.webgpu_error_type();
339 self.handle_error_inner(sink_mutex, error_type, Box::new(source), None, fn_ident)
340 }
341
342 #[track_caller]
343 #[cold]
344 fn handle_error_fatal(
345 &self,
346 cause: impl Error + WasmNotSendSync + 'static,
347 operation: &'static str,
348 ) -> ! {
349 panic!("Error in {operation}: {f}", f = self.format_error(&cause));
350 }
351
352 #[inline(never)]
353 fn format_error(&self, err: &(dyn Error + 'static)) -> String {
354 let mut output = String::new();
355 let mut level = 1;
356
357 fn print_tree(output: &mut String, level: &mut usize, e: &(dyn Error + 'static)) {
358 let mut print = |e: &(dyn Error + 'static)| {
359 use core::fmt::Write;
360 writeln!(output, "{}{}", " ".repeat(*level * 2), e).unwrap();
361
362 if let Some(e) = e.source() {
363 *level += 1;
364 print_tree(output, level, e);
365 *level -= 1;
366 }
367 };
368 if let Some(multi) = e.downcast_ref::<wgc::error::MultiError>() {
369 for e in multi.errors() {
370 print(e);
371 }
372 } else {
373 print(e);
374 }
375 }
376
377 print_tree(&mut output, &mut level, err);
378
379 format!("Validation Error\n\nCaused by:\n{output}")
380 }
381
382 pub unsafe fn queue_as_hal<A: hal::Api>(
383 &self,
384 queue: &CoreQueue,
385 ) -> Option<impl Deref<Target = A::Queue> + WasmNotSendSync> {
386 unsafe { self.0.queue_as_hal::<A>(queue.id) }
387 }
388}
389
390fn map_buffer_copy_view(
391 view: crate::TexelCopyBufferInfo<'_>,
392) -> wgt::TexelCopyBufferInfo<wgc::id::BufferId> {
393 wgt::TexelCopyBufferInfo {
394 buffer: view.buffer.inner.as_core().id,
395 layout: view.layout,
396 }
397}
398
399fn map_texture_copy_view(
400 view: crate::TexelCopyTextureInfo<'_>,
401) -> wgt::TexelCopyTextureInfo<wgc::id::TextureId> {
402 wgt::TexelCopyTextureInfo {
403 texture: view.texture.inner.as_core().id,
404 mip_level: view.mip_level,
405 origin: view.origin,
406 aspect: view.aspect,
407 }
408}
409
410#[cfg_attr(not(webgl), expect(unused))]
411fn map_texture_tagged_copy_view(
412 view: crate::CopyExternalImageDestInfo<&api::Texture>,
413) -> wgt::CopyExternalImageDestInfo<wgc::id::TextureId> {
414 wgt::CopyExternalImageDestInfo {
415 texture: view.texture.inner.as_core().id,
416 mip_level: view.mip_level,
417 origin: view.origin,
418 aspect: view.aspect,
419 color_space: view.color_space,
420 premultiplied_alpha: view.premultiplied_alpha,
421 }
422}
423
424fn map_load_op<V: Copy>(load: &LoadOp<V>) -> LoadOp<Option<V>> {
425 match *load {
426 LoadOp::Clear(clear_value) => LoadOp::Clear(Some(clear_value)),
427 LoadOp::DontCare(token) => LoadOp::DontCare(token),
428 LoadOp::Load => LoadOp::Load,
429 }
430}
431
432fn map_pass_channel<V: Copy>(ops: Option<&Operations<V>>) -> wgc::command::PassChannel<Option<V>> {
433 match ops {
434 Some(&Operations { load, store }) => wgc::command::PassChannel {
435 load_op: Some(map_load_op(&load)),
436 store_op: Some(store),
437 read_only: false,
438 },
439 None => wgc::command::PassChannel {
440 load_op: None,
441 store_op: None,
442 read_only: true,
443 },
444 }
445}
446
447#[derive(Debug)]
448pub struct CoreSurface {
449 pub(crate) context: ContextWgpuCore,
450 id: wgc::id::SurfaceId,
451 configured_device: Mutex<Option<wgc::id::DeviceId>>,
454 error_sink: Mutex<Option<ErrorSink>>,
457}
458
459#[derive(Debug)]
460pub struct CoreAdapter {
461 pub(crate) context: ContextWgpuCore,
462 pub(crate) id: wgc::id::AdapterId,
463}
464
465#[derive(Debug)]
466pub struct CoreDevice {
467 pub(crate) context: ContextWgpuCore,
468 id: wgc::id::DeviceId,
469 error_sink: ErrorSink,
470 features: Features,
471}
472
473impl CoreDevice {
474 pub fn read_program_links(&self) -> bool {
477 self.context.0.device_read_program_links(self.id)
478 }
479
480 #[cfg(webgl)]
482 pub fn create_shader_module_glsl_templates(
483 &self,
484 label: crate::Label<'_>,
485 templates: &'static [hal::GlslTemplate],
486 ) -> dispatch::DispatchShaderModule {
487 let (id, error) = unsafe {
489 self.context.0.device_create_shader_module_glsl_templates(
490 self.id,
491 &label.map(Cow::Borrowed),
492 templates,
493 None,
494 )
495 };
496 let compilation_info = match error {
497 Some(cause) => {
498 self.context.handle_error(
499 &self.error_sink,
500 cause.clone(),
501 label,
502 "Device::create_shader_module_glsl_templates",
503 );
504 CompilationInfo::from(cause)
505 }
506 None => CompilationInfo { messages: vec![] },
507 };
508 CoreShaderModule {
509 context: self.context.clone(),
510 id,
511 compilation_info,
512 }
513 .into()
514 }
515}
516
517#[derive(Debug)]
518pub struct CoreBuffer {
519 pub(crate) context: ContextWgpuCore,
520 id: wgc::id::BufferId,
521 error_sink: ErrorSink,
522}
523
524#[derive(Debug)]
525pub struct CoreShaderModule {
526 pub(crate) context: ContextWgpuCore,
527 id: wgc::id::ShaderModuleId,
528 compilation_info: CompilationInfo,
529}
530
531#[derive(Debug)]
532pub struct CoreBindGroupLayout {
533 pub(crate) context: ContextWgpuCore,
534 id: wgc::id::BindGroupLayoutId,
535}
536
537#[derive(Debug)]
538pub struct CoreBindGroup {
539 pub(crate) context: ContextWgpuCore,
540 id: wgc::id::BindGroupId,
541}
542
543#[derive(Debug)]
544pub struct CoreTexture {
545 pub(crate) context: ContextWgpuCore,
546 id: wgc::id::TextureId,
547 error_sink: ErrorSink,
548}
549
550#[derive(Debug)]
551pub struct CoreTextureView {
552 pub(crate) context: ContextWgpuCore,
553 id: wgc::id::TextureViewId,
554}
555
556#[derive(Debug)]
557pub struct CoreExternalTexture {
558 pub(crate) context: ContextWgpuCore,
559 id: wgc::id::ExternalTextureId,
560}
561
562#[derive(Debug)]
563pub struct CoreSampler {
564 pub(crate) context: ContextWgpuCore,
565 id: wgc::id::SamplerId,
566}
567
568#[derive(Debug)]
569pub struct CoreQuerySet {
570 pub(crate) context: ContextWgpuCore,
571 id: wgc::id::QuerySetId,
572}
573
574#[derive(Debug)]
575pub struct CorePipelineLayout {
576 pub(crate) context: ContextWgpuCore,
577 id: wgc::id::PipelineLayoutId,
578}
579
580#[derive(Debug)]
581pub struct CorePipelineCache {
582 pub(crate) context: ContextWgpuCore,
583 id: wgc::id::PipelineCacheId,
584}
585
586#[derive(Debug)]
587pub struct CoreCommandBuffer {
588 pub(crate) context: ContextWgpuCore,
589 id: wgc::id::CommandBufferId,
590}
591
592#[derive(Debug)]
593pub struct CoreRenderBundleEncoder {
594 pub(crate) context: ContextWgpuCore,
595 encoder: Box<wgc::command::RenderBundleEncoder>,
596 id: crate::cmp::Identifier,
597}
598
599#[derive(Debug)]
600pub struct CoreRenderBundle {
601 context: ContextWgpuCore,
602 id: wgc::id::RenderBundleId,
603}
604
605#[derive(Debug)]
606pub struct CoreQueue {
607 pub(crate) context: ContextWgpuCore,
608 id: wgc::id::QueueId,
609 error_sink: ErrorSink,
610}
611
612#[derive(Debug)]
613pub struct CoreComputePipeline {
614 pub(crate) context: ContextWgpuCore,
615 id: wgc::id::ComputePipelineId,
616 error_sink: ErrorSink,
617}
618
619#[derive(Debug)]
620pub struct CoreRenderPipeline {
621 pub(crate) context: ContextWgpuCore,
622 id: wgc::id::RenderPipelineId,
623 error_sink: ErrorSink,
624}
625
626#[derive(Debug)]
627pub struct CoreComputePass {
628 pub(crate) context: ContextWgpuCore,
629 pass: wgc::command::ComputePass,
630 error_sink: ErrorSink,
631 id: crate::cmp::Identifier,
632}
633
634#[derive(Debug)]
635pub struct CoreRenderPass {
636 pub(crate) context: ContextWgpuCore,
637 pass: wgc::command::RenderPass,
638 error_sink: ErrorSink,
639 id: crate::cmp::Identifier,
640}
641
642#[derive(Debug)]
643pub struct CoreCommandEncoder {
644 pub(crate) context: ContextWgpuCore,
645 id: wgc::id::CommandEncoderId,
646 error_sink: ErrorSink,
647}
648
649#[derive(Debug)]
650pub struct CoreBlas {
651 pub(crate) context: ContextWgpuCore,
652 id: wgc::id::BlasId,
653 error_sink: ErrorSink,
654}
655
656#[derive(Debug)]
657pub struct CoreTlas {
658 pub(crate) context: ContextWgpuCore,
659 id: wgc::id::TlasId,
660 }
662
663#[derive(Debug)]
664pub struct CoreSurfaceOutputDetail {
665 context: ContextWgpuCore,
666 surface_id: wgc::id::SurfaceId,
667 error_sink: ErrorSink,
668 image: Option<crate::SurfaceImage>,
669}
670
671type ErrorSink = Arc<Mutex<ErrorSinkRaw>>;
672
673struct ErrorScope {
674 error: Option<crate::Error>,
675 filter: crate::ErrorFilter,
676}
677
678struct ErrorSinkRaw {
679 scopes: HashMap<thread_id::ThreadId, Vec<ErrorScope>>,
680 uncaptured_handler: Option<Arc<dyn crate::UncapturedErrorHandler>>,
681}
682
683impl ErrorSinkRaw {
684 fn new() -> ErrorSinkRaw {
685 ErrorSinkRaw {
686 scopes: HashMap::new(),
687 uncaptured_handler: None,
688 }
689 }
690
691 #[track_caller]
701 #[must_use]
702 fn handle_error_or_return_handler(&mut self, err: crate::Error) -> Option<impl FnOnce()> {
703 let filter = match err {
704 crate::Error::OutOfMemory { .. } => crate::ErrorFilter::OutOfMemory,
705 crate::Error::Validation { .. } => crate::ErrorFilter::Validation,
706 crate::Error::Internal { .. } => crate::ErrorFilter::Internal,
707 };
708 let thread_id = thread_id::ThreadId::current();
709 let scopes = self.scopes.entry(thread_id).or_default();
710 match scopes.iter_mut().rev().find(|scope| scope.filter == filter) {
711 Some(scope) => {
712 if scope.error.is_none() {
713 scope.error = Some(err);
714 }
715 None
716 }
717 None => {
718 if let Some(custom_handler) = &self.uncaptured_handler {
719 let custom_handler = Arc::clone(custom_handler);
720 Some(move || (custom_handler)(err))
721 } else {
722 default_error_handler(err)
724 }
725 }
726 }
727 }
728}
729
730impl fmt::Debug for ErrorSinkRaw {
731 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
732 write!(f, "ErrorSink")
733 }
734}
735
736#[track_caller]
737fn default_error_handler(err: crate::Error) -> ! {
738 log::error!("Handling wgpu errors as fatal by default");
739 panic!("wgpu error: {err}\n");
740}
741
742impl From<CreateShaderModuleError> for CompilationInfo {
743 fn from(value: CreateShaderModuleError) -> Self {
744 match value {
745 #[cfg(feature = "wgsl")]
746 CreateShaderModuleError::Parsing(v) => v.into(),
747 #[cfg(feature = "glsl")]
748 CreateShaderModuleError::ParsingGlsl(v) => v.into(),
749 #[cfg(feature = "spirv")]
750 CreateShaderModuleError::ParsingSpirV(v) => v.into(),
751 CreateShaderModuleError::Validation(v) => v.into(),
752 CreateShaderModuleError::Device(_) | CreateShaderModuleError::Generation => {
755 CompilationInfo {
756 messages: Vec::new(),
757 }
758 }
759 _ => CompilationInfo {
761 messages: vec![CompilationMessage {
762 message: value.to_string(),
763 message_type: CompilationMessageType::Error,
764 location: None,
765 }],
766 },
767 }
768 }
769}
770
771#[derive(Debug)]
772pub struct CoreQueueWriteBuffer {
773 buffer_id: wgc::id::StagingBufferId,
774 mapping: CoreBufferMappedRange,
775}
776
777#[derive(Debug)]
778pub struct CoreBufferMappedRange {
779 ptr: NonNull<u8>,
780 size: usize,
781}
782
783#[cfg(send_sync)]
784unsafe impl Send for CoreBufferMappedRange {}
785#[cfg(send_sync)]
786unsafe impl Sync for CoreBufferMappedRange {}
787
788impl Drop for CoreBufferMappedRange {
789 fn drop(&mut self) {
790 }
793}
794
795crate::cmp::impl_eq_ord_hash_arc_address!(ContextWgpuCore => .0);
796crate::cmp::impl_eq_ord_hash_proxy!(CoreAdapter => .id);
797crate::cmp::impl_eq_ord_hash_proxy!(CoreDevice => .id);
798crate::cmp::impl_eq_ord_hash_proxy!(CoreQueue => .id);
799crate::cmp::impl_eq_ord_hash_proxy!(CoreShaderModule => .id);
800crate::cmp::impl_eq_ord_hash_proxy!(CoreBindGroupLayout => .id);
801crate::cmp::impl_eq_ord_hash_proxy!(CoreBindGroup => .id);
802crate::cmp::impl_eq_ord_hash_proxy!(CoreTextureView => .id);
803crate::cmp::impl_eq_ord_hash_proxy!(CoreSampler => .id);
804crate::cmp::impl_eq_ord_hash_proxy!(CoreBuffer => .id);
805crate::cmp::impl_eq_ord_hash_proxy!(CoreTexture => .id);
806crate::cmp::impl_eq_ord_hash_proxy!(CoreExternalTexture => .id);
807crate::cmp::impl_eq_ord_hash_proxy!(CoreBlas => .id);
808crate::cmp::impl_eq_ord_hash_proxy!(CoreTlas => .id);
809crate::cmp::impl_eq_ord_hash_proxy!(CoreQuerySet => .id);
810crate::cmp::impl_eq_ord_hash_proxy!(CorePipelineLayout => .id);
811crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPipeline => .id);
812crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePipeline => .id);
813crate::cmp::impl_eq_ord_hash_proxy!(CorePipelineCache => .id);
814crate::cmp::impl_eq_ord_hash_proxy!(CoreCommandEncoder => .id);
815crate::cmp::impl_eq_ord_hash_proxy!(CoreComputePass => .id);
816crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderPass => .id);
817crate::cmp::impl_eq_ord_hash_proxy!(CoreCommandBuffer => .id);
818crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderBundleEncoder => .id);
819crate::cmp::impl_eq_ord_hash_proxy!(CoreRenderBundle => .id);
820crate::cmp::impl_eq_ord_hash_proxy!(CoreSurface => .id);
821crate::cmp::impl_eq_ord_hash_proxy!(CoreSurfaceOutputDetail => .surface_id);
822crate::cmp::impl_eq_ord_hash_proxy!(CoreQueueWriteBuffer => .mapping.ptr);
823crate::cmp::impl_eq_ord_hash_proxy!(CoreBufferMappedRange => .ptr);
824
825impl dispatch::InstanceInterface for ContextWgpuCore {
826 fn new(desc: wgt::InstanceDescriptor) -> Self
827 where
828 Self: Sized,
829 {
830 Self(Arc::new(wgc::global::Global::new("wgpu", desc, None)))
831 }
832
833 unsafe fn create_surface(
834 &self,
835 target: crate::api::SurfaceTargetUnsafe,
836 ) -> Result<dispatch::DispatchSurface, crate::CreateSurfaceError> {
837 let id = match target {
838 SurfaceTargetUnsafe::RawHandle {
839 raw_display_handle,
840 raw_window_handle,
841 } => unsafe {
842 self.0
843 .instance_create_surface(raw_display_handle, raw_window_handle, None)
844 },
845
846 #[cfg(all(drm, not(target_os = "netbsd")))]
847 SurfaceTargetUnsafe::Drm {
848 fd,
849 plane,
850 connector_id,
851 width,
852 height,
853 refresh_rate,
854 } => unsafe {
855 self.0.instance_create_surface_from_drm(
856 fd,
857 plane,
858 connector_id,
859 width,
860 height,
861 refresh_rate,
862 None,
863 )
864 },
865
866 #[cfg(metal)]
867 SurfaceTargetUnsafe::CoreAnimationLayer(layer) => unsafe {
868 self.0.instance_create_surface_metal(layer, None)
869 },
870
871 #[cfg(all(drm, target_os = "netbsd"))]
872 SurfaceTargetUnsafe::Drm { .. } => Err(
873 wgc::instance::CreateSurfaceError::BackendNotEnabled(wgt::Backend::Vulkan),
874 ),
875
876 #[cfg(dx12)]
877 SurfaceTargetUnsafe::CompositionVisual(visual) => unsafe {
878 self.0.instance_create_surface_from_visual(visual, None)
879 },
880
881 #[cfg(dx12)]
882 SurfaceTargetUnsafe::SurfaceHandle(surface_handle) => unsafe {
883 self.0
884 .instance_create_surface_from_surface_handle(surface_handle, None)
885 },
886
887 #[cfg(dx12)]
888 SurfaceTargetUnsafe::SwapChainPanel(swap_chain_panel) => unsafe {
889 self.0
890 .instance_create_surface_from_swap_chain_panel(swap_chain_panel, None)
891 },
892 }?;
893
894 Ok(CoreSurface {
895 context: self.clone(),
896 id,
897 configured_device: Mutex::default(),
898 error_sink: Mutex::default(),
899 }
900 .into())
901 }
902
903 fn request_adapter(
904 &self,
905 options: &crate::api::RequestAdapterOptions<'_, '_>,
906 ) -> Pin<Box<dyn dispatch::RequestAdapterFuture>> {
907 let id = self.0.request_adapter(
908 &wgc::instance::RequestAdapterOptions {
909 power_preference: options.power_preference,
910 force_fallback_adapter: options.force_fallback_adapter,
911 compatible_surface: options
912 .compatible_surface
913 .map(|surface| surface.inner.as_core().id),
914 apply_limit_buckets: false,
915 },
916 wgt::Backends::all(),
917 None,
918 );
919 let adapter = id.map(|id| {
920 let core = CoreAdapter {
921 context: self.clone(),
922 id,
923 };
924 let generic: dispatch::DispatchAdapter = core.into();
925 generic
926 });
927 Box::pin(ready(adapter))
928 }
929
930 fn poll_all_devices(&self, force_wait: bool) -> bool {
931 match self.0.poll_all_devices(force_wait) {
932 Ok(all_queue_empty) => all_queue_empty,
933 Err(err) => self.handle_error_fatal(err, "Instance::poll_all_devices"),
934 }
935 }
936
937 #[cfg(feature = "wgsl")]
938 fn wgsl_language_features(&self) -> crate::WgslLanguageFeatures {
939 use wgc::naga::front::wgsl::ImplementedLanguageExtension;
940 ImplementedLanguageExtension::all().iter().copied().fold(
941 crate::WgslLanguageFeatures::empty(),
942 |acc, wle| {
943 acc | match wle {
944 ImplementedLanguageExtension::ReadOnlyAndReadWriteStorageTextures => {
945 crate::WgslLanguageFeatures::ReadOnlyAndReadWriteStorageTextures
946 }
947 ImplementedLanguageExtension::Packed4x8IntegerDotProduct => {
948 crate::WgslLanguageFeatures::Packed4x8IntegerDotProduct
949 }
950 ImplementedLanguageExtension::PointerCompositeAccess => {
951 crate::WgslLanguageFeatures::PointerCompositeAccess
952 }
953 }
954 },
955 )
956 }
957
958 fn enumerate_adapters(
959 &self,
960 backends: crate::Backends,
961 ) -> Pin<Box<dyn dispatch::EnumerateAdapterFuture>> {
962 let adapters: Vec<DispatchAdapter> = self
963 .enumerate_adapters(backends)
964 .into_iter()
965 .map(|adapter| {
966 let core = crate::backend::wgpu_core::CoreAdapter {
967 context: self.clone(),
968 id: adapter,
969 };
970 core.into()
971 })
972 .collect();
973 Box::pin(ready(adapters))
974 }
975}
976
977impl dispatch::AdapterInterface for CoreAdapter {
978 fn request_device(
979 &self,
980 desc: &crate::DeviceDescriptor<'_>,
981 ) -> Pin<Box<dyn dispatch::RequestDeviceFuture>> {
982 let res = self.context.0.adapter_request_device(
983 self.id,
984 &desc.map_label(|l| l.map(Borrowed)),
985 None,
986 None,
987 );
988 let (device_id, queue_id) = match res {
989 Ok(ids) => ids,
990 Err(err) => {
991 return Box::pin(ready(Err(err.into())));
992 }
993 };
994 let error_sink = Arc::new(Mutex::new(ErrorSinkRaw::new()));
995 let device = CoreDevice {
996 context: self.context.clone(),
997 id: device_id,
998 error_sink: error_sink.clone(),
999 features: desc.required_features,
1000 };
1001 let queue = CoreQueue {
1002 context: self.context.clone(),
1003 id: queue_id,
1004 error_sink,
1005 };
1006 Box::pin(ready(Ok((device.into(), queue.into()))))
1007 }
1008
1009 fn is_surface_supported(&self, surface: &dispatch::DispatchSurface) -> bool {
1010 let surface = surface.as_core();
1011
1012 self.context
1013 .0
1014 .adapter_is_surface_supported(self.id, surface.id)
1015 }
1016
1017 fn features(&self) -> crate::Features {
1018 self.context.0.adapter_features(self.id)
1019 }
1020
1021 fn limits(&self) -> crate::Limits {
1022 self.context.0.adapter_limits(self.id)
1023 }
1024
1025 fn downlevel_capabilities(&self) -> crate::DownlevelCapabilities {
1026 self.context.0.adapter_downlevel_capabilities(self.id)
1027 }
1028
1029 fn get_info(&self) -> crate::AdapterInfo {
1030 self.context.0.adapter_get_info(self.id)
1031 }
1032
1033 fn get_texture_format_features(
1034 &self,
1035 format: crate::TextureFormat,
1036 ) -> crate::TextureFormatFeatures {
1037 self.context
1038 .0
1039 .adapter_get_texture_format_features(self.id, format)
1040 }
1041
1042 fn get_presentation_timestamp(&self) -> crate::PresentationTimestamp {
1043 self.context.0.adapter_get_presentation_timestamp(self.id)
1044 }
1045
1046 fn cooperative_matrix_properties(&self) -> Vec<crate::wgt::CooperativeMatrixProperties> {
1047 self.context
1048 .0
1049 .adapter_cooperative_matrix_properties(self.id)
1050 }
1051}
1052
1053impl Drop for CoreAdapter {
1054 fn drop(&mut self) {
1055 self.context.0.adapter_drop(self.id)
1056 }
1057}
1058
1059impl dispatch::DeviceInterface for CoreDevice {
1060 fn features(&self) -> crate::Features {
1061 self.context.0.device_features(self.id)
1062 }
1063
1064 fn limits(&self) -> crate::Limits {
1065 self.context.0.device_limits(self.id)
1066 }
1067
1068 fn adapter_info(&self) -> crate::AdapterInfo {
1069 self.context.0.device_adapter_info(self.id)
1070 }
1071
1072 #[cfg_attr(
1074 not(any(
1075 feature = "spirv",
1076 feature = "glsl",
1077 feature = "wgsl",
1078 feature = "naga-ir"
1079 )),
1080 expect(unused)
1081 )]
1082 fn create_shader_module(
1083 &self,
1084 desc: crate::ShaderModuleDescriptor<'_>,
1085 shader_bound_checks: wgt::ShaderRuntimeChecks,
1086 ) -> dispatch::DispatchShaderModule {
1087 let descriptor = wgc::pipeline::ShaderModuleDescriptor {
1088 label: desc.label.map(Borrowed),
1089 runtime_checks: shader_bound_checks,
1090 };
1091 let source = match desc.source {
1092 #[cfg(feature = "spirv")]
1093 ShaderSource::SpirV(ref spv) => {
1094 let options = naga::front::spv::Options {
1096 adjust_coordinate_space: false, strict_capabilities: true,
1098 block_ctx_dump_prefix: None,
1099 };
1100 wgc::pipeline::ShaderModuleSource::SpirV(Borrowed(spv), options)
1101 }
1102 #[cfg(feature = "glsl")]
1103 ShaderSource::Glsl {
1104 ref shader,
1105 stage,
1106 defines,
1107 } => {
1108 let options = naga::front::glsl::Options {
1109 stage,
1110 defines: defines
1111 .iter()
1112 .map(|&(key, value)| (String::from(key), String::from(value)))
1113 .collect(),
1114 };
1115 wgc::pipeline::ShaderModuleSource::Glsl(Borrowed(shader), options)
1116 }
1117 #[cfg(feature = "wgsl")]
1118 ShaderSource::Wgsl(ref code) => wgc::pipeline::ShaderModuleSource::Wgsl(Borrowed(code)),
1119 #[cfg(feature = "naga-ir")]
1120 ShaderSource::Naga(module) => wgc::pipeline::ShaderModuleSource::Naga(module),
1121 ShaderSource::Dummy(_) => panic!("found `ShaderSource::Dummy`"),
1122 };
1123 let (id, error) =
1124 self.context
1125 .0
1126 .device_create_shader_module(self.id, &descriptor, source, None);
1127 let compilation_info = match error {
1128 Some(cause) => {
1129 self.context.handle_error(
1130 &self.error_sink,
1131 cause.clone(),
1132 desc.label,
1133 "Device::create_shader_module",
1134 );
1135 CompilationInfo::from(cause)
1136 }
1137 None => CompilationInfo { messages: vec![] },
1138 };
1139
1140 CoreShaderModule {
1141 context: self.context.clone(),
1142 id,
1143 compilation_info,
1144 }
1145 .into()
1146 }
1147
1148 unsafe fn create_shader_module_passthrough(
1149 &self,
1150 desc: &crate::ShaderModuleDescriptorPassthrough<'_>,
1151 ) -> dispatch::DispatchShaderModule {
1152 let desc = desc.map_label(|l| l.map(Cow::from));
1153 let (id, error) = unsafe {
1154 self.context
1155 .0
1156 .device_create_shader_module_passthrough(self.id, &desc, None)
1157 };
1158
1159 let compilation_info = match error {
1160 Some(cause) => {
1161 self.context.handle_error(
1162 &self.error_sink,
1163 cause.clone(),
1164 desc.label.as_deref(),
1165 "Device::create_shader_module_passthrough",
1166 );
1167 CompilationInfo::from(cause)
1168 }
1169 None => CompilationInfo { messages: vec![] },
1170 };
1171
1172 CoreShaderModule {
1173 context: self.context.clone(),
1174 id,
1175 compilation_info,
1176 }
1177 .into()
1178 }
1179
1180 fn create_bind_group_layout(
1181 &self,
1182 desc: &crate::BindGroupLayoutDescriptor<'_>,
1183 ) -> dispatch::DispatchBindGroupLayout {
1184 let descriptor = wgc::binding_model::BindGroupLayoutDescriptor {
1185 label: desc.label.map(Borrowed),
1186 entries: Borrowed(desc.entries),
1187 };
1188 let (id, error) =
1189 self.context
1190 .0
1191 .device_create_bind_group_layout(self.id, &descriptor, None);
1192 if let Some(cause) = error {
1193 self.context.handle_error(
1194 &self.error_sink,
1195 cause,
1196 desc.label,
1197 "Device::create_bind_group_layout",
1198 );
1199 }
1200 CoreBindGroupLayout {
1201 context: self.context.clone(),
1202 id,
1203 }
1204 .into()
1205 }
1206
1207 fn create_bind_group(
1208 &self,
1209 desc: &crate::BindGroupDescriptor<'_>,
1210 ) -> dispatch::DispatchBindGroup {
1211 use wgc::binding_model as bm;
1212
1213 let mut arrayed_texture_views = Vec::new();
1214 let mut arrayed_samplers = Vec::new();
1215 if self.features.contains(Features::TEXTURE_BINDING_ARRAY) {
1216 for entry in desc.entries.iter() {
1218 if let BindingResource::TextureViewArray(array) = entry.resource {
1219 arrayed_texture_views.extend(array.iter().map(|view| view.inner.as_core().id));
1220 }
1221 if let BindingResource::SamplerArray(array) = entry.resource {
1222 arrayed_samplers.extend(array.iter().map(|sampler| sampler.inner.as_core().id));
1223 }
1224 }
1225 }
1226 let mut remaining_arrayed_texture_views = &arrayed_texture_views[..];
1227 let mut remaining_arrayed_samplers = &arrayed_samplers[..];
1228
1229 let mut arrayed_buffer_bindings = Vec::new();
1230 if self.features.contains(Features::BUFFER_BINDING_ARRAY) {
1231 for entry in desc.entries.iter() {
1233 if let BindingResource::BufferArray(array) = entry.resource {
1234 arrayed_buffer_bindings.extend(array.iter().map(|binding| bm::BufferBinding {
1235 buffer: binding.buffer.inner.as_core().id,
1236 offset: binding.offset,
1237 size: binding.size.map(wgt::BufferSize::get),
1238 }));
1239 }
1240 }
1241 }
1242 let mut remaining_arrayed_buffer_bindings = &arrayed_buffer_bindings[..];
1243
1244 let mut arrayed_acceleration_structures = Vec::new();
1245 if self
1246 .features
1247 .contains(Features::ACCELERATION_STRUCTURE_BINDING_ARRAY)
1248 {
1249 for entry in desc.entries.iter() {
1251 if let BindingResource::AccelerationStructureArray(array) = entry.resource {
1252 arrayed_acceleration_structures
1253 .extend(array.iter().map(|tlas| tlas.inner.as_core().id));
1254 }
1255 }
1256 }
1257 let mut remaining_arrayed_acceleration_structures = &arrayed_acceleration_structures[..];
1258
1259 let entries = desc
1260 .entries
1261 .iter()
1262 .map(|entry| bm::BindGroupEntry {
1263 binding: entry.binding,
1264 resource: match entry.resource {
1265 BindingResource::Buffer(BufferBinding {
1266 buffer,
1267 offset,
1268 size,
1269 }) => bm::BindingResource::Buffer(bm::BufferBinding {
1270 buffer: buffer.inner.as_core().id,
1271 offset,
1272 size: size.map(wgt::BufferSize::get),
1273 }),
1274 BindingResource::BufferArray(array) => {
1275 let slice = &remaining_arrayed_buffer_bindings[..array.len()];
1276 remaining_arrayed_buffer_bindings =
1277 &remaining_arrayed_buffer_bindings[array.len()..];
1278 bm::BindingResource::BufferArray(Borrowed(slice))
1279 }
1280 BindingResource::Sampler(sampler) => {
1281 bm::BindingResource::Sampler(sampler.inner.as_core().id)
1282 }
1283 BindingResource::SamplerArray(array) => {
1284 let slice = &remaining_arrayed_samplers[..array.len()];
1285 remaining_arrayed_samplers = &remaining_arrayed_samplers[array.len()..];
1286 bm::BindingResource::SamplerArray(Borrowed(slice))
1287 }
1288 BindingResource::TextureView(texture_view) => {
1289 bm::BindingResource::TextureView(texture_view.inner.as_core().id)
1290 }
1291 BindingResource::TextureViewArray(array) => {
1292 let slice = &remaining_arrayed_texture_views[..array.len()];
1293 remaining_arrayed_texture_views =
1294 &remaining_arrayed_texture_views[array.len()..];
1295 bm::BindingResource::TextureViewArray(Borrowed(slice))
1296 }
1297 BindingResource::AccelerationStructure(acceleration_structure) => {
1298 bm::BindingResource::AccelerationStructure(
1299 acceleration_structure.inner.as_core().id,
1300 )
1301 }
1302 BindingResource::AccelerationStructureArray(array) => {
1303 let slice = &remaining_arrayed_acceleration_structures[..array.len()];
1304 remaining_arrayed_acceleration_structures =
1305 &remaining_arrayed_acceleration_structures[array.len()..];
1306 bm::BindingResource::AccelerationStructureArray(Borrowed(slice))
1307 }
1308 BindingResource::ExternalTexture(external_texture) => {
1309 bm::BindingResource::ExternalTexture(external_texture.inner.as_core().id)
1310 }
1311 },
1312 })
1313 .collect::<Vec<_>>();
1314 let descriptor = bm::BindGroupDescriptor {
1315 label: desc.label.as_ref().map(|label| Borrowed(&label[..])),
1316 layout: desc.layout.inner.as_core().id,
1317 entries: Borrowed(&entries),
1318 };
1319
1320 let (id, error) = self
1321 .context
1322 .0
1323 .device_create_bind_group(self.id, &descriptor, None);
1324 if let Some(cause) = error {
1325 self.context.handle_error(
1326 &self.error_sink,
1327 cause,
1328 desc.label,
1329 "Device::create_bind_group",
1330 );
1331 }
1332 CoreBindGroup {
1333 context: self.context.clone(),
1334 id,
1335 }
1336 .into()
1337 }
1338
1339 fn create_pipeline_layout(
1340 &self,
1341 desc: &crate::PipelineLayoutDescriptor<'_>,
1342 ) -> dispatch::DispatchPipelineLayout {
1343 assert!(
1346 desc.bind_group_layouts.len() <= wgc::MAX_BIND_GROUPS,
1347 "Bind group layout count {} exceeds device bind group limit {}",
1348 desc.bind_group_layouts.len(),
1349 wgc::MAX_BIND_GROUPS
1350 );
1351
1352 let temp_layouts = desc
1353 .bind_group_layouts
1354 .iter()
1355 .map(|bgl| bgl.map(|bgl| bgl.inner.as_core().id))
1356 .collect::<ArrayVec<_, { wgc::MAX_BIND_GROUPS }>>();
1357 let descriptor = wgc::binding_model::PipelineLayoutDescriptor {
1358 label: desc.label.map(Borrowed),
1359 bind_group_layouts: Borrowed(&temp_layouts),
1360 immediate_size: desc.immediate_size,
1361 };
1362
1363 let (id, error) = self
1364 .context
1365 .0
1366 .device_create_pipeline_layout(self.id, &descriptor, None);
1367 if let Some(cause) = error {
1368 self.context.handle_error(
1369 &self.error_sink,
1370 cause,
1371 desc.label,
1372 "Device::create_pipeline_layout",
1373 );
1374 }
1375 CorePipelineLayout {
1376 context: self.context.clone(),
1377 id,
1378 }
1379 .into()
1380 }
1381
1382 fn create_render_pipeline(
1383 &self,
1384 desc: &crate::RenderPipelineDescriptor<'_>,
1385 ) -> dispatch::DispatchRenderPipeline {
1386 use wgc::pipeline as pipe;
1387
1388 let vertex_buffers: ArrayVec<_, { wgc::MAX_VERTEX_BUFFERS }> = desc
1389 .vertex
1390 .buffers
1391 .iter()
1392 .map(|vbuf| {
1393 vbuf.as_ref().map(|vbuf| pipe::VertexBufferLayout {
1394 array_stride: vbuf.array_stride,
1395 step_mode: vbuf.step_mode,
1396 attributes: Borrowed(vbuf.attributes),
1397 })
1398 })
1399 .collect();
1400
1401 let vert_constants = desc
1402 .vertex
1403 .compilation_options
1404 .constants
1405 .iter()
1406 .map(|&(key, value)| (String::from(key), value))
1407 .collect();
1408
1409 let descriptor = pipe::RenderPipelineDescriptor {
1410 label: desc.label.map(Borrowed),
1411 layout: desc.layout.map(|layout| layout.inner.as_core().id),
1412 vertex: pipe::VertexState {
1413 stage: pipe::ProgrammableStageDescriptor {
1414 module: desc.vertex.module.inner.as_core().id,
1415 entry_point: desc.vertex.entry_point.map(Borrowed),
1416 constants: vert_constants,
1417 zero_initialize_workgroup_memory: desc
1418 .vertex
1419 .compilation_options
1420 .zero_initialize_workgroup_memory,
1421 },
1422 buffers: Borrowed(&vertex_buffers),
1423 },
1424 primitive: desc.primitive,
1425 depth_stencil: desc.depth_stencil.clone(),
1426 multisample: desc.multisample,
1427 fragment: desc.fragment.as_ref().map(|frag| {
1428 let frag_constants = frag
1429 .compilation_options
1430 .constants
1431 .iter()
1432 .map(|&(key, value)| (String::from(key), value))
1433 .collect();
1434 pipe::FragmentState {
1435 stage: pipe::ProgrammableStageDescriptor {
1436 module: frag.module.inner.as_core().id,
1437 entry_point: frag.entry_point.map(Borrowed),
1438 constants: frag_constants,
1439 zero_initialize_workgroup_memory: frag
1440 .compilation_options
1441 .zero_initialize_workgroup_memory,
1442 },
1443 targets: Borrowed(frag.targets),
1444 }
1445 }),
1446 multiview_mask: desc.multiview_mask,
1447 cache: desc.cache.map(|cache| cache.inner.as_core().id),
1448 };
1449
1450 let (id, error) = self
1451 .context
1452 .0
1453 .device_create_render_pipeline(self.id, &descriptor, None);
1454 if let Some(cause) = error {
1455 if let wgc::pipeline::CreateRenderPipelineError::Internal { stage, ref error } = cause {
1456 log::error!("Shader translation error for stage {stage:?}: {error}");
1457 log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1458 }
1459 self.context.handle_error(
1460 &self.error_sink,
1461 cause,
1462 desc.label,
1463 "Device::create_render_pipeline",
1464 );
1465 }
1466 CoreRenderPipeline {
1467 context: self.context.clone(),
1468 id,
1469 error_sink: Arc::clone(&self.error_sink),
1470 }
1471 .into()
1472 }
1473
1474 fn create_mesh_pipeline(
1475 &self,
1476 desc: &crate::MeshPipelineDescriptor<'_>,
1477 ) -> dispatch::DispatchRenderPipeline {
1478 use wgc::pipeline as pipe;
1479
1480 let mesh_constants = desc
1481 .mesh
1482 .compilation_options
1483 .constants
1484 .iter()
1485 .map(|&(key, value)| (String::from(key), value))
1486 .collect();
1487 let descriptor = pipe::MeshPipelineDescriptor {
1488 label: desc.label.map(Borrowed),
1489 task: desc.task.as_ref().map(|task| {
1490 let task_constants = task
1491 .compilation_options
1492 .constants
1493 .iter()
1494 .map(|&(key, value)| (String::from(key), value))
1495 .collect();
1496 pipe::TaskState {
1497 stage: pipe::ProgrammableStageDescriptor {
1498 module: task.module.inner.as_core().id,
1499 entry_point: task.entry_point.map(Borrowed),
1500 constants: task_constants,
1501 zero_initialize_workgroup_memory: desc
1502 .mesh
1503 .compilation_options
1504 .zero_initialize_workgroup_memory,
1505 },
1506 }
1507 }),
1508 mesh: pipe::MeshState {
1509 stage: pipe::ProgrammableStageDescriptor {
1510 module: desc.mesh.module.inner.as_core().id,
1511 entry_point: desc.mesh.entry_point.map(Borrowed),
1512 constants: mesh_constants,
1513 zero_initialize_workgroup_memory: desc
1514 .mesh
1515 .compilation_options
1516 .zero_initialize_workgroup_memory,
1517 },
1518 },
1519 layout: desc.layout.map(|layout| layout.inner.as_core().id),
1520 primitive: desc.primitive,
1521 depth_stencil: desc.depth_stencil.clone(),
1522 multisample: desc.multisample,
1523 fragment: desc.fragment.as_ref().map(|frag| {
1524 let frag_constants = frag
1525 .compilation_options
1526 .constants
1527 .iter()
1528 .map(|&(key, value)| (String::from(key), value))
1529 .collect();
1530 pipe::FragmentState {
1531 stage: pipe::ProgrammableStageDescriptor {
1532 module: frag.module.inner.as_core().id,
1533 entry_point: frag.entry_point.map(Borrowed),
1534 constants: frag_constants,
1535 zero_initialize_workgroup_memory: frag
1536 .compilation_options
1537 .zero_initialize_workgroup_memory,
1538 },
1539 targets: Borrowed(frag.targets),
1540 }
1541 }),
1542 multiview: desc.multiview,
1543 cache: desc.cache.map(|cache| cache.inner.as_core().id),
1544 };
1545
1546 let (id, error) = self
1547 .context
1548 .0
1549 .device_create_mesh_pipeline(self.id, &descriptor, None);
1550 if let Some(cause) = error {
1551 if let wgc::pipeline::CreateRenderPipelineError::Internal { stage, ref error } = cause {
1552 log::error!("Shader translation error for stage {stage:?}: {error}");
1553 log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1554 }
1555 self.context.handle_error(
1556 &self.error_sink,
1557 cause,
1558 desc.label,
1559 "Device::create_render_pipeline",
1560 );
1561 }
1562 CoreRenderPipeline {
1563 context: self.context.clone(),
1564 id,
1565 error_sink: Arc::clone(&self.error_sink),
1566 }
1567 .into()
1568 }
1569
1570 fn create_compute_pipeline(
1571 &self,
1572 desc: &crate::ComputePipelineDescriptor<'_>,
1573 ) -> dispatch::DispatchComputePipeline {
1574 use wgc::pipeline as pipe;
1575
1576 let constants = desc
1577 .compilation_options
1578 .constants
1579 .iter()
1580 .map(|&(key, value)| (String::from(key), value))
1581 .collect();
1582
1583 let descriptor = pipe::ComputePipelineDescriptor {
1584 label: desc.label.map(Borrowed),
1585 layout: desc.layout.map(|pll| pll.inner.as_core().id),
1586 stage: pipe::ProgrammableStageDescriptor {
1587 module: desc.module.inner.as_core().id,
1588 entry_point: desc.entry_point.map(Borrowed),
1589 constants,
1590 zero_initialize_workgroup_memory: desc
1591 .compilation_options
1592 .zero_initialize_workgroup_memory,
1593 },
1594 cache: desc.cache.map(|cache| cache.inner.as_core().id),
1595 };
1596
1597 let (id, error) = self
1598 .context
1599 .0
1600 .device_create_compute_pipeline(self.id, &descriptor, None);
1601 if let Some(cause) = error {
1602 if let wgc::pipeline::CreateComputePipelineError::Internal(ref error) = cause {
1603 log::error!(
1604 "Shader translation error for stage {:?}: {}",
1605 wgt::ShaderStages::COMPUTE,
1606 error
1607 );
1608 log::error!("Please report it to https://github.com/gfx-rs/wgpu");
1609 }
1610 self.context.handle_error(
1611 &self.error_sink,
1612 cause,
1613 desc.label,
1614 "Device::create_compute_pipeline",
1615 );
1616 }
1617 CoreComputePipeline {
1618 context: self.context.clone(),
1619 id,
1620 error_sink: Arc::clone(&self.error_sink),
1621 }
1622 .into()
1623 }
1624
1625 unsafe fn create_pipeline_cache(
1626 &self,
1627 desc: &crate::PipelineCacheDescriptor<'_>,
1628 ) -> dispatch::DispatchPipelineCache {
1629 use wgc::pipeline as pipe;
1630
1631 let descriptor = pipe::PipelineCacheDescriptor {
1632 label: desc.label.map(Borrowed),
1633 data: desc.data.map(Borrowed),
1634 fallback: desc.fallback,
1635 };
1636 let (id, error) = unsafe {
1637 self.context
1638 .0
1639 .device_create_pipeline_cache(self.id, &descriptor, None)
1640 };
1641 if let Some(cause) = error {
1642 self.context.handle_error(
1643 &self.error_sink,
1644 cause,
1645 desc.label,
1646 "Device::device_create_pipeline_cache_init",
1647 );
1648 }
1649 CorePipelineCache {
1650 context: self.context.clone(),
1651 id,
1652 }
1653 .into()
1654 }
1655
1656 fn create_buffer(&self, desc: &crate::BufferDescriptor<'_>) -> dispatch::DispatchBuffer {
1657 let (id, error) = self.context.0.device_create_buffer(
1658 self.id,
1659 &desc.map_label(|l| l.map(Borrowed)),
1660 None,
1661 );
1662 if let Some(cause) = error {
1663 self.context
1664 .handle_error(&self.error_sink, cause, desc.label, "Device::create_buffer");
1665 }
1666
1667 CoreBuffer {
1668 context: self.context.clone(),
1669 id,
1670 error_sink: Arc::clone(&self.error_sink),
1671 }
1672 .into()
1673 }
1674
1675 fn create_texture(&self, desc: &crate::TextureDescriptor<'_>) -> dispatch::DispatchTexture {
1676 let wgt_desc = desc.map_label_and_view_formats(|l| l.map(Borrowed), |v| v.to_vec());
1677 let (id, error) = self
1678 .context
1679 .0
1680 .device_create_texture(self.id, &wgt_desc, None);
1681 if let Some(cause) = error {
1682 self.context.handle_error(
1683 &self.error_sink,
1684 cause,
1685 desc.label,
1686 "Device::create_texture",
1687 );
1688 }
1689
1690 CoreTexture {
1691 context: self.context.clone(),
1692 id,
1693 error_sink: Arc::clone(&self.error_sink),
1694 }
1695 .into()
1696 }
1697
1698 fn create_external_texture(
1699 &self,
1700 desc: &crate::ExternalTextureDescriptor<'_>,
1701 planes: &[&crate::TextureView],
1702 ) -> dispatch::DispatchExternalTexture {
1703 let wgt_desc = desc.map_label(|l| l.map(Borrowed));
1704 let planes = planes
1705 .iter()
1706 .map(|plane| plane.inner.as_core().id)
1707 .collect::<Vec<_>>();
1708 let (id, error) = self
1709 .context
1710 .0
1711 .device_create_external_texture(self.id, &wgt_desc, &planes, None);
1712 if let Some(cause) = error {
1713 self.context.handle_error(
1714 &self.error_sink,
1715 cause,
1716 desc.label,
1717 "Device::create_external_texture",
1718 );
1719 }
1720
1721 CoreExternalTexture {
1722 context: self.context.clone(),
1723 id,
1724 }
1725 .into()
1726 }
1727
1728 fn create_blas(
1729 &self,
1730 desc: &crate::CreateBlasDescriptor<'_>,
1731 sizes: crate::BlasGeometrySizeDescriptors,
1732 ) -> (Option<u64>, dispatch::DispatchBlas) {
1733 let global = &self.context.0;
1734 let (id, handle, error) =
1735 global.device_create_blas(self.id, &desc.map_label(|l| l.map(Borrowed)), sizes, None);
1736 if let Some(cause) = error {
1737 self.context
1738 .handle_error(&self.error_sink, cause, desc.label, "Device::create_blas");
1739 }
1740 (
1741 handle,
1742 CoreBlas {
1743 context: self.context.clone(),
1744 id,
1745 error_sink: Arc::clone(&self.error_sink),
1746 }
1747 .into(),
1748 )
1749 }
1750
1751 fn create_tlas(&self, desc: &crate::CreateTlasDescriptor<'_>) -> dispatch::DispatchTlas {
1752 let global = &self.context.0;
1753 let (id, error) =
1754 global.device_create_tlas(self.id, &desc.map_label(|l| l.map(Borrowed)), None);
1755 if let Some(cause) = error {
1756 self.context
1757 .handle_error(&self.error_sink, cause, desc.label, "Device::create_tlas");
1758 }
1759 CoreTlas {
1760 context: self.context.clone(),
1761 id,
1762 }
1764 .into()
1765 }
1766
1767 fn create_sampler(&self, desc: &crate::SamplerDescriptor<'_>) -> dispatch::DispatchSampler {
1768 let descriptor = wgc::resource::SamplerDescriptor {
1769 label: desc.label.map(Borrowed),
1770 address_modes: [
1771 desc.address_mode_u,
1772 desc.address_mode_v,
1773 desc.address_mode_w,
1774 ],
1775 mag_filter: desc.mag_filter,
1776 min_filter: desc.min_filter,
1777 mipmap_filter: desc.mipmap_filter,
1778 lod_min_clamp: desc.lod_min_clamp,
1779 lod_max_clamp: desc.lod_max_clamp,
1780 compare: desc.compare,
1781 anisotropy_clamp: desc.anisotropy_clamp,
1782 border_color: desc.border_color,
1783 };
1784
1785 let (id, error) = self
1786 .context
1787 .0
1788 .device_create_sampler(self.id, &descriptor, None);
1789 if let Some(cause) = error {
1790 self.context.handle_error(
1791 &self.error_sink,
1792 cause,
1793 desc.label,
1794 "Device::create_sampler",
1795 );
1796 }
1797 CoreSampler {
1798 context: self.context.clone(),
1799 id,
1800 }
1801 .into()
1802 }
1803
1804 fn create_query_set(&self, desc: &crate::QuerySetDescriptor<'_>) -> dispatch::DispatchQuerySet {
1805 let (id, error) = self.context.0.device_create_query_set(
1806 self.id,
1807 &desc.map_label(|l| l.map(Borrowed)),
1808 None,
1809 );
1810 if let Some(cause) = error {
1811 self.context
1812 .handle_error_nolabel(&self.error_sink, cause, "Device::create_query_set");
1813 }
1814 CoreQuerySet {
1815 context: self.context.clone(),
1816 id,
1817 }
1818 .into()
1819 }
1820
1821 fn create_command_encoder(
1822 &self,
1823 desc: &crate::CommandEncoderDescriptor<'_>,
1824 ) -> dispatch::DispatchCommandEncoder {
1825 let (id, error) = self.context.0.device_create_command_encoder(
1826 self.id,
1827 &desc.map_label(|l| l.map(Borrowed)),
1828 None,
1829 );
1830 if let Some(cause) = error {
1831 self.context.handle_error(
1832 &self.error_sink,
1833 cause,
1834 desc.label,
1835 "Device::create_command_encoder",
1836 );
1837 }
1838
1839 CoreCommandEncoder {
1840 context: self.context.clone(),
1841 id,
1842 error_sink: Arc::clone(&self.error_sink),
1843 }
1844 .into()
1845 }
1846
1847 fn create_render_bundle_encoder(
1848 &self,
1849 desc: &crate::RenderBundleEncoderDescriptor<'_>,
1850 ) -> dispatch::DispatchRenderBundleEncoder {
1851 let descriptor = wgc::command::RenderBundleEncoderDescriptor {
1852 label: desc.label.map(Borrowed),
1853 color_formats: Borrowed(desc.color_formats),
1854 depth_stencil: desc.depth_stencil,
1855 sample_count: desc.sample_count,
1856 multiview: desc.multiview,
1857 };
1858 let (encoder, error) = self
1859 .context
1860 .0
1861 .device_create_render_bundle_encoder(self.id, &descriptor);
1862 if let Some(cause) = error {
1863 self.context.handle_error(
1864 &self.error_sink,
1865 cause,
1866 desc.label,
1867 "Device::create_render_bundle_encoder",
1868 );
1869 }
1870
1871 CoreRenderBundleEncoder {
1872 context: self.context.clone(),
1873 encoder,
1874 id: crate::cmp::Identifier::create(),
1875 }
1876 .into()
1877 }
1878
1879 fn set_device_lost_callback(&self, device_lost_callback: dispatch::BoxDeviceLostCallback) {
1880 self.context
1881 .0
1882 .device_set_device_lost_closure(self.id, device_lost_callback);
1883 }
1884
1885 fn on_uncaptured_error(&self, handler: Arc<dyn crate::UncapturedErrorHandler>) {
1886 let mut error_sink = self.error_sink.lock();
1887 error_sink.uncaptured_handler = Some(handler);
1888 }
1889
1890 fn push_error_scope(&self, filter: crate::ErrorFilter) -> u32 {
1891 let mut error_sink = self.error_sink.lock();
1892 let thread_id = thread_id::ThreadId::current();
1893 let scopes = error_sink.scopes.entry(thread_id).or_default();
1894 let index = scopes
1895 .len()
1896 .try_into()
1897 .expect("Greater than 2^32 nested error scopes");
1898 scopes.push(ErrorScope {
1899 error: None,
1900 filter,
1901 });
1902 index
1903 }
1904
1905 fn pop_error_scope(&self, index: u32) -> Pin<Box<dyn dispatch::PopErrorScopeFuture>> {
1906 let mut error_sink = self.error_sink.lock();
1907
1908 let is_panicking = crate::util::is_panicking();
1911 let thread_id = thread_id::ThreadId::current();
1912 let err = "Mismatched pop_error_scope call: no error scope for this thread. Error scopes are thread-local.";
1913 let scopes = match error_sink.scopes.get_mut(&thread_id) {
1914 Some(s) => s,
1915 None => {
1916 if !is_panicking {
1917 panic!("{err}");
1918 } else {
1919 return Box::pin(ready(None));
1920 }
1921 }
1922 };
1923 if scopes.is_empty() && !is_panicking {
1924 panic!("{err}");
1925 }
1926 if index as usize != scopes.len() - 1 && !is_panicking {
1927 panic!(
1928 "Mismatched pop_error_scope call: error scopes must be popped in reverse order."
1929 );
1930 }
1931
1932 let scope = match scopes.pop() {
1937 Some(s) => s,
1938 None if !is_panicking => unreachable!(),
1939 None => return Box::pin(ready(None)),
1940 };
1941
1942 Box::pin(ready(scope.error))
1943 }
1944
1945 unsafe fn start_graphics_debugger_capture(&self) {
1946 unsafe {
1947 self.context
1948 .0
1949 .device_start_graphics_debugger_capture(self.id)
1950 };
1951 }
1952
1953 unsafe fn stop_graphics_debugger_capture(&self) {
1954 unsafe {
1955 self.context
1956 .0
1957 .device_stop_graphics_debugger_capture(self.id)
1958 };
1959 }
1960
1961 fn poll(&self, poll_type: wgt::PollType<u64>) -> Result<crate::PollStatus, crate::PollError> {
1962 match self.context.0.device_poll(self.id, poll_type) {
1963 Ok(status) => Ok(status),
1964 Err(err) => {
1965 if let Some(poll_error) = err.to_poll_error() {
1966 return Err(poll_error);
1967 }
1968
1969 self.context.handle_error_fatal(err, "Device::poll")
1970 }
1971 }
1972 }
1973
1974 fn get_internal_counters(&self) -> crate::InternalCounters {
1975 self.context.0.device_get_internal_counters(self.id)
1976 }
1977
1978 fn generate_allocator_report(&self) -> Option<wgt::AllocatorReport> {
1979 self.context.0.device_generate_allocator_report(self.id)
1980 }
1981
1982 fn destroy(&self) {
1983 self.context.0.device_destroy(self.id);
1984 }
1985}
1986
1987impl Drop for CoreDevice {
1988 fn drop(&mut self) {
1989 self.context.0.device_drop(self.id)
1990 }
1991}
1992
1993impl dispatch::QueueInterface for CoreQueue {
1994 fn write_buffer(
1995 &self,
1996 buffer: &dispatch::DispatchBuffer,
1997 offset: crate::BufferAddress,
1998 data: &[u8],
1999 ) {
2000 let buffer = buffer.as_core();
2001
2002 match self
2003 .context
2004 .0
2005 .queue_write_buffer(self.id, buffer.id, offset, data)
2006 {
2007 Ok(()) => (),
2008 Err(err) => {
2009 self.context
2010 .handle_error_nolabel(&self.error_sink, err, "Queue::write_buffer")
2011 }
2012 }
2013 }
2014
2015 fn create_staging_buffer(
2016 &self,
2017 size: crate::BufferSize,
2018 ) -> Option<dispatch::DispatchQueueWriteBuffer> {
2019 match self
2020 .context
2021 .0
2022 .queue_create_staging_buffer(self.id, size, None)
2023 {
2024 Ok((buffer_id, ptr)) => Some(
2025 CoreQueueWriteBuffer {
2026 buffer_id,
2027 mapping: CoreBufferMappedRange {
2028 ptr,
2029 size: size.get() as usize,
2030 },
2031 }
2032 .into(),
2033 ),
2034 Err(err) => {
2035 self.context.handle_error_nolabel(
2036 &self.error_sink,
2037 err,
2038 "Queue::write_buffer_with",
2039 );
2040 None
2041 }
2042 }
2043 }
2044
2045 fn validate_write_buffer(
2046 &self,
2047 buffer: &dispatch::DispatchBuffer,
2048 offset: wgt::BufferAddress,
2049 size: wgt::BufferSize,
2050 ) -> Option<()> {
2051 let buffer = buffer.as_core();
2052
2053 match self
2054 .context
2055 .0
2056 .queue_validate_write_buffer(self.id, buffer.id, offset, size)
2057 {
2058 Ok(()) => Some(()),
2059 Err(err) => {
2060 self.context.handle_error_nolabel(
2061 &self.error_sink,
2062 err,
2063 "Queue::write_buffer_with",
2064 );
2065 None
2066 }
2067 }
2068 }
2069
2070 fn write_staging_buffer(
2071 &self,
2072 buffer: &dispatch::DispatchBuffer,
2073 offset: crate::BufferAddress,
2074 staging_buffer: &dispatch::DispatchQueueWriteBuffer,
2075 ) {
2076 let buffer = buffer.as_core();
2077 let staging_buffer = staging_buffer.as_core();
2078
2079 match self.context.0.queue_write_staging_buffer(
2080 self.id,
2081 buffer.id,
2082 offset,
2083 staging_buffer.buffer_id,
2084 ) {
2085 Ok(()) => (),
2086 Err(err) => {
2087 self.context.handle_error_nolabel(
2088 &self.error_sink,
2089 err,
2090 "Queue::write_buffer_with",
2091 );
2092 }
2093 }
2094 }
2095
2096 fn write_texture(
2097 &self,
2098 texture: crate::TexelCopyTextureInfo<'_>,
2099 data: &[u8],
2100 data_layout: crate::TexelCopyBufferLayout,
2101 size: crate::Extent3d,
2102 ) {
2103 match self.context.0.queue_write_texture(
2104 self.id,
2105 &map_texture_copy_view(texture),
2106 data,
2107 &data_layout,
2108 &size,
2109 ) {
2110 Ok(()) => (),
2111 Err(err) => {
2112 self.context
2113 .handle_error_nolabel(&self.error_sink, err, "Queue::write_texture")
2114 }
2115 }
2116 }
2117
2118 #[cfg(web)]
2121 #[cfg_attr(not(webgl), expect(unused_variables))]
2122 fn copy_external_image_to_texture(
2123 &self,
2124 source: &crate::CopyExternalImageSourceInfo,
2125 dest: crate::CopyExternalImageDestInfo<&crate::api::Texture>,
2126 size: crate::Extent3d,
2127 ) {
2128 #[cfg(webgl)]
2129 match self.context.0.queue_copy_external_image_to_texture(
2130 self.id,
2131 source,
2132 map_texture_tagged_copy_view(dest),
2133 size,
2134 ) {
2135 Ok(()) => (),
2136 Err(err) => self.context.handle_error_nolabel(
2137 &self.error_sink,
2138 err,
2139 "Queue::copy_external_image_to_texture",
2140 ),
2141 }
2142 }
2143
2144 fn submit(
2145 &self,
2146 command_buffers: &mut dyn Iterator<Item = dispatch::DispatchCommandBuffer>,
2147 ) -> u64 {
2148 let temp_command_buffers = command_buffers.collect::<SmallVec<[_; 4]>>();
2149 let command_buffer_ids = temp_command_buffers
2150 .iter()
2151 .map(|cmdbuf| cmdbuf.as_core().id)
2152 .collect::<SmallVec<[_; 4]>>();
2153
2154 let index = match self.context.0.queue_submit(self.id, &command_buffer_ids) {
2155 Ok(index) => index,
2156 Err((index, err)) => {
2157 self.context
2158 .handle_error_nolabel(&self.error_sink, err, "Queue::submit");
2159 index
2160 }
2161 };
2162
2163 drop(temp_command_buffers);
2164
2165 index
2166 }
2167
2168 fn get_timestamp_period(&self) -> f32 {
2169 self.context.0.queue_get_timestamp_period(self.id)
2170 }
2171
2172 fn on_submitted_work_done(&self, callback: dispatch::BoxSubmittedWorkDoneCallback) {
2173 self.context
2174 .0
2175 .queue_on_submitted_work_done(self.id, callback);
2176 }
2177
2178 fn compact_blas(&self, blas: &dispatch::DispatchBlas) -> (Option<u64>, dispatch::DispatchBlas) {
2179 let (id, handle, error) =
2180 self.context
2181 .0
2182 .queue_compact_blas(self.id, blas.as_core().id, None);
2183
2184 if let Some(cause) = error {
2185 self.context
2186 .handle_error_nolabel(&self.error_sink, cause, "Queue::compact_blas");
2187 }
2188 (
2189 handle,
2190 CoreBlas {
2191 context: self.context.clone(),
2192 id,
2193 error_sink: Arc::clone(&self.error_sink),
2194 }
2195 .into(),
2196 )
2197 }
2198
2199 fn present(&self, detail: &dispatch::DispatchSurfaceOutputDetail) {
2200 let detail = detail.as_core();
2201 match self.context.0.surface_present(detail.surface_id) {
2202 Ok(_status) => (),
2203 Err(err) => {
2204 self.context
2205 .handle_error_nolabel(&self.error_sink, err, "Queue::present");
2206 }
2207 }
2208 }
2209}
2210
2211impl Drop for CoreQueue {
2212 fn drop(&mut self) {
2213 self.context.0.queue_drop(self.id)
2214 }
2215}
2216
2217impl dispatch::ShaderModuleInterface for CoreShaderModule {
2218 fn get_compilation_info(&self) -> Pin<Box<dyn dispatch::ShaderCompilationInfoFuture>> {
2219 Box::pin(ready(self.compilation_info.clone()))
2220 }
2221}
2222
2223impl Drop for CoreShaderModule {
2224 fn drop(&mut self) {
2225 self.context.0.shader_module_drop(self.id)
2226 }
2227}
2228
2229impl dispatch::BindGroupLayoutInterface for CoreBindGroupLayout {}
2230
2231impl Drop for CoreBindGroupLayout {
2232 fn drop(&mut self) {
2233 self.context.0.bind_group_layout_drop(self.id)
2234 }
2235}
2236
2237impl dispatch::BindGroupInterface for CoreBindGroup {}
2238
2239impl Drop for CoreBindGroup {
2240 fn drop(&mut self) {
2241 self.context.0.bind_group_drop(self.id)
2242 }
2243}
2244
2245impl dispatch::TextureViewInterface for CoreTextureView {}
2246
2247impl Drop for CoreTextureView {
2248 fn drop(&mut self) {
2249 self.context.0.texture_view_drop(self.id);
2250 }
2251}
2252
2253impl dispatch::ExternalTextureInterface for CoreExternalTexture {
2254 fn destroy(&self) {
2255 self.context.0.external_texture_destroy(self.id);
2256 }
2257}
2258
2259impl Drop for CoreExternalTexture {
2260 fn drop(&mut self) {
2261 self.context.0.external_texture_drop(self.id);
2262 }
2263}
2264
2265impl dispatch::SamplerInterface for CoreSampler {}
2266
2267impl Drop for CoreSampler {
2268 fn drop(&mut self) {
2269 self.context.0.sampler_drop(self.id)
2270 }
2271}
2272
2273impl dispatch::BufferInterface for CoreBuffer {
2274 fn map_async(
2275 &self,
2276 mode: crate::MapMode,
2277 range: Range<crate::BufferAddress>,
2278 callback: dispatch::BufferMapCallback,
2279 ) {
2280 let operation = wgc::resource::BufferMapOperation {
2281 host: match mode {
2282 MapMode::Read => wgc::device::HostMap::Read,
2283 MapMode::Write => wgc::device::HostMap::Write,
2284 },
2285 callback: Some(Box::new(|status| {
2286 let res = status.map_err(|_| crate::BufferAsyncError);
2287 callback(res);
2288 })),
2289 };
2290
2291 match self.context.0.buffer_map_async(
2292 self.id,
2293 range.start,
2294 Some(range.end - range.start),
2295 operation,
2296 ) {
2297 Ok(_) => (),
2298 Err(cause) => {
2299 self.context
2300 .handle_error_nolabel(&self.error_sink, cause, "Buffer::map_async")
2301 }
2302 }
2303 }
2304
2305 fn get_mapped_range(
2306 &self,
2307 sub_range: Range<crate::BufferAddress>,
2308 ) -> Result<dispatch::DispatchBufferMappedRange, crate::MapRangeError> {
2309 let size = sub_range.end - sub_range.start;
2310 self.context
2311 .0
2312 .buffer_get_mapped_range(self.id, sub_range.start, Some(size))
2313 .map(|(ptr, size)| {
2314 CoreBufferMappedRange {
2315 ptr,
2316 size: size as usize,
2317 }
2318 .into()
2319 })
2320 .map_err(|err| crate::MapRangeError(self.context.format_error(&err)))
2321 }
2322
2323 fn unmap(&self) {
2324 match self.context.0.buffer_unmap(self.id) {
2325 Ok(()) => (),
2326 Err(cause) => {
2327 self.context
2328 .handle_error_nolabel(&self.error_sink, cause, "Buffer::buffer_unmap")
2329 }
2330 }
2331 }
2332
2333 fn destroy(&self) {
2334 self.context.0.buffer_destroy(self.id);
2335 }
2336}
2337
2338impl Drop for CoreBuffer {
2339 fn drop(&mut self) {
2340 self.context.0.buffer_drop(self.id)
2341 }
2342}
2343
2344impl dispatch::TextureInterface for CoreTexture {
2345 fn create_view(
2346 &self,
2347 desc: &crate::TextureViewDescriptor<'_>,
2348 ) -> dispatch::DispatchTextureView {
2349 let descriptor = wgc::resource::TextureViewDescriptor {
2350 label: desc.label.map(Borrowed),
2351 format: desc.format,
2352 dimension: desc.dimension,
2353 usage: desc.usage,
2354 range: wgt::ImageSubresourceRange {
2355 aspect: desc.aspect,
2356 base_mip_level: desc.base_mip_level,
2357 mip_level_count: desc.mip_level_count,
2358 base_array_layer: desc.base_array_layer,
2359 array_layer_count: desc.array_layer_count,
2360 },
2361 };
2362 let (id, error) = self
2363 .context
2364 .0
2365 .texture_create_view(self.id, &descriptor, None);
2366 if let Some(cause) = error {
2367 self.context
2368 .handle_error(&self.error_sink, cause, desc.label, "Texture::create_view");
2369 }
2370 CoreTextureView {
2371 context: self.context.clone(),
2372 id,
2373 }
2374 .into()
2375 }
2376
2377 fn destroy(&self) {
2378 self.context.0.texture_destroy(self.id);
2379 }
2380}
2381
2382impl Drop for CoreTexture {
2383 fn drop(&mut self) {
2384 self.context.0.texture_drop(self.id)
2385 }
2386}
2387
2388impl dispatch::BlasInterface for CoreBlas {
2389 fn prepare_compact_async(&self, callback: BlasCompactCallback) {
2390 let callback: Option<wgc::resource::BlasCompactCallback> =
2391 Some(Box::new(|status: BlasPrepareCompactResult| {
2392 let res = status.map_err(|_| crate::BlasAsyncError);
2393 callback(res);
2394 }));
2395
2396 match self.context.0.blas_prepare_compact_async(self.id, callback) {
2397 Ok(_) => (),
2398 Err(cause) => self.context.handle_error_nolabel(
2399 &self.error_sink,
2400 cause,
2401 "Blas::prepare_compact_async",
2402 ),
2403 }
2404 }
2405
2406 fn ready_for_compaction(&self) -> bool {
2407 match self.context.0.ready_for_compaction(self.id) {
2408 Ok(ready) => ready,
2409 Err(cause) => {
2410 self.context.handle_error_nolabel(
2411 &self.error_sink,
2412 cause,
2413 "Blas::ready_for_compaction",
2414 );
2415 false
2417 }
2418 }
2419 }
2420}
2421
2422impl Drop for CoreBlas {
2423 fn drop(&mut self) {
2424 self.context.0.blas_drop(self.id)
2425 }
2426}
2427
2428impl dispatch::TlasInterface for CoreTlas {}
2429
2430impl Drop for CoreTlas {
2431 fn drop(&mut self) {
2432 self.context.0.tlas_drop(self.id)
2433 }
2434}
2435
2436impl dispatch::QuerySetInterface for CoreQuerySet {
2437 fn destroy(&self) {
2438 self.context.0.query_set_destroy(self.id);
2439 }
2440}
2441
2442impl Drop for CoreQuerySet {
2443 fn drop(&mut self) {
2444 self.context.0.query_set_drop(self.id)
2445 }
2446}
2447
2448impl dispatch::PipelineLayoutInterface for CorePipelineLayout {}
2449
2450impl Drop for CorePipelineLayout {
2451 fn drop(&mut self) {
2452 self.context.0.pipeline_layout_drop(self.id)
2453 }
2454}
2455
2456impl dispatch::RenderPipelineInterface for CoreRenderPipeline {
2457 fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2458 let (id, error) = self
2459 .context
2460 .0
2461 .render_pipeline_get_bind_group_layout(self.id, index, None);
2462 if let Some(err) = error {
2463 self.context.handle_error_nolabel(
2464 &self.error_sink,
2465 err,
2466 "RenderPipeline::get_bind_group_layout",
2467 )
2468 }
2469 CoreBindGroupLayout {
2470 context: self.context.clone(),
2471 id,
2472 }
2473 .into()
2474 }
2475}
2476
2477impl Drop for CoreRenderPipeline {
2478 fn drop(&mut self) {
2479 self.context.0.render_pipeline_drop(self.id)
2480 }
2481}
2482
2483impl dispatch::ComputePipelineInterface for CoreComputePipeline {
2484 fn get_bind_group_layout(&self, index: u32) -> dispatch::DispatchBindGroupLayout {
2485 let (id, error) = self
2486 .context
2487 .0
2488 .compute_pipeline_get_bind_group_layout(self.id, index, None);
2489 if let Some(err) = error {
2490 self.context.handle_error_nolabel(
2491 &self.error_sink,
2492 err,
2493 "ComputePipeline::get_bind_group_layout",
2494 )
2495 }
2496 CoreBindGroupLayout {
2497 context: self.context.clone(),
2498 id,
2499 }
2500 .into()
2501 }
2502}
2503
2504impl Drop for CoreComputePipeline {
2505 fn drop(&mut self) {
2506 self.context.0.compute_pipeline_drop(self.id)
2507 }
2508}
2509
2510impl dispatch::PipelineCacheInterface for CorePipelineCache {
2511 fn get_data(&self) -> Option<Vec<u8>> {
2512 self.context.0.pipeline_cache_get_data(self.id)
2513 }
2514}
2515
2516impl Drop for CorePipelineCache {
2517 fn drop(&mut self) {
2518 self.context.0.pipeline_cache_drop(self.id)
2519 }
2520}
2521
2522impl dispatch::CommandEncoderInterface for CoreCommandEncoder {
2523 fn copy_buffer_to_buffer(
2524 &self,
2525 source: &dispatch::DispatchBuffer,
2526 source_offset: crate::BufferAddress,
2527 destination: &dispatch::DispatchBuffer,
2528 destination_offset: crate::BufferAddress,
2529 copy_size: Option<crate::BufferAddress>,
2530 ) {
2531 let source = source.as_core();
2532 let destination = destination.as_core();
2533
2534 if let Err(cause) = self.context.0.command_encoder_copy_buffer_to_buffer(
2535 self.id,
2536 source.id,
2537 source_offset,
2538 destination.id,
2539 destination_offset,
2540 copy_size,
2541 ) {
2542 self.context.handle_error_nolabel(
2543 &self.error_sink,
2544 cause,
2545 "CommandEncoder::copy_buffer_to_buffer",
2546 );
2547 }
2548 }
2549
2550 fn copy_buffer_to_texture(
2551 &self,
2552 source: crate::TexelCopyBufferInfo<'_>,
2553 destination: crate::TexelCopyTextureInfo<'_>,
2554 copy_size: crate::Extent3d,
2555 ) {
2556 if let Err(cause) = self.context.0.command_encoder_copy_buffer_to_texture(
2557 self.id,
2558 &map_buffer_copy_view(source),
2559 &map_texture_copy_view(destination),
2560 ©_size,
2561 ) {
2562 self.context.handle_error_nolabel(
2563 &self.error_sink,
2564 cause,
2565 "CommandEncoder::copy_buffer_to_texture",
2566 );
2567 }
2568 }
2569
2570 fn copy_texture_to_buffer(
2571 &self,
2572 source: crate::TexelCopyTextureInfo<'_>,
2573 destination: crate::TexelCopyBufferInfo<'_>,
2574 copy_size: crate::Extent3d,
2575 ) {
2576 if let Err(cause) = self.context.0.command_encoder_copy_texture_to_buffer(
2577 self.id,
2578 &map_texture_copy_view(source),
2579 &map_buffer_copy_view(destination),
2580 ©_size,
2581 ) {
2582 self.context.handle_error_nolabel(
2583 &self.error_sink,
2584 cause,
2585 "CommandEncoder::copy_texture_to_buffer",
2586 );
2587 }
2588 }
2589
2590 fn copy_texture_to_texture(
2591 &self,
2592 source: crate::TexelCopyTextureInfo<'_>,
2593 destination: crate::TexelCopyTextureInfo<'_>,
2594 copy_size: crate::Extent3d,
2595 ) {
2596 if let Err(cause) = self.context.0.command_encoder_copy_texture_to_texture(
2597 self.id,
2598 &map_texture_copy_view(source),
2599 &map_texture_copy_view(destination),
2600 ©_size,
2601 ) {
2602 self.context.handle_error_nolabel(
2603 &self.error_sink,
2604 cause,
2605 "CommandEncoder::copy_texture_to_texture",
2606 );
2607 }
2608 }
2609
2610 fn begin_compute_pass(
2611 &self,
2612 desc: &crate::ComputePassDescriptor<'_>,
2613 ) -> dispatch::DispatchComputePass {
2614 let timestamp_writes =
2615 desc.timestamp_writes
2616 .as_ref()
2617 .map(|tw| wgc::command::PassTimestampWrites {
2618 query_set: tw.query_set.inner.as_core().id,
2619 beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
2620 end_of_pass_write_index: tw.end_of_pass_write_index,
2621 });
2622
2623 let (pass, err) = self.context.0.command_encoder_begin_compute_pass(
2624 self.id,
2625 &wgc::command::ComputePassDescriptor {
2626 label: desc.label.map(Borrowed),
2627 timestamp_writes,
2628 },
2629 );
2630
2631 if let Some(cause) = err {
2632 self.context.handle_error(
2633 &self.error_sink,
2634 cause,
2635 desc.label,
2636 "CommandEncoder::begin_compute_pass",
2637 );
2638 }
2639
2640 CoreComputePass {
2641 context: self.context.clone(),
2642 pass,
2643 error_sink: self.error_sink.clone(),
2644 id: crate::cmp::Identifier::create(),
2645 }
2646 .into()
2647 }
2648
2649 fn begin_render_pass(
2650 &self,
2651 desc: &crate::RenderPassDescriptor<'_>,
2652 ) -> dispatch::DispatchRenderPass {
2653 let colors = desc
2654 .color_attachments
2655 .iter()
2656 .map(|ca| {
2657 ca.as_ref()
2658 .map(|at| wgc::command::RenderPassColorAttachment {
2659 view: at.view.inner.as_core().id,
2660 depth_slice: at.depth_slice,
2661 resolve_target: at.resolve_target.map(|view| view.inner.as_core().id),
2662 load_op: at.ops.load,
2663 store_op: at.ops.store,
2664 })
2665 })
2666 .collect::<Vec<_>>();
2667
2668 let depth_stencil = desc.depth_stencil_attachment.as_ref().map(|dsa| {
2669 wgc::command::RenderPassDepthStencilAttachment {
2670 view: dsa.view.inner.as_core().id,
2671 depth: map_pass_channel(dsa.depth_ops.as_ref()),
2672 stencil: map_pass_channel(dsa.stencil_ops.as_ref()),
2673 }
2674 });
2675
2676 let timestamp_writes =
2677 desc.timestamp_writes
2678 .as_ref()
2679 .map(|tw| wgc::command::PassTimestampWrites {
2680 query_set: tw.query_set.inner.as_core().id,
2681 beginning_of_pass_write_index: tw.beginning_of_pass_write_index,
2682 end_of_pass_write_index: tw.end_of_pass_write_index,
2683 });
2684
2685 let (pass, err) = self.context.0.command_encoder_begin_render_pass(
2686 self.id,
2687 &wgc::command::RenderPassDescriptor {
2688 label: desc.label.map(Borrowed),
2689 timestamp_writes,
2690 color_attachments: Borrowed(&colors),
2691 depth_stencil_attachment: depth_stencil,
2692 occlusion_query_set: desc.occlusion_query_set.map(|qs| qs.inner.as_core().id),
2693 multiview_mask: desc.multiview_mask,
2694 },
2695 );
2696
2697 if let Some(cause) = err {
2698 self.context.handle_error(
2699 &self.error_sink,
2700 cause,
2701 desc.label,
2702 "CommandEncoder::begin_render_pass",
2703 );
2704 }
2705
2706 CoreRenderPass {
2707 context: self.context.clone(),
2708 pass,
2709 error_sink: self.error_sink.clone(),
2710 id: crate::cmp::Identifier::create(),
2711 }
2712 .into()
2713 }
2714
2715 fn finish(&mut self) -> dispatch::DispatchCommandBuffer {
2716 let descriptor = wgt::CommandBufferDescriptor::default();
2717 let (id, opt_label_and_error) =
2718 self.context
2719 .0
2720 .command_encoder_finish(self.id, &descriptor, None);
2721 if let Some((label, cause)) = opt_label_and_error {
2722 self.context
2723 .handle_error(&self.error_sink, cause, Some(&label), "a CommandEncoder");
2724 }
2725 CoreCommandBuffer {
2726 context: self.context.clone(),
2727 id,
2728 }
2729 .into()
2730 }
2731
2732 fn clear_texture(
2733 &self,
2734 texture: &dispatch::DispatchTexture,
2735 subresource_range: &crate::ImageSubresourceRange,
2736 ) {
2737 let texture = texture.as_core();
2738
2739 if let Err(cause) =
2740 self.context
2741 .0
2742 .command_encoder_clear_texture(self.id, texture.id, subresource_range)
2743 {
2744 self.context.handle_error_nolabel(
2745 &self.error_sink,
2746 cause,
2747 "CommandEncoder::clear_texture",
2748 );
2749 }
2750 }
2751
2752 fn clear_buffer(
2753 &self,
2754 buffer: &dispatch::DispatchBuffer,
2755 offset: crate::BufferAddress,
2756 size: Option<crate::BufferAddress>,
2757 ) {
2758 let buffer = buffer.as_core();
2759
2760 if let Err(cause) = self
2761 .context
2762 .0
2763 .command_encoder_clear_buffer(self.id, buffer.id, offset, size)
2764 {
2765 self.context.handle_error_nolabel(
2766 &self.error_sink,
2767 cause,
2768 "CommandEncoder::fill_buffer",
2769 );
2770 }
2771 }
2772
2773 fn insert_debug_marker(&self, label: &str) {
2774 if let Err(cause) = self
2775 .context
2776 .0
2777 .command_encoder_insert_debug_marker(self.id, label)
2778 {
2779 self.context.handle_error_nolabel(
2780 &self.error_sink,
2781 cause,
2782 "CommandEncoder::insert_debug_marker",
2783 );
2784 }
2785 }
2786
2787 fn push_debug_group(&self, label: &str) {
2788 if let Err(cause) = self
2789 .context
2790 .0
2791 .command_encoder_push_debug_group(self.id, label)
2792 {
2793 self.context.handle_error_nolabel(
2794 &self.error_sink,
2795 cause,
2796 "CommandEncoder::push_debug_group",
2797 );
2798 }
2799 }
2800
2801 fn pop_debug_group(&self) {
2802 if let Err(cause) = self.context.0.command_encoder_pop_debug_group(self.id) {
2803 self.context.handle_error_nolabel(
2804 &self.error_sink,
2805 cause,
2806 "CommandEncoder::pop_debug_group",
2807 );
2808 }
2809 }
2810
2811 fn write_timestamp(&self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
2812 let query_set = query_set.as_core();
2813
2814 if let Err(cause) =
2815 self.context
2816 .0
2817 .command_encoder_write_timestamp(self.id, query_set.id, query_index)
2818 {
2819 self.context.handle_error_nolabel(
2820 &self.error_sink,
2821 cause,
2822 "CommandEncoder::write_timestamp",
2823 );
2824 }
2825 }
2826
2827 fn resolve_query_set(
2828 &self,
2829 query_set: &dispatch::DispatchQuerySet,
2830 first_query: u32,
2831 query_count: u32,
2832 destination: &dispatch::DispatchBuffer,
2833 destination_offset: crate::BufferAddress,
2834 ) {
2835 let query_set = query_set.as_core();
2836 let destination = destination.as_core();
2837
2838 if let Err(cause) = self.context.0.command_encoder_resolve_query_set(
2839 self.id,
2840 query_set.id,
2841 first_query,
2842 query_count,
2843 destination.id,
2844 destination_offset,
2845 ) {
2846 self.context.handle_error_nolabel(
2847 &self.error_sink,
2848 cause,
2849 "CommandEncoder::resolve_query_set",
2850 );
2851 }
2852 }
2853
2854 fn mark_acceleration_structures_built<'a>(
2855 &self,
2856 blas: &mut dyn Iterator<Item = &'a Blas>,
2857 tlas: &mut dyn Iterator<Item = &'a Tlas>,
2858 ) {
2859 let blas = blas
2860 .map(|b| b.inner.as_core().id)
2861 .collect::<SmallVec<[_; 4]>>();
2862 let tlas = tlas
2863 .map(|t| t.inner.as_core().id)
2864 .collect::<SmallVec<[_; 4]>>();
2865 if let Err(cause) = self
2866 .context
2867 .0
2868 .command_encoder_mark_acceleration_structures_built(self.id, &blas, &tlas)
2869 {
2870 self.context.handle_error_nolabel(
2871 &self.error_sink,
2872 cause,
2873 "CommandEncoder::build_acceleration_structures_unsafe_tlas",
2874 );
2875 }
2876 }
2877
2878 fn build_acceleration_structures<'a>(
2879 &self,
2880 blas: &mut dyn Iterator<Item = &'a crate::BlasBuildEntry<'a>>,
2881 tlas: &mut dyn Iterator<Item = &'a crate::Tlas>,
2882 ) {
2883 let blas = blas.map(|e: &crate::BlasBuildEntry<'_>| {
2884 let geometries = match e.geometry {
2885 crate::BlasGeometries::TriangleGeometries(ref triangle_geometries) => {
2886 let iter = triangle_geometries.iter().map(|tg| {
2887 wgc::ray_tracing::BlasTriangleGeometry {
2888 vertex_buffer: tg.vertex_buffer.inner.as_core().id,
2889 index_buffer: tg.index_buffer.map(|buf| buf.inner.as_core().id),
2890 transform_buffer: tg.transform_buffer.map(|buf| buf.inner.as_core().id),
2891 size: tg.size,
2892 transform_buffer_offset: tg.transform_buffer_offset,
2893 first_vertex: tg.first_vertex,
2894 vertex_stride: tg.vertex_stride,
2895 first_index: tg.first_index,
2896 }
2897 });
2898 wgc::ray_tracing::BlasGeometries::TriangleGeometries(Box::new(iter))
2899 }
2900 crate::BlasGeometries::AabbGeometries(ref aabb_geometries) => {
2901 let iter =
2902 aabb_geometries
2903 .iter()
2904 .map(|ag| wgc::ray_tracing::BlasAabbGeometry {
2905 aabb_buffer: ag.aabb_buffer.inner.as_core().id,
2906 stride: ag.stride,
2907 size: ag.size,
2908 primitive_offset: ag.primitive_offset,
2909 });
2910 wgc::ray_tracing::BlasGeometries::AabbGeometries(Box::new(iter))
2911 }
2912 };
2913 wgc::ray_tracing::BlasBuildEntry {
2914 blas_id: e.blas.inner.as_core().id,
2915 geometries,
2916 }
2917 });
2918
2919 let tlas = tlas.into_iter().map(|e| {
2920 let instances = e
2921 .instances
2922 .iter()
2923 .map(|instance: &Option<crate::TlasInstance>| {
2924 instance
2925 .as_ref()
2926 .map(|instance| wgc::ray_tracing::TlasInstance {
2927 blas_id: instance.blas.as_core().id,
2928 transform: &instance.transform,
2929 custom_data: instance.custom_data,
2930 mask: instance.mask,
2931 })
2932 });
2933 wgc::ray_tracing::TlasPackage {
2934 tlas_id: e.inner.as_core().id,
2935 instances: Box::new(instances),
2936 lowest_unmodified: e.lowest_unmodified,
2937 }
2938 });
2939
2940 if let Err(cause) = self
2941 .context
2942 .0
2943 .command_encoder_build_acceleration_structures(self.id, blas, tlas)
2944 {
2945 self.context.handle_error_nolabel(
2946 &self.error_sink,
2947 cause,
2948 "CommandEncoder::build_acceleration_structures_unsafe_tlas",
2949 );
2950 }
2951 }
2952
2953 fn transition_resources<'a>(
2954 &mut self,
2955 buffer_transitions: &mut dyn Iterator<
2956 Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>,
2957 >,
2958 texture_transitions: &mut dyn Iterator<
2959 Item = wgt::TextureTransition<&'a dispatch::DispatchTexture>,
2960 >,
2961 ) {
2962 let result = self.context.0.command_encoder_transition_resources(
2963 self.id,
2964 buffer_transitions.map(|t| wgt::BufferTransition {
2965 buffer: t.buffer.as_core().id,
2966 state: t.state,
2967 }),
2968 texture_transitions.map(|t| wgt::TextureTransition {
2969 texture: t.texture.as_core().id,
2970 selector: t.selector.clone(),
2971 state: t.state,
2972 }),
2973 );
2974
2975 if let Err(cause) = result {
2976 self.context.handle_error_nolabel(
2977 &self.error_sink,
2978 cause,
2979 "CommandEncoder::transition_resources",
2980 );
2981 }
2982 }
2983}
2984
2985impl Drop for CoreCommandEncoder {
2986 fn drop(&mut self) {
2987 self.context.0.command_encoder_drop(self.id)
2988 }
2989}
2990
2991impl dispatch::CommandBufferInterface for CoreCommandBuffer {}
2992
2993impl Drop for CoreCommandBuffer {
2994 fn drop(&mut self) {
2995 self.context.0.command_buffer_drop(self.id)
2996 }
2997}
2998
2999impl dispatch::ComputePassInterface for CoreComputePass {
3000 fn set_pipeline(&mut self, pipeline: &dispatch::DispatchComputePipeline) {
3001 let pipeline = pipeline.as_core();
3002
3003 if let Err(cause) = self
3004 .context
3005 .0
3006 .compute_pass_set_pipeline(&mut self.pass, pipeline.id)
3007 {
3008 self.context.handle_error(
3009 &self.error_sink,
3010 cause,
3011 self.pass.label(),
3012 "ComputePass::set_pipeline",
3013 );
3014 }
3015 }
3016
3017 fn set_bind_group(
3018 &mut self,
3019 index: u32,
3020 bind_group: Option<&dispatch::DispatchBindGroup>,
3021 offsets: &[crate::DynamicOffset],
3022 ) {
3023 let bg = bind_group.map(|bg| bg.as_core().id);
3024
3025 if let Err(cause) =
3026 self.context
3027 .0
3028 .compute_pass_set_bind_group(&mut self.pass, index, bg, offsets)
3029 {
3030 self.context.handle_error(
3031 &self.error_sink,
3032 cause,
3033 self.pass.label(),
3034 "ComputePass::set_bind_group",
3035 );
3036 }
3037 }
3038
3039 fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3040 if let Err(cause) = self
3041 .context
3042 .0
3043 .compute_pass_set_immediates(&mut self.pass, offset, data)
3044 {
3045 self.context.handle_error(
3046 &self.error_sink,
3047 cause,
3048 self.pass.label(),
3049 "ComputePass::set_immediates",
3050 );
3051 }
3052 }
3053
3054 fn insert_debug_marker(&mut self, label: &str) {
3055 if let Err(cause) =
3056 self.context
3057 .0
3058 .compute_pass_insert_debug_marker(&mut self.pass, label, 0)
3059 {
3060 self.context.handle_error(
3061 &self.error_sink,
3062 cause,
3063 self.pass.label(),
3064 "ComputePass::insert_debug_marker",
3065 );
3066 }
3067 }
3068
3069 fn push_debug_group(&mut self, group_label: &str) {
3070 if let Err(cause) =
3071 self.context
3072 .0
3073 .compute_pass_push_debug_group(&mut self.pass, group_label, 0)
3074 {
3075 self.context.handle_error(
3076 &self.error_sink,
3077 cause,
3078 self.pass.label(),
3079 "ComputePass::push_debug_group",
3080 );
3081 }
3082 }
3083
3084 fn pop_debug_group(&mut self) {
3085 if let Err(cause) = self.context.0.compute_pass_pop_debug_group(&mut self.pass) {
3086 self.context.handle_error(
3087 &self.error_sink,
3088 cause,
3089 self.pass.label(),
3090 "ComputePass::pop_debug_group",
3091 );
3092 }
3093 }
3094
3095 fn write_timestamp(&mut self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
3096 let query_set = query_set.as_core();
3097
3098 if let Err(cause) =
3099 self.context
3100 .0
3101 .compute_pass_write_timestamp(&mut self.pass, query_set.id, query_index)
3102 {
3103 self.context.handle_error(
3104 &self.error_sink,
3105 cause,
3106 self.pass.label(),
3107 "ComputePass::write_timestamp",
3108 );
3109 }
3110 }
3111
3112 fn begin_pipeline_statistics_query(
3113 &mut self,
3114 query_set: &dispatch::DispatchQuerySet,
3115 query_index: u32,
3116 ) {
3117 let query_set = query_set.as_core();
3118
3119 if let Err(cause) = self.context.0.compute_pass_begin_pipeline_statistics_query(
3120 &mut self.pass,
3121 query_set.id,
3122 query_index,
3123 ) {
3124 self.context.handle_error(
3125 &self.error_sink,
3126 cause,
3127 self.pass.label(),
3128 "ComputePass::begin_pipeline_statistics_query",
3129 );
3130 }
3131 }
3132
3133 fn end_pipeline_statistics_query(&mut self) {
3134 if let Err(cause) = self
3135 .context
3136 .0
3137 .compute_pass_end_pipeline_statistics_query(&mut self.pass)
3138 {
3139 self.context.handle_error(
3140 &self.error_sink,
3141 cause,
3142 self.pass.label(),
3143 "ComputePass::end_pipeline_statistics_query",
3144 );
3145 }
3146 }
3147
3148 fn dispatch_workgroups(&mut self, x: u32, y: u32, z: u32) {
3149 if let Err(cause) = self
3150 .context
3151 .0
3152 .compute_pass_dispatch_workgroups(&mut self.pass, x, y, z)
3153 {
3154 self.context.handle_error(
3155 &self.error_sink,
3156 cause,
3157 self.pass.label(),
3158 "ComputePass::dispatch_workgroups",
3159 );
3160 }
3161 }
3162
3163 fn dispatch_workgroups_indirect(
3164 &mut self,
3165 indirect_buffer: &dispatch::DispatchBuffer,
3166 indirect_offset: crate::BufferAddress,
3167 ) {
3168 let indirect_buffer = indirect_buffer.as_core();
3169
3170 if let Err(cause) = self.context.0.compute_pass_dispatch_workgroups_indirect(
3171 &mut self.pass,
3172 indirect_buffer.id,
3173 indirect_offset,
3174 ) {
3175 self.context.handle_error(
3176 &self.error_sink,
3177 cause,
3178 self.pass.label(),
3179 "ComputePass::dispatch_workgroups_indirect",
3180 );
3181 }
3182 }
3183
3184 fn transition_resources<'a>(
3185 &mut self,
3186 buffer_transitions: &mut dyn Iterator<
3187 Item = wgt::BufferTransition<&'a dispatch::DispatchBuffer>,
3188 >,
3189 texture_transitions: &mut dyn Iterator<
3190 Item = wgt::TextureTransition<&'a dispatch::DispatchTextureView>,
3191 >,
3192 ) {
3193 let result = self.context.0.compute_pass_transition_resources(
3194 &mut self.pass,
3195 buffer_transitions.map(|t| wgt::BufferTransition {
3196 buffer: t.buffer.as_core().id,
3197 state: t.state,
3198 }),
3199 texture_transitions.map(|t| wgt::TextureTransition {
3200 texture: t.texture.as_core().id,
3201 selector: t.selector.clone(),
3202 state: t.state,
3203 }),
3204 );
3205
3206 if let Err(cause) = result {
3207 self.context.handle_error(
3208 &self.error_sink,
3209 cause,
3210 self.pass.label(),
3211 "ComputePass::transition_resources",
3212 );
3213 }
3214 }
3215}
3216
3217impl Drop for CoreComputePass {
3218 fn drop(&mut self) {
3219 if let Err(cause) = self.context.0.compute_pass_end(&mut self.pass) {
3220 self.context.handle_error(
3221 &self.error_sink,
3222 cause,
3223 self.pass.label(),
3224 "ComputePass::end",
3225 );
3226 }
3227 }
3228}
3229
3230impl dispatch::RenderPassInterface for CoreRenderPass {
3231 fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
3232 let pipeline = pipeline.as_core();
3233
3234 if let Err(cause) = self
3235 .context
3236 .0
3237 .render_pass_set_pipeline(&mut self.pass, pipeline.id)
3238 {
3239 self.context.handle_error(
3240 &self.error_sink,
3241 cause,
3242 self.pass.label(),
3243 "RenderPass::set_pipeline",
3244 );
3245 }
3246 }
3247
3248 fn set_bind_group(
3249 &mut self,
3250 index: u32,
3251 bind_group: Option<&dispatch::DispatchBindGroup>,
3252 offsets: &[crate::DynamicOffset],
3253 ) {
3254 let bg = bind_group.map(|bg| bg.as_core().id);
3255
3256 if let Err(cause) =
3257 self.context
3258 .0
3259 .render_pass_set_bind_group(&mut self.pass, index, bg, offsets)
3260 {
3261 self.context.handle_error(
3262 &self.error_sink,
3263 cause,
3264 self.pass.label(),
3265 "RenderPass::set_bind_group",
3266 );
3267 }
3268 }
3269
3270 fn set_index_buffer(
3271 &mut self,
3272 buffer: &dispatch::DispatchBuffer,
3273 index_format: crate::IndexFormat,
3274 offset: crate::BufferAddress,
3275 size: Option<crate::BufferSize>,
3276 ) {
3277 let buffer = buffer.as_core();
3278
3279 if let Err(cause) = self.context.0.render_pass_set_index_buffer(
3280 &mut self.pass,
3281 buffer.id,
3282 index_format,
3283 offset,
3284 size,
3285 ) {
3286 self.context.handle_error(
3287 &self.error_sink,
3288 cause,
3289 self.pass.label(),
3290 "RenderPass::set_index_buffer",
3291 );
3292 }
3293 }
3294
3295 fn set_vertex_buffer(
3296 &mut self,
3297 slot: u32,
3298 buffer: Option<&dispatch::DispatchBuffer>,
3299 offset: crate::BufferAddress,
3300 size: Option<crate::BufferSize>,
3301 ) {
3302 let buffer = buffer.map(|buffer| buffer.as_core().id);
3303
3304 if let Err(cause) =
3305 self.context
3306 .0
3307 .render_pass_set_vertex_buffer(&mut self.pass, slot, buffer, offset, size)
3308 {
3309 self.context.handle_error(
3310 &self.error_sink,
3311 cause,
3312 self.pass.label(),
3313 "RenderPass::set_vertex_buffer",
3314 );
3315 }
3316 }
3317
3318 fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3319 if let Err(cause) = self
3320 .context
3321 .0
3322 .render_pass_set_immediates(&mut self.pass, offset, data)
3323 {
3324 self.context.handle_error(
3325 &self.error_sink,
3326 cause,
3327 self.pass.label(),
3328 "RenderPass::set_immediates",
3329 );
3330 }
3331 }
3332
3333 fn set_blend_constant(&mut self, color: crate::Color) {
3334 if let Err(cause) = self
3335 .context
3336 .0
3337 .render_pass_set_blend_constant(&mut self.pass, color)
3338 {
3339 self.context.handle_error(
3340 &self.error_sink,
3341 cause,
3342 self.pass.label(),
3343 "RenderPass::set_blend_constant",
3344 );
3345 }
3346 }
3347
3348 fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32) {
3349 if let Err(cause) =
3350 self.context
3351 .0
3352 .render_pass_set_scissor_rect(&mut self.pass, x, y, width, height)
3353 {
3354 self.context.handle_error(
3355 &self.error_sink,
3356 cause,
3357 self.pass.label(),
3358 "RenderPass::set_scissor_rect",
3359 );
3360 }
3361 }
3362
3363 fn set_viewport(
3364 &mut self,
3365 x: f32,
3366 y: f32,
3367 width: f32,
3368 height: f32,
3369 min_depth: f32,
3370 max_depth: f32,
3371 ) {
3372 if let Err(cause) = self.context.0.render_pass_set_viewport(
3373 &mut self.pass,
3374 x,
3375 y,
3376 width,
3377 height,
3378 min_depth,
3379 max_depth,
3380 ) {
3381 self.context.handle_error(
3382 &self.error_sink,
3383 cause,
3384 self.pass.label(),
3385 "RenderPass::set_viewport",
3386 );
3387 }
3388 }
3389
3390 fn set_stencil_reference(&mut self, reference: u32) {
3391 if let Err(cause) = self
3392 .context
3393 .0
3394 .render_pass_set_stencil_reference(&mut self.pass, reference)
3395 {
3396 self.context.handle_error(
3397 &self.error_sink,
3398 cause,
3399 self.pass.label(),
3400 "RenderPass::set_stencil_reference",
3401 );
3402 }
3403 }
3404
3405 fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
3406 if let Err(cause) = self.context.0.render_pass_draw(
3407 &mut self.pass,
3408 vertices.end - vertices.start,
3409 instances.end - instances.start,
3410 vertices.start,
3411 instances.start,
3412 ) {
3413 self.context.handle_error(
3414 &self.error_sink,
3415 cause,
3416 self.pass.label(),
3417 "RenderPass::draw",
3418 );
3419 }
3420 }
3421
3422 fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
3423 if let Err(cause) = self.context.0.render_pass_draw_indexed(
3424 &mut self.pass,
3425 indices.end - indices.start,
3426 instances.end - instances.start,
3427 indices.start,
3428 base_vertex,
3429 instances.start,
3430 ) {
3431 self.context.handle_error(
3432 &self.error_sink,
3433 cause,
3434 self.pass.label(),
3435 "RenderPass::draw_indexed",
3436 );
3437 }
3438 }
3439
3440 fn draw_mesh_tasks(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) {
3441 if let Err(cause) = self.context.0.render_pass_draw_mesh_tasks(
3442 &mut self.pass,
3443 group_count_x,
3444 group_count_y,
3445 group_count_z,
3446 ) {
3447 self.context.handle_error(
3448 &self.error_sink,
3449 cause,
3450 self.pass.label(),
3451 "RenderPass::draw_mesh_tasks",
3452 );
3453 }
3454 }
3455
3456 fn draw_indirect(
3457 &mut self,
3458 indirect_buffer: &dispatch::DispatchBuffer,
3459 indirect_offset: crate::BufferAddress,
3460 ) {
3461 let indirect_buffer = indirect_buffer.as_core();
3462
3463 if let Err(cause) = self.context.0.render_pass_draw_indirect(
3464 &mut self.pass,
3465 indirect_buffer.id,
3466 indirect_offset,
3467 ) {
3468 self.context.handle_error(
3469 &self.error_sink,
3470 cause,
3471 self.pass.label(),
3472 "RenderPass::draw_indirect",
3473 );
3474 }
3475 }
3476
3477 fn draw_indexed_indirect(
3478 &mut self,
3479 indirect_buffer: &dispatch::DispatchBuffer,
3480 indirect_offset: crate::BufferAddress,
3481 ) {
3482 let indirect_buffer = indirect_buffer.as_core();
3483
3484 if let Err(cause) = self.context.0.render_pass_draw_indexed_indirect(
3485 &mut self.pass,
3486 indirect_buffer.id,
3487 indirect_offset,
3488 ) {
3489 self.context.handle_error(
3490 &self.error_sink,
3491 cause,
3492 self.pass.label(),
3493 "RenderPass::draw_indexed_indirect",
3494 );
3495 }
3496 }
3497
3498 fn draw_mesh_tasks_indirect(
3499 &mut self,
3500 indirect_buffer: &dispatch::DispatchBuffer,
3501 indirect_offset: crate::BufferAddress,
3502 ) {
3503 let indirect_buffer = indirect_buffer.as_core();
3504
3505 if let Err(cause) = self.context.0.render_pass_draw_mesh_tasks_indirect(
3506 &mut self.pass,
3507 indirect_buffer.id,
3508 indirect_offset,
3509 ) {
3510 self.context.handle_error(
3511 &self.error_sink,
3512 cause,
3513 self.pass.label(),
3514 "RenderPass::draw_mesh_tasks_indirect",
3515 );
3516 }
3517 }
3518
3519 fn multi_draw_indirect(
3520 &mut self,
3521 indirect_buffer: &dispatch::DispatchBuffer,
3522 indirect_offset: crate::BufferAddress,
3523 count: u32,
3524 ) {
3525 let indirect_buffer = indirect_buffer.as_core();
3526
3527 if let Err(cause) = self.context.0.render_pass_multi_draw_indirect(
3528 &mut self.pass,
3529 indirect_buffer.id,
3530 indirect_offset,
3531 count,
3532 ) {
3533 self.context.handle_error(
3534 &self.error_sink,
3535 cause,
3536 self.pass.label(),
3537 "RenderPass::multi_draw_indirect",
3538 );
3539 }
3540 }
3541
3542 fn multi_draw_indexed_indirect(
3543 &mut self,
3544 indirect_buffer: &dispatch::DispatchBuffer,
3545 indirect_offset: crate::BufferAddress,
3546 count: u32,
3547 ) {
3548 let indirect_buffer = indirect_buffer.as_core();
3549
3550 if let Err(cause) = self.context.0.render_pass_multi_draw_indexed_indirect(
3551 &mut self.pass,
3552 indirect_buffer.id,
3553 indirect_offset,
3554 count,
3555 ) {
3556 self.context.handle_error(
3557 &self.error_sink,
3558 cause,
3559 self.pass.label(),
3560 "RenderPass::multi_draw_indexed_indirect",
3561 );
3562 }
3563 }
3564
3565 fn multi_draw_mesh_tasks_indirect(
3566 &mut self,
3567 indirect_buffer: &dispatch::DispatchBuffer,
3568 indirect_offset: crate::BufferAddress,
3569 count: u32,
3570 ) {
3571 let indirect_buffer = indirect_buffer.as_core();
3572
3573 if let Err(cause) = self.context.0.render_pass_multi_draw_mesh_tasks_indirect(
3574 &mut self.pass,
3575 indirect_buffer.id,
3576 indirect_offset,
3577 count,
3578 ) {
3579 self.context.handle_error(
3580 &self.error_sink,
3581 cause,
3582 self.pass.label(),
3583 "RenderPass::multi_draw_mesh_tasks_indirect",
3584 );
3585 }
3586 }
3587
3588 fn multi_draw_indirect_count(
3589 &mut self,
3590 indirect_buffer: &dispatch::DispatchBuffer,
3591 indirect_offset: crate::BufferAddress,
3592 count_buffer: &dispatch::DispatchBuffer,
3593 count_buffer_offset: crate::BufferAddress,
3594 max_count: u32,
3595 ) {
3596 let indirect_buffer = indirect_buffer.as_core();
3597 let count_buffer = count_buffer.as_core();
3598
3599 if let Err(cause) = self.context.0.render_pass_multi_draw_indirect_count(
3600 &mut self.pass,
3601 indirect_buffer.id,
3602 indirect_offset,
3603 count_buffer.id,
3604 count_buffer_offset,
3605 max_count,
3606 ) {
3607 self.context.handle_error(
3608 &self.error_sink,
3609 cause,
3610 self.pass.label(),
3611 "RenderPass::multi_draw_indirect_count",
3612 );
3613 }
3614 }
3615
3616 fn multi_draw_indexed_indirect_count(
3617 &mut self,
3618 indirect_buffer: &dispatch::DispatchBuffer,
3619 indirect_offset: crate::BufferAddress,
3620 count_buffer: &dispatch::DispatchBuffer,
3621 count_buffer_offset: crate::BufferAddress,
3622 max_count: u32,
3623 ) {
3624 let indirect_buffer = indirect_buffer.as_core();
3625 let count_buffer = count_buffer.as_core();
3626
3627 if let Err(cause) = self
3628 .context
3629 .0
3630 .render_pass_multi_draw_indexed_indirect_count(
3631 &mut self.pass,
3632 indirect_buffer.id,
3633 indirect_offset,
3634 count_buffer.id,
3635 count_buffer_offset,
3636 max_count,
3637 )
3638 {
3639 self.context.handle_error(
3640 &self.error_sink,
3641 cause,
3642 self.pass.label(),
3643 "RenderPass::multi_draw_indexed_indirect_count",
3644 );
3645 }
3646 }
3647
3648 fn multi_draw_mesh_tasks_indirect_count(
3649 &mut self,
3650 indirect_buffer: &dispatch::DispatchBuffer,
3651 indirect_offset: crate::BufferAddress,
3652 count_buffer: &dispatch::DispatchBuffer,
3653 count_buffer_offset: crate::BufferAddress,
3654 max_count: u32,
3655 ) {
3656 let indirect_buffer = indirect_buffer.as_core();
3657 let count_buffer = count_buffer.as_core();
3658
3659 if let Err(cause) = self
3660 .context
3661 .0
3662 .render_pass_multi_draw_mesh_tasks_indirect_count(
3663 &mut self.pass,
3664 indirect_buffer.id,
3665 indirect_offset,
3666 count_buffer.id,
3667 count_buffer_offset,
3668 max_count,
3669 )
3670 {
3671 self.context.handle_error(
3672 &self.error_sink,
3673 cause,
3674 self.pass.label(),
3675 "RenderPass::multi_draw_mesh_tasks_indirect_count",
3676 );
3677 }
3678 }
3679
3680 fn insert_debug_marker(&mut self, label: &str) {
3681 if let Err(cause) = self
3682 .context
3683 .0
3684 .render_pass_insert_debug_marker(&mut self.pass, label, 0)
3685 {
3686 self.context.handle_error(
3687 &self.error_sink,
3688 cause,
3689 self.pass.label(),
3690 "RenderPass::insert_debug_marker",
3691 );
3692 }
3693 }
3694
3695 fn push_debug_group(&mut self, group_label: &str) {
3696 if let Err(cause) =
3697 self.context
3698 .0
3699 .render_pass_push_debug_group(&mut self.pass, group_label, 0)
3700 {
3701 self.context.handle_error(
3702 &self.error_sink,
3703 cause,
3704 self.pass.label(),
3705 "RenderPass::push_debug_group",
3706 );
3707 }
3708 }
3709
3710 fn pop_debug_group(&mut self) {
3711 if let Err(cause) = self.context.0.render_pass_pop_debug_group(&mut self.pass) {
3712 self.context.handle_error(
3713 &self.error_sink,
3714 cause,
3715 self.pass.label(),
3716 "RenderPass::pop_debug_group",
3717 );
3718 }
3719 }
3720
3721 fn write_timestamp(&mut self, query_set: &dispatch::DispatchQuerySet, query_index: u32) {
3722 let query_set = query_set.as_core();
3723
3724 if let Err(cause) =
3725 self.context
3726 .0
3727 .render_pass_write_timestamp(&mut self.pass, query_set.id, query_index)
3728 {
3729 self.context.handle_error(
3730 &self.error_sink,
3731 cause,
3732 self.pass.label(),
3733 "RenderPass::write_timestamp",
3734 );
3735 }
3736 }
3737
3738 fn begin_occlusion_query(&mut self, query_index: u32) {
3739 if let Err(cause) = self
3740 .context
3741 .0
3742 .render_pass_begin_occlusion_query(&mut self.pass, query_index)
3743 {
3744 self.context.handle_error(
3745 &self.error_sink,
3746 cause,
3747 self.pass.label(),
3748 "RenderPass::begin_occlusion_query",
3749 );
3750 }
3751 }
3752
3753 fn end_occlusion_query(&mut self) {
3754 if let Err(cause) = self
3755 .context
3756 .0
3757 .render_pass_end_occlusion_query(&mut self.pass)
3758 {
3759 self.context.handle_error(
3760 &self.error_sink,
3761 cause,
3762 self.pass.label(),
3763 "RenderPass::end_occlusion_query",
3764 );
3765 }
3766 }
3767
3768 fn begin_pipeline_statistics_query(
3769 &mut self,
3770 query_set: &dispatch::DispatchQuerySet,
3771 query_index: u32,
3772 ) {
3773 let query_set = query_set.as_core();
3774
3775 if let Err(cause) = self.context.0.render_pass_begin_pipeline_statistics_query(
3776 &mut self.pass,
3777 query_set.id,
3778 query_index,
3779 ) {
3780 self.context.handle_error(
3781 &self.error_sink,
3782 cause,
3783 self.pass.label(),
3784 "RenderPass::begin_pipeline_statistics_query",
3785 );
3786 }
3787 }
3788
3789 fn end_pipeline_statistics_query(&mut self) {
3790 if let Err(cause) = self
3791 .context
3792 .0
3793 .render_pass_end_pipeline_statistics_query(&mut self.pass)
3794 {
3795 self.context.handle_error(
3796 &self.error_sink,
3797 cause,
3798 self.pass.label(),
3799 "RenderPass::end_pipeline_statistics_query",
3800 );
3801 }
3802 }
3803
3804 fn execute_bundles(
3805 &mut self,
3806 render_bundles: &mut dyn Iterator<Item = &dispatch::DispatchRenderBundle>,
3807 ) {
3808 let temp_render_bundles = render_bundles
3809 .map(|rb| rb.as_core().id)
3810 .collect::<SmallVec<[_; 4]>>();
3811 if let Err(cause) = self
3812 .context
3813 .0
3814 .render_pass_execute_bundles(&mut self.pass, &temp_render_bundles)
3815 {
3816 self.context.handle_error(
3817 &self.error_sink,
3818 cause,
3819 self.pass.label(),
3820 "RenderPass::execute_bundles",
3821 );
3822 }
3823 }
3824}
3825
3826impl Drop for CoreRenderPass {
3827 fn drop(&mut self) {
3828 if let Err(cause) = self.context.0.render_pass_end(&mut self.pass) {
3829 self.context.handle_error(
3830 &self.error_sink,
3831 cause,
3832 self.pass.label(),
3833 "RenderPass::end",
3834 );
3835 }
3836 }
3837}
3838
3839impl dispatch::RenderBundleEncoderInterface for CoreRenderBundleEncoder {
3840 fn set_pipeline(&mut self, pipeline: &dispatch::DispatchRenderPipeline) {
3841 let pipeline = pipeline.as_core();
3842
3843 self.context
3844 .0
3845 .render_bundle_encoder_set_pipeline(&mut self.encoder, pipeline.id)
3846 .expect("RenderBundleEncoder should not have ended")
3847 }
3848
3849 fn set_bind_group(
3850 &mut self,
3851 index: u32,
3852 bind_group: Option<&dispatch::DispatchBindGroup>,
3853 offsets: &[crate::DynamicOffset],
3854 ) {
3855 let bg = bind_group.map(|bg| bg.as_core().id);
3856
3857 self.context
3858 .0
3859 .render_bundle_encoder_set_bind_group(&mut self.encoder, index, bg, offsets)
3860 .expect("RenderBundleEncoder should not have ended");
3861 }
3862
3863 fn set_index_buffer(
3864 &mut self,
3865 buffer: &dispatch::DispatchBuffer,
3866 index_format: crate::IndexFormat,
3867 offset: crate::BufferAddress,
3868 size: Option<crate::BufferSize>,
3869 ) {
3870 let buffer = buffer.as_core();
3871
3872 self.context
3873 .0
3874 .render_bundle_encoder_set_index_buffer(
3875 &mut self.encoder,
3876 buffer.id,
3877 index_format,
3878 offset,
3879 size,
3880 )
3881 .expect("RenderBundleEncoder should not have ended");
3882 }
3883
3884 fn set_vertex_buffer(
3885 &mut self,
3886 slot: u32,
3887 buffer: Option<&dispatch::DispatchBuffer>,
3888 offset: crate::BufferAddress,
3889 size: Option<crate::BufferSize>,
3890 ) {
3891 let buffer = buffer.map(|buffer| buffer.as_core().id);
3892
3893 self.context
3894 .0
3895 .render_bundle_encoder_set_vertex_buffer(&mut self.encoder, slot, buffer, offset, size)
3896 .expect("RenderBundleEncoder should not have ended");
3897 }
3898
3899 fn set_immediates(&mut self, offset: u32, data: &[u8]) {
3900 self.context
3901 .0
3902 .render_bundle_encoder_set_immediates(&mut self.encoder, offset, data)
3903 .expect("RenderBundleEncoder should not have ended");
3904 }
3905
3906 fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
3907 self.context
3908 .0
3909 .render_bundle_encoder_draw(
3910 &mut self.encoder,
3911 vertices.end - vertices.start,
3912 instances.end - instances.start,
3913 vertices.start,
3914 instances.start,
3915 )
3916 .expect("RenderBundleEncoder should not have ended");
3917 }
3918
3919 fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
3920 self.context
3921 .0
3922 .render_bundle_encoder_draw_indexed(
3923 &mut self.encoder,
3924 indices.end - indices.start,
3925 instances.end - instances.start,
3926 indices.start,
3927 base_vertex,
3928 instances.start,
3929 )
3930 .expect("RenderBundleEncoder should not have ended");
3931 }
3932
3933 fn draw_indirect(
3934 &mut self,
3935 indirect_buffer: &dispatch::DispatchBuffer,
3936 indirect_offset: crate::BufferAddress,
3937 ) {
3938 let indirect_buffer = indirect_buffer.as_core();
3939
3940 self.context
3941 .0
3942 .render_bundle_encoder_draw_indirect(
3943 &mut self.encoder,
3944 indirect_buffer.id,
3945 indirect_offset,
3946 )
3947 .expect("RenderBundleEncoder should not have ended");
3948 }
3949
3950 fn draw_indexed_indirect(
3951 &mut self,
3952 indirect_buffer: &dispatch::DispatchBuffer,
3953 indirect_offset: crate::BufferAddress,
3954 ) {
3955 let indirect_buffer = indirect_buffer.as_core();
3956
3957 self.context
3958 .0
3959 .render_bundle_encoder_draw_indexed_indirect(
3960 &mut self.encoder,
3961 indirect_buffer.id,
3962 indirect_offset,
3963 )
3964 .expect("RenderBundleEncoder should not have ended");
3965 }
3966
3967 fn finish(mut self, desc: &crate::RenderBundleDescriptor<'_>) -> dispatch::DispatchRenderBundle
3968 where
3969 Self: Sized,
3970 {
3971 let (id, error) = self.context.0.render_bundle_encoder_finish(
3972 &mut self.encoder,
3973 &desc.map_label(|l| l.map(Borrowed)),
3974 None,
3975 );
3976 if let Some(err) = error {
3977 self.context
3978 .handle_error_fatal(err, "RenderBundleEncoder::finish");
3979 }
3980 CoreRenderBundle {
3981 context: self.context.clone(),
3982 id,
3983 }
3984 .into()
3985 }
3986
3987 #[cfg(custom)]
3988 fn finish_boxed(
3989 self: Box<Self>,
3990 desc: &crate::RenderBundleDescriptor<'_>,
3991 ) -> dispatch::DispatchRenderBundle {
3992 (*self).finish(desc)
3993 }
3994}
3995
3996impl dispatch::RenderBundleInterface for CoreRenderBundle {}
3997
3998impl Drop for CoreRenderBundle {
3999 fn drop(&mut self) {
4000 self.context.0.render_bundle_drop(self.id)
4001 }
4002}
4003
4004impl dispatch::SurfaceInterface for CoreSurface {
4005 fn get_capabilities(&self, adapter: &dispatch::DispatchAdapter) -> wgt::SurfaceCapabilities {
4006 let adapter = adapter.as_core();
4007
4008 self.context
4009 .0
4010 .surface_get_capabilities(self.id, adapter.id)
4011 .unwrap_or_default()
4012 }
4013
4014 fn display_hdr_info(&self, adapter: &dispatch::DispatchAdapter) -> wgt::DisplayHdrInfo {
4015 let adapter = adapter.as_core();
4016
4017 self.context.0.surface_display_hdr_info(self.id, adapter.id)
4018 }
4019
4020 fn keep_presented_images(&self, keep: bool) {
4021 self.context.0.surface_keep_presented_images(self.id, keep);
4022 }
4023
4024 fn configure(&self, device: &dispatch::DispatchDevice, config: &crate::SurfaceConfiguration) {
4025 let device = device.as_core();
4026
4027 let error = self.context.0.surface_configure(self.id, device.id, config);
4028 if let Some(e) = error {
4029 self.context
4030 .handle_error_nolabel(&device.error_sink, e, "Surface::configure");
4031 } else {
4032 *self.configured_device.lock() = Some(device.id);
4033 *self.error_sink.lock() = Some(device.error_sink.clone());
4034 }
4035 }
4036
4037 fn get_current_texture(
4038 &self,
4039 ) -> (
4040 Option<dispatch::DispatchTexture>,
4041 crate::SurfaceStatus,
4042 dispatch::DispatchSurfaceOutputDetail,
4043 ) {
4044 let error_sink = if let Some(error_sink) = self.error_sink.lock().as_ref() {
4045 error_sink.clone()
4046 } else {
4047 Arc::new(Mutex::new(ErrorSinkRaw::new()))
4048 };
4049
4050 let output_detail = |image: Option<wgc::present::SurfaceImage>| {
4051 CoreSurfaceOutputDetail {
4052 context: self.context.clone(),
4053 surface_id: self.id,
4054 error_sink: error_sink.clone(),
4055 image: image.map(|image| crate::SurfaceImage {
4056 index: image.index,
4057 kept: image.kept,
4058 }),
4059 }
4060 .into()
4061 };
4062
4063 match self.context.0.surface_get_current_texture(self.id, None) {
4064 Ok(wgc::present::SurfaceOutput {
4065 status,
4066 texture: texture_id,
4067 image,
4068 }) => {
4069 let output_detail = output_detail(image);
4070 let data = texture_id
4071 .map(|id| CoreTexture {
4072 context: self.context.clone(),
4073 id,
4074 error_sink,
4075 })
4076 .map(Into::into);
4077
4078 (data, status, output_detail)
4079 }
4080 Err(err) => {
4081 let output_detail = output_detail(None);
4082 let error_sink = self.error_sink.lock();
4083 match error_sink.as_ref() {
4084 Some(error_sink) => {
4085 self.context.handle_error_nolabel(
4086 error_sink,
4087 err,
4088 "Surface::get_current_texture_view",
4089 );
4090 (None, crate::SurfaceStatus::Validation, output_detail)
4091 }
4092 None => self
4093 .context
4094 .handle_error_fatal(err, "Surface::get_current_texture_view"),
4095 }
4096 }
4097 }
4098 }
4099}
4100
4101impl Drop for CoreSurface {
4102 fn drop(&mut self) {
4103 self.context.0.surface_drop(self.id)
4104 }
4105}
4106
4107impl dispatch::SurfaceOutputDetailInterface for CoreSurfaceOutputDetail {
4108 fn texture_discard(&self) {
4109 match self.context.0.surface_texture_discard(self.surface_id) {
4110 Ok(_status) => (),
4111 Err(err) => {
4112 self.context
4113 .handle_error_nolabel(&self.error_sink, err, "Surface::discard_texture")
4114 }
4115 }
4116 }
4117
4118 fn texture_release(&self) {
4119 match self.context.0.surface_texture_release(self.surface_id) {
4120 Ok(_status) => (),
4121 Err(err) => {
4122 self.context
4123 .handle_error_nolabel(&self.error_sink, err, "Surface::release_texture")
4124 }
4125 }
4126 }
4127
4128 fn image(&self) -> Option<crate::SurfaceImage> {
4129 self.image
4130 }
4131}
4132impl Drop for CoreSurfaceOutputDetail {
4133 fn drop(&mut self) {
4134 }
4138}
4139
4140impl dispatch::QueueWriteBufferInterface for CoreQueueWriteBuffer {
4141 #[inline]
4142 fn len(&self) -> usize {
4143 self.mapping.len()
4144 }
4145
4146 #[inline]
4147 unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> {
4148 unsafe { self.mapping.write_slice() }
4149 }
4150}
4151impl Drop for CoreQueueWriteBuffer {
4152 fn drop(&mut self) {
4153 }
4157}
4158
4159impl dispatch::BufferMappedRangeInterface for CoreBufferMappedRange {
4160 #[inline]
4161 fn len(&self) -> usize {
4162 self.size
4163 }
4164
4165 #[inline]
4166 unsafe fn read_slice(&self) -> &[u8] {
4167 unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.size) }
4168 }
4169
4170 #[inline]
4171 unsafe fn write_slice(&mut self) -> WriteOnly<'_, [u8]> {
4172 unsafe { WriteOnly::new(NonNull::slice_from_raw_parts(self.ptr, self.size)) }
4173 }
4174
4175 #[cfg(webgpu)]
4176 fn as_uint8array(&self) -> &js_sys::Uint8Array {
4177 panic!("Only available on WebGPU")
4178 }
4179}