Skip to main content

script_webgpu/
gputexture.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use dom_struct::dom_struct;
6use js::context::{JSContext, NoGC};
7use log::warn;
8use malloc_size_of_derive::MallocSizeOf;
9use script_bindings::DomTypes;
10use script_bindings::cell::DomRefCell;
11use script_bindings::codegen::GenericBindings::WebGPUBinding::{
12    GPUTextureAspect, GPUTextureDescriptor, GPUTextureDimension, GPUTextureFormat,
13    GPUTextureMethods, GPUTextureViewDescriptor, GPUTextureWrap,
14};
15use script_bindings::dom::MutNullableDom;
16use script_bindings::interfaces::PromiseHelpers;
17use script_bindings::reflector::{DomGlobalGeneric, Reflector, reflect_dom_object_with_wrap};
18use webgpu_traits::{
19    Extent3d, ImageSubresourceRange, TextureAspect, TextureDescriptor, TextureUsages,
20    TextureViewDescriptor, WebGPU, WebGPURequest, WebGPUTexture, WebGPUTextureView,
21};
22
23use crate::JSTraceable;
24use crate::dom::bindings::error::Fallible;
25use crate::dom::bindings::root::{Dom, DomRoot};
26use crate::dom::bindings::str::USVString;
27use crate::gpuconvert::{WebGPUConvert, convert_texture_descriptor};
28use crate::gputextureview::GPUTextureView;
29use crate::traits::{Equivalence, WebGPUGlobalTrait, WebGPUPromise};
30
31#[derive(JSTraceable, MallocSizeOf)]
32struct DroppableGPUTexture {
33    #[no_trace]
34    channel: WebGPU,
35    #[no_trace]
36    texture: WebGPUTexture,
37}
38
39impl Drop for DroppableGPUTexture {
40    fn drop(&mut self) {
41        if let Err(e) = self
42            .channel
43            .0
44            .send(WebGPURequest::DropTexture(self.texture.0))
45        {
46            warn!(
47                "Failed to send WebGPURequest::DropTexture({:?}) ({})",
48                self.texture.0, e
49            );
50        };
51    }
52}
53
54#[dom_struct]
55pub struct GPUTexture<D: DomTypes> {
56    reflector_: Reflector,
57    label: DomRefCell<USVString>,
58    device: Dom<D::GPUDevice>,
59    #[no_trace]
60    #[ignore_malloc_size_of = "External type"]
61    texture_size: Extent3d,
62    mip_level_count: u32,
63    sample_count: u32,
64    dimension: GPUTextureDimension,
65    format: GPUTextureFormat,
66    texture_usage: u32,
67    droppable: DroppableGPUTexture,
68    default_view: MutNullableDom<GPUTextureView<D>>,
69}
70
71impl<D: Equivalence> GPUTexture<D> {
72    #[expect(clippy::too_many_arguments)]
73    fn new_inherited(
74        texture: WebGPUTexture,
75        device: &D::GPUDevice,
76        channel: WebGPU,
77        texture_size: Extent3d,
78        mip_level_count: u32,
79        sample_count: u32,
80        dimension: GPUTextureDimension,
81        format: GPUTextureFormat,
82        texture_usage: u32,
83        label: USVString,
84    ) -> Self {
85        Self {
86            reflector_: Reflector::new(),
87            label: DomRefCell::new(label),
88            device: Dom::from_ref(device),
89            texture_size,
90            mip_level_count,
91            sample_count,
92            dimension,
93            format,
94            texture_usage,
95            droppable: DroppableGPUTexture { channel, texture },
96            default_view: MutNullableDom::new(None),
97        }
98    }
99
100    #[expect(clippy::too_many_arguments)]
101    pub(crate) fn new(
102        cx: &mut JSContext,
103        global: &D::GlobalScope,
104        texture: WebGPUTexture,
105        device: &D::GPUDevice,
106        channel: WebGPU,
107        texture_size: Extent3d,
108        mip_level_count: u32,
109        sample_count: u32,
110        dimension: GPUTextureDimension,
111        format: GPUTextureFormat,
112        texture_usage: u32,
113        label: USVString,
114    ) -> DomRoot<Self> {
115        reflect_dom_object_with_wrap::<D, _, _>(
116            cx,
117            Box::new(GPUTexture::new_inherited(
118                texture,
119                device,
120                channel,
121                texture_size,
122                mip_level_count,
123                sample_count,
124                dimension,
125                format,
126                texture_usage,
127                label,
128            )),
129            global,
130            GPUTextureWrap::<D>,
131        )
132    }
133}
134
135impl<D> GPUTexture<D>
136where
137    D: Equivalence,
138    <D::Promise as PromiseHelpers<D>>::StackRoot: WebGPUPromise<D>,
139{
140    pub fn id(&self) -> WebGPUTexture {
141        self.droppable.texture
142    }
143
144    pub fn wgpu_texture_descriptor(&self) -> TextureDescriptor<'static> {
145        TextureDescriptor {
146            label: Some(self.label.borrow().to_string().into()),
147            size: self.texture_size,
148            mip_level_count: self.mip_level_count,
149            sample_count: self.sample_count,
150            dimension: self.dimension.convert(),
151            format: self.format.convert(),
152            usage: TextureUsages::from_bits_retain(self.texture_usage),
153            view_formats: vec![],
154        }
155    }
156
157    /// <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createtexture>
158    pub(crate) fn create(
159        cx: &mut JSContext,
160        device: &D::GPUDevice,
161        descriptor: &GPUTextureDescriptor,
162    ) -> Fallible<DomRoot<GPUTexture<D>>> {
163        let (desc, size) = convert_texture_descriptor::<D>(descriptor, device)?;
164
165        let global: DomRoot<D::GlobalScope> = device.global_from_reflector();
166        let texture_id = global.global_wgpu_id_hub().create_texture_id();
167
168        device
169            .channel()
170            .0
171            .send(WebGPURequest::CreateTexture {
172                device_id: device.id().0,
173                texture_id,
174                descriptor: desc,
175            })
176            .expect("Failed to create WebGPU Texture");
177
178        let texture = WebGPUTexture(texture_id);
179
180        Ok(GPUTexture::new(
181            cx,
182            &*device.global_from_reflector(),
183            texture,
184            device,
185            device.channel(),
186            size,
187            descriptor.mipLevelCount,
188            descriptor.sampleCount,
189            descriptor.dimension,
190            descriptor.format,
191            descriptor.usage,
192            descriptor.parent.label.clone(),
193        ))
194    }
195
196    pub(crate) fn get_default_view(&self, cx: &mut JSContext) -> WebGPUTextureView {
197        self.default_view
198            .or_init(|| {
199                self.CreateView(cx, &GPUTextureViewDescriptor::default())
200                    .expect("Default descriptor should always be valid.")
201            })
202            .id()
203    }
204}
205
206impl<D> GPUTextureMethods<D> for GPUTexture<D>
207where
208    D: Equivalence,
209    <D::Promise as PromiseHelpers<D>>::StackRoot: WebGPUPromise<D>,
210{
211    /// <https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label>
212    fn Label(&self) -> USVString {
213        self.label.borrow().clone()
214    }
215
216    /// <https://gpuweb.github.io/gpuweb/#dom-gpuobjectbase-label>
217    fn SetLabel(&self, no_gc: &NoGC, value: USVString) {
218        *self.label.safe_borrow_mut(no_gc) = value;
219    }
220
221    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-createview>
222    fn CreateView(
223        &self,
224        cx: &mut JSContext,
225        descriptor: &GPUTextureViewDescriptor,
226    ) -> Fallible<DomRoot<GPUTextureView<D>>> {
227        // Invalid descriptors (e.g. a zero mip level or array layer count) are validated by wgpu,
228        // which then still registers the view id as invalid so that later uses don't panic.
229        let desc = TextureViewDescriptor {
230            label: (&descriptor.parent).convert(),
231            format: descriptor
232                .format
233                .map(|f| self.device.validate_texture_format_required_features(&f))
234                .transpose()?,
235            dimension: descriptor.dimension.map(|dimension| dimension.convert()),
236            usage: Some(TextureUsages::from_bits_retain(descriptor.usage)),
237            range: ImageSubresourceRange {
238                aspect: match descriptor.aspect {
239                    GPUTextureAspect::All => TextureAspect::All,
240                    GPUTextureAspect::Stencil_only => TextureAspect::StencilOnly,
241                    GPUTextureAspect::Depth_only => TextureAspect::DepthOnly,
242                },
243                base_mip_level: descriptor.baseMipLevel,
244                mip_level_count: descriptor.mipLevelCount,
245                base_array_layer: descriptor.baseArrayLayer,
246                array_layer_count: descriptor.arrayLayerCount,
247            },
248        };
249
250        let texture_view_id = self
251            .global_from_reflector()
252            .global_wgpu_id_hub()
253            .create_texture_view_id();
254
255        self.droppable
256            .channel
257            .0
258            .send(WebGPURequest::CreateTextureView {
259                texture_id: self.id().0,
260                texture_view_id,
261                device_id: self.device.id().0,
262                descriptor: desc,
263            })
264            .expect("Failed to create WebGPU texture view");
265
266        let texture_view = WebGPUTextureView(texture_view_id);
267
268        Ok(GPUTextureView::new(
269            cx,
270            &*self.global_from_reflector(),
271            self.droppable.channel.clone(),
272            texture_view,
273            self,
274            descriptor.parent.label.clone(),
275        ))
276    }
277
278    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-destroy>
279    fn Destroy(&self) {
280        if let Err(e) = self
281            .droppable
282            .channel
283            .0
284            .send(WebGPURequest::DestroyTexture(self.id().0))
285        {
286            warn!(
287                "Failed to send WebGPURequest::DestroyTexture({:?}) ({})",
288                self.id().0,
289                e
290            );
291        };
292    }
293
294    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-width>
295    fn Width(&self) -> u32 {
296        self.texture_size.width
297    }
298
299    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-height>
300    fn Height(&self) -> u32 {
301        self.texture_size.height
302    }
303
304    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-depthorarraylayers>
305    fn DepthOrArrayLayers(&self) -> u32 {
306        self.texture_size.depth_or_array_layers
307    }
308
309    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-miplevelcount>
310    fn MipLevelCount(&self) -> u32 {
311        self.mip_level_count
312    }
313
314    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-samplecount>
315    fn SampleCount(&self) -> u32 {
316        self.sample_count
317    }
318
319    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-dimension>
320    fn Dimension(&self) -> GPUTextureDimension {
321        self.dimension
322    }
323
324    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-format>
325    fn Format(&self) -> GPUTextureFormat {
326        self.format
327    }
328
329    /// <https://gpuweb.github.io/gpuweb/#dom-gputexture-usage>
330    fn Usage(&self) -> u32 {
331        self.texture_usage
332    }
333}