// Copyright 2018-2025 the Deno authors. MIT license. #![cfg(not(target_arch = "wasm32"))] #![warn(unsafe_op_in_unsafe_fn)] #![allow(clippy::disallowed_types)] use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; use deno_core::cppgc::SameObject; use deno_core::op2; use deno_core::v8; use deno_core::GarbageCollected; use deno_core::OpState; use deno_error::JsErrorBox; use serde::de::IntoDeserializer; use serde::Deserialize as _; pub use wgpu_core; pub use wgpu_types; use wgpu_types::PowerPreference; use crate::error::GPUGenericError; mod adapter; mod bind_group; mod bind_group_layout; mod buffer; mod byow; mod command_buffer; mod command_encoder; mod compute_pass; mod compute_pipeline; mod device; mod error; mod pipeline_layout; mod query_set; mod queue; mod render_bundle; mod render_pass; mod render_pipeline; mod sampler; mod shader; mod surface; mod texture; mod webidl; pub const UNSTABLE_FEATURE_NAME: &str = "webgpu"; pub const DX12_COMPILER_ENV_VAR: &str = "DENO_WEBGPU_DX12_COMPILER"; pub const STRICT_COMPLIANCE_ENV_VAR: &str = "DENO_WEBGPU_STRICT_COMPLIANCE"; #[allow(clippy::print_stdout)] pub fn print_linker_flags(name: &str) { if cfg!(windows) { // these dls load slowly, so delay loading them let dlls = [ // webgpu "d3dcompiler_47", "OPENGL32", // network related functions "iphlpapi", ]; for dll in dlls { println!("cargo:rustc-link-arg-bin={name}=/delayload:{dll}.dll"); } // enable delay loading println!("cargo:rustc-link-arg-bin={name}=delayimp.lib"); } } pub type Instance = Arc; deno_core::extension!( deno_webgpu, deps = [deno_webidl, deno_web], ops = [ op_create_gpu, device::op_webgpu_device_start_capture, device::op_webgpu_device_stop_capture, ], objects = [ GPU, WGSLLanguageFeatures, adapter::GPUAdapter, adapter::GPUAdapterInfo, bind_group::GPUBindGroup, bind_group_layout::GPUBindGroupLayout, buffer::GPUBuffer, command_buffer::GPUCommandBuffer, command_encoder::GPUCommandEncoder, compute_pass::GPUComputePassEncoder, compute_pipeline::GPUComputePipeline, device::GPUDevice, device::GPUDeviceLostInfo, pipeline_layout::GPUPipelineLayout, query_set::GPUQuerySet, queue::GPUQueue, render_bundle::GPURenderBundle, render_bundle::GPURenderBundleEncoder, render_pass::GPURenderPassEncoder, render_pipeline::GPURenderPipeline, sampler::GPUSampler, shader::GPUCompilationInfo, shader::GPUCompilationMessage, shader::GPUShaderModule, adapter::GPUSupportedFeatures, adapter::GPUSupportedLimits, texture::GPUTexture, texture::GPUTextureView, texture::GPUExternalTexture, byow::UnsafeWindowSurface, surface::GPUCanvasContext, ], esm = ["00_init.js", "02_surface.js"], lazy_loaded_esm = ["01_webgpu.js"], ); pub(crate) type WeakDeviceHM = HashMap>; pub(crate) type LostPromiseResolverHM = HashMap>; #[op2] #[cppgc] pub fn op_create_gpu( state: &mut OpState, scope: &mut v8::HandleScope, webidl_brand: v8::Local, set_event_target_data: v8::Local, uncaptured_error_event_class: v8::Local, pipeline_error_class: v8::Local, ) -> GPU { state.put(WeakDeviceHM::new()); state.put(LostPromiseResolverHM::new()); state.put(EventTargetSetup { brand: v8::Global::new(scope, webidl_brand), set_event_target_data: v8::Global::new(scope, set_event_target_data), }); state.put(ErrorEventClass(v8::Global::new( scope, uncaptured_error_event_class, ))); state.put(PipelineErrorClass(v8::Global::new( scope, pipeline_error_class, ))); GPU { wgsl_language_features: SameObject::new(), } } struct EventTargetSetup { brand: v8::Global, set_event_target_data: v8::Global, } struct ErrorEventClass(v8::Global); struct PipelineErrorClass(v8::Global); pub struct GPU { pub wgsl_language_features: SameObject, } impl GarbageCollected for GPU { fn get_name(&self) -> &'static std::ffi::CStr { c"GPU" } } #[op2] impl GPU { #[constructor] #[cppgc] fn constructor(_: bool) -> Result { Err(GPUGenericError::InvalidConstructor) } #[async_method] #[reentrant] #[cppgc] async fn request_adapter( &self, state: Rc>, #[webidl] options: adapter::GPURequestAdapterOptions, ) -> Option { let dx12_compiler = std::env::var(DX12_COMPILER_ENV_VAR) .ok() .and_then(|s| s.parse().ok()); let backends = std::env::var("DENO_WEBGPU_BACKEND").map_or_else( |_| wgpu_types::Backends::all(), |s| wgpu_types::Backends::from_comma_list(&s), ); let instance = { let mut state = state.borrow_mut(); if let Some(instance) = state.try_borrow::() { instance.clone() } else { let mut flags = wgpu_types::InstanceFlags::from_build_config(); let strict_compliance = std::env::var(STRICT_COMPLIANCE_ENV_VAR) .is_ok_and(|value| { !matches!(value.to_ascii_lowercase().as_str(), "false" | "no" | "0") }); if strict_compliance { flags |= wgpu_types::InstanceFlags::STRICT_WEBGPU_COMPLIANCE; } state.put(wgpu_core::instance::Instance::new( "webgpu", wgpu_types::InstanceDescriptor { backends, flags, memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds { for_resource_creation: Some(97), for_device_loss: Some(99), }, backend_options: wgpu_types::BackendOptions { dx12: wgpu_types::Dx12BackendOptions { shader_compiler: dx12_compiler .unwrap_or(wgpu_types::Dx12Compiler::Fxc), ..Default::default() }, gl: wgpu_types::GlBackendOptions::default(), noop: wgpu_types::NoopBackendOptions::default(), }, display: None, }, None, )); state.borrow::().clone() } }; // Check that the feature level string is valid. // `wgpu` does not support compatibility-level adapters. As permitted // by the spec, we always return a core-level adapter. wgpu_types::FeatureLevel::deserialize(IntoDeserializer::< serde::de::value::Error, >::into_deserializer( options.feature_level.as_str() )) .ok()?; let descriptor = wgpu_types::RequestAdapterOptions { power_preference: options .power_preference .map(|pp| match pp { adapter::GPUPowerPreference::LowPower => PowerPreference::LowPower, adapter::GPUPowerPreference::HighPerformance => { PowerPreference::HighPerformance } }) .unwrap_or_default(), force_fallback_adapter: options.force_fallback_adapter, compatible_surface: None, // windowless apply_limit_buckets: false, }; let wgpu_adapter = instance.request_adapter(&descriptor, backends).ok()?; Some(adapter::GPUAdapter { features: SameObject::new(), limits: SameObject::new(), info: Rc::new(SameObject::new()), wgpu_adapter, }) } #[string] fn getPreferredCanvasFormat(&self) -> &'static str { // https://github.com/mozilla/gecko-dev/blob/b75080bb8b11844d18cb5f9ac6e68a866ef8e243/dom/webgpu/Instance.h#L42-L47 if cfg!(target_os = "android") { texture::GPUTextureFormat::Rgba8unorm.as_str() } else { texture::GPUTextureFormat::Bgra8unorm.as_str() } } #[getter] #[global] fn wgslLanguageFeatures( &self, scope: &mut v8::HandleScope, ) -> v8::Global { self .wgsl_language_features .get(scope, WGSLLanguageFeatures::new) } } pub struct WGSLLanguageFeatures(v8::Global); impl GarbageCollected for WGSLLanguageFeatures { fn get_name(&self) -> &'static std::ffi::CStr { c"WGSLLanguageFeatures" } } impl WGSLLanguageFeatures { pub fn new(scope: &mut v8::HandleScope) -> Self { use wgpu_core::naga::front::wgsl::ImplementedLanguageExtension; let set = v8::Set::new(scope); for ext in ImplementedLanguageExtension::all() { let key = v8::String::new(scope, ext.to_ident()).unwrap(); set.add(scope, key.into()); } Self(v8::Global::new(scope, >::from(set))) } } #[op2] impl WGSLLanguageFeatures { #[constructor] #[cppgc] fn constructor(_: bool) -> Result { Err(GPUGenericError::InvalidConstructor) } #[global] #[symbol("setlike_set")] fn set(&self) -> v8::Global { self.0.clone() } } fn transform_label<'a>(label: String) -> Option> { if label.is_empty() { None } else { Some(std::borrow::Cow::Owned(label)) } } fn map_texture_component_swizzle( swizzle: &str, ) -> Result { if swizzle.len() != 4 { return Err(deno_error::JsErrorBox::type_error( "`TextureViewDescriptor::swizzle` must be exactly a four-character string", )); } let mut c = swizzle.chars(); let r = map_component_swizzle(c.next())?; let g = map_component_swizzle(c.next())?; let b = map_component_swizzle(c.next())?; let a = map_component_swizzle(c.next())?; Ok(wgpu_types::TextureComponentSwizzle { r, g, b, a }) } fn map_component_swizzle( swizzle: Option, ) -> Result { match swizzle { Some('0') => Ok(wgpu_types::ComponentSwizzle::Zero), Some('1') => Ok(wgpu_types::ComponentSwizzle::One), Some('r') => Ok(wgpu_types::ComponentSwizzle::R), Some('g') => Ok(wgpu_types::ComponentSwizzle::G), Some('b') => Ok(wgpu_types::ComponentSwizzle::B), Some('a') => Ok(wgpu_types::ComponentSwizzle::A), None => Err(deno_error::JsErrorBox::type_error( "`TextureViewDescriptor::swizzle` \ must be exactly a four-character string", )), Some(_) => Err(deno_error::JsErrorBox::type_error( "Invalid character for texture component swizzle", )), } } fn operation_error( message: impl Into>, ) -> JsErrorBox { JsErrorBox::new("DOMExceptionOperationError", message) } /// Validate the input data (AllowSharedBufferSource) and return the slice that applied the offset and size, /// or return `Err` if validation fails. /// /// See also the content timeline requirements of /// and fn get_data_slice<'a>( scope: &mut v8::HandleScope, data_arg: v8::Local<'a, v8::Value>, data_offset: u64, data_size: Option, ) -> Result<&'a [u8], JsErrorBox> { const EMPTY: &[u8] = &[]; // Per the WebGPU spec, dataOffset and size are in elements (not bytes) // when data is a TypedArray, and in bytes otherwise. let (buf, bytes_per_element) = if let Ok(typed_array) = v8::Local::::try_from(data_arg) { let len = typed_array.length(); // Avoid panicking as data of zero length array is `None`. if let Some(bpe) = typed_array.byte_length().checked_div(len) { let byte_offset = typed_array.byte_offset(); let byte_len = typed_array.byte_length(); let ab = typed_array.buffer(scope).unwrap(); // SAFETY: Pointer is non-null, and V8 guarantees that the // byte_offset is within the buffer backing store. let ptr = unsafe { ab.data().unwrap().as_ptr().add(byte_offset) }; let buf = // SAFETY: the slice is within the bounds of the backing store unsafe { std::slice::from_raw_parts(ptr as *const u8, byte_len) }; (buf, bpe) } else { (EMPTY, 1) } } else if let Ok(ab) = v8::Local::::try_from(data_arg) { let byte_len = ab.byte_length(); // Avoid panicking as data of zero length array is `None`. if byte_len == 0 { (EMPTY, 1) } else { let ptr = ab.data().unwrap().as_ptr(); let buf = // SAFETY: Pointer is non-null and byte_len is within the backing store. unsafe { std::slice::from_raw_parts(ptr as *const u8, byte_len) }; (buf, 1) } } else if let Ok(ab) = v8::Local::::try_from(data_arg) { let byte_len = ab.byte_length(); // Avoid panicking as data of zero length array is `None`. if byte_len == 0 { (EMPTY, 1) } else { let ptr = ab.get_backing_store().data().unwrap().as_ptr(); let buf = // SAFETY: Pointer is non-null and byte_len is within the backing store. unsafe { std::slice::from_raw_parts(ptr as *const u8, byte_len) }; (buf, 1) } } else if let Ok(view) = v8::Local::::try_from(data_arg) { let byte_offset = view.byte_offset(); let byte_len = view.byte_length(); if byte_len == 0 { (EMPTY, 1) } else { let ab = view.buffer(scope).unwrap(); // SAFETY: Pointer is non-null, and V8 guarantees that the // byte_offset is within the buffer backing store. let ptr = unsafe { ab.data().unwrap().as_ptr().add(byte_offset) }; // SAFETY: the slice is within the bounds of the backing store let buf = unsafe { std::slice::from_raw_parts(ptr as *const u8, byte_len) }; (buf, 1) } } else { return Err(JsErrorBox::type_error( "data must be an ArrayBuffer, SharedArrayBuffer or ArrayBufferView", )); }; let data_offset_bytes = data_offset .checked_mul(bytes_per_element as u64) .ok_or(operation_error("data offset in bytes overflows a `u64`"))?; let content_size_bytes = if let Some(data_size) = data_size { let data_size_bytes = data_size .checked_mul(bytes_per_element as u64) .ok_or(operation_error("data size in bytes overflows a `u64`"))?; if data_offset_bytes .checked_add(data_size_bytes) .ok_or(operation_error("data size + offset overflows a `u64`"))? > buf.len() as u64 { return Err(operation_error("data size + offset is out of bounds")); } data_size_bytes } else { (buf.len() as u64) .checked_sub(data_offset_bytes) .ok_or(operation_error("data offset is out of bounds"))? }; // Both `Queue::write_buffer` and `set_immediates` require content size to be a multiple of 4 const { assert!(wgpu_types::COPY_BUFFER_ALIGNMENT == 4); assert!(wgpu_types::IMMEDIATE_DATA_ALIGNMENT == 4); } if !content_size_bytes.is_multiple_of(4) { return Err(operation_error( "content size in bytes is not a multiple of 4", )); } // We have validated data offset and content size are within the bounds. let data = &buf[(data_offset_bytes as usize) ..((data_offset_bytes + content_size_bytes) as usize)]; Ok(data) }