Skip to main content

script/dom/webgpu/
gpucanvascontext.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 std::borrow::Cow;
6use std::cell::{Cell, RefCell};
7use std::rc::Rc;
8
9use arrayvec::ArrayVec;
10use dom_struct::dom_struct;
11use js::context::JSContext;
12use pixels::Snapshot;
13use script_bindings::cformat;
14use script_bindings::codegen::GenericBindings::WebGPUBinding::{
15    GPUDeviceMethods, GPUTextureFormat, GPUTextureUsageConstants,
16};
17use script_bindings::reflector::{Reflector, reflect_weak_referenceable_dom_object};
18use script_bindings::trace::RootedTraceableBox;
19use script_webgpu::gpuconvert::convert_texture_descriptor;
20use servo_base::{Epoch, generic_channel};
21use webgpu_traits::{
22    ContextConfiguration, PRESENTATION_BUFFER_COUNT, PendingTexture, WebGPU, WebGPUContextId,
23    WebGPURequest, id,
24};
25use webrender_api::{ImageFormat, ImageKey};
26
27use super::gputexture::GPUTexture;
28use crate::canvas_context::{CanvasContext, CanvasHelpers, HTMLCanvasElementOrOffscreenCanvas};
29use crate::dom::bindings::codegen::Bindings::WebGPUBinding::GPUTexture_Binding::GPUTextureMethods;
30use crate::dom::bindings::codegen::Bindings::WebGPUBinding::{
31    GPUCanvasAlphaMode, GPUCanvasConfiguration, GPUCanvasContextMethods, GPUExtent3D,
32    GPUExtent3DDict, GPUObjectDescriptorBase, GPUTextureDescriptor, GPUTextureDimension,
33};
34use crate::dom::bindings::codegen::UnionTypes::HTMLCanvasElementOrOffscreenCanvas as RootedHTMLCanvasElementOrOffscreenCanvas;
35use crate::dom::bindings::error::{Error, Fallible};
36use crate::dom::bindings::reflector::DomGlobal;
37use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
38use crate::dom::bindings::str::USVString;
39use crate::dom::globalscope::GlobalScope;
40use crate::dom::htmlcanvaselement::HTMLCanvasElement;
41
42/// <https://gpuweb.github.io/gpuweb/#supported-context-formats>
43fn supported_context_format(format: GPUTextureFormat) -> bool {
44    // TODO: GPUTextureFormat::Rgba16float
45    matches!(
46        format,
47        GPUTextureFormat::Bgra8unorm | GPUTextureFormat::Rgba8unorm
48    )
49}
50
51#[derive(JSTraceable, MallocSizeOf)]
52struct DroppableGPUCanvasContext {
53    #[no_trace]
54    context_id: WebGPUContextId,
55    #[no_trace]
56    channel: WebGPU,
57}
58
59impl Drop for DroppableGPUCanvasContext {
60    fn drop(&mut self) {
61        if let Err(error) = self.channel.0.send(WebGPURequest::DestroyContext {
62            context_id: self.context_id,
63        }) {
64            warn!(
65                "Failed to send DestroyContext({:?}): {error}",
66                self.context_id,
67            );
68        }
69    }
70}
71
72#[dom_struct]
73pub(crate) struct GPUCanvasContext {
74    reflector_: Reflector,
75    /// <https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-canvas>
76    canvas: HTMLCanvasElementOrOffscreenCanvas,
77    /// <https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-configuration-slot>
78    configuration: RefCell<Option<GPUCanvasConfiguration>>,
79    /// <https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-texturedescriptor-slot>
80    texture_descriptor: RefCell<Option<GPUTextureDescriptor>>,
81    /// <https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-currenttexture-slot>
82    current_texture: MutNullableDom<GPUTexture>,
83    /// Set if image is cleared
84    /// (usually done by [`GPUCanvasContext::replace_drawing_buffer`])
85    cleared: Cell<bool>,
86    droppable: DroppableGPUCanvasContext,
87}
88
89impl GPUCanvasContext {
90    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
91    fn new_inherited(
92        global: &GlobalScope,
93        canvas: HTMLCanvasElementOrOffscreenCanvas,
94        channel: WebGPU,
95    ) -> Self {
96        let (sender, receiver) = generic_channel::channel().unwrap();
97        let size = canvas.size().cast().cast_unit();
98        let mut buffer_ids = ArrayVec::<id::BufferId, PRESENTATION_BUFFER_COUNT>::new();
99        for _ in 0..PRESENTATION_BUFFER_COUNT {
100            buffer_ids.push(global.wgpu_id_hub().create_buffer_id());
101        }
102        if let Err(error) = channel.0.send(WebGPURequest::CreateContext {
103            buffer_ids,
104            size,
105            sender,
106        }) {
107            warn!("Failed to send CreateContext ({error:?})");
108        }
109        let context_id = receiver.recv().unwrap();
110
111        Self {
112            reflector_: Reflector::new(),
113            canvas,
114            configuration: RefCell::new(None),
115            texture_descriptor: RefCell::new(None),
116            current_texture: MutNullableDom::default(),
117            cleared: Cell::new(true),
118            droppable: DroppableGPUCanvasContext {
119                context_id,
120                channel,
121            },
122        }
123    }
124
125    pub(crate) fn new(
126        cx: &mut JSContext,
127        global: &GlobalScope,
128        canvas: &HTMLCanvasElement,
129        channel: WebGPU,
130    ) -> DomRoot<Self> {
131        reflect_weak_referenceable_dom_object(
132            cx,
133            Rc::new(GPUCanvasContext::new_inherited(
134                global,
135                HTMLCanvasElementOrOffscreenCanvas::HTMLCanvasElement(Dom::from_ref(canvas)),
136                channel,
137            )),
138            global,
139        )
140    }
141}
142
143// Abstract ops from spec
144impl GPUCanvasContext {
145    pub(crate) fn set_image_key(&self, image_key: ImageKey) {
146        if let Err(error) = self.droppable.channel.0.send(WebGPURequest::SetImageKey {
147            context_id: self.context_id(),
148            image_key,
149        }) {
150            warn!(
151                "Failed to send WebGPURequest::Present({:?}) ({error})",
152                self.context_id()
153            );
154        }
155    }
156
157    /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-updating-the-rendering-of-a-webgpu-canvas>
158    pub(crate) fn update_rendering(&self, canvas_epoch: Epoch) -> bool {
159        // Present by updating the image in WebRender. This will copy the texture into
160        // the presentation buffer and use it for presenting or send a cleared image to WebRender.
161        if let Err(error) = self.droppable.channel.0.send(WebGPURequest::Present {
162            context_id: self.context_id(),
163            pending_texture: self.pending_texture(),
164            size: self.size(),
165            canvas_epoch,
166        }) {
167            warn!(
168                "Failed to send WebGPURequest::Present({:?}) ({error})",
169                self.context_id()
170            );
171        }
172
173        // 1. Expire the current texture of context.
174        self.expire_current_texture(true);
175
176        true
177    }
178
179    /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-gputexturedescriptor-for-the-canvas-and-configuration>
180    fn texture_descriptor_for_canvas_and_configuration(
181        &self,
182        configuration: &GPUCanvasConfiguration,
183    ) -> GPUTextureDescriptor {
184        let size = self.size();
185        GPUTextureDescriptor {
186            size: GPUExtent3D::GPUExtent3DDict(GPUExtent3DDict {
187                width: size.width,
188                height: size.height,
189                depthOrArrayLayers: 1,
190            }),
191            format: configuration.format,
192            // We need to add `COPY_SRC` so we can copy texture to presentation buffer
193            // causes FAIL on webgpu:web_platform,canvas,configure:usage:*
194            usage: configuration.usage | GPUTextureUsageConstants::COPY_SRC,
195            viewFormats: configuration.viewFormats.clone(),
196            // All other members set to their defaults.
197            mipLevelCount: 1,
198            sampleCount: 1,
199            parent: GPUObjectDescriptorBase {
200                label: USVString::default(),
201            },
202            dimension: GPUTextureDimension::_2d,
203        }
204    }
205
206    /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-expire-the-current-texture>
207    fn expire_current_texture(&self, skip_dirty: bool) {
208        // 1. If context.[[currentTexture]] is not null:
209
210        if let Some(current_texture) = self.current_texture.take() {
211            // 1.2 Set context.[[currentTexture]] to null.
212
213            // 1.1 Call context.[[currentTexture]].destroy()
214            // (without destroying context.[[drawingBuffer]])
215            // to terminate write access to the image.
216            current_texture.Destroy()
217            // we can safely destroy content here,
218            // because we already copied content when doing present
219            // or current texture is getting cleared
220        }
221        // We skip marking the canvas as dirty again if we are already
222        // in the process of updating the rendering.
223        if !skip_dirty {
224            // texture is either cleared or applied to canvas
225            self.mark_as_dirty();
226        }
227    }
228
229    /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-replace-the-drawing-buffer>
230    fn replace_drawing_buffer(&self) {
231        // 1. Expire the current texture of context.
232        self.expire_current_texture(false);
233        // 2. Let configuration be context.[[configuration]].
234        // 3. Set context.[[drawingBuffer]] to
235        // a transparent black image of the same size as context.canvas
236        self.cleared.set(true);
237    }
238}
239
240// Internal helper methods
241impl GPUCanvasContext {
242    fn context_configuration(&self) -> Option<ContextConfiguration> {
243        let configuration = self.configuration.borrow();
244        let configuration = configuration.as_ref()?;
245        Some(ContextConfiguration {
246            device_id: configuration.device.id().0,
247            queue_id: configuration.device.queue_id().0,
248            format: match configuration.format {
249                GPUTextureFormat::Bgra8unorm => ImageFormat::BGRA8,
250                GPUTextureFormat::Rgba8unorm => ImageFormat::RGBA8,
251                _ => unreachable!("Configure method should set valid texture format"),
252            },
253            is_opaque: matches!(configuration.alphaMode, GPUCanvasAlphaMode::Opaque),
254            size: self.size(),
255        })
256    }
257
258    fn pending_texture(&self) -> Option<PendingTexture> {
259        self.current_texture.get().map(|texture| PendingTexture {
260            texture_id: texture.id().0,
261            encoder_id: self.global().wgpu_id_hub().create_command_encoder_id(),
262            command_buffer_id: self.global().wgpu_id_hub().create_command_buffer_id(),
263            configuration: self
264                .context_configuration()
265                .expect("Context should be configured if there is a texture."),
266        })
267    }
268}
269
270impl CanvasContext for GPUCanvasContext {
271    type ID = WebGPUContextId;
272
273    fn context_id(&self) -> WebGPUContextId {
274        self.droppable.context_id
275    }
276
277    /// <https://gpuweb.github.io/gpuweb/#abstract-opdef-update-the-canvas-size>
278    fn resize(&self) {
279        // 1. Replace the drawing buffer of context.
280        self.replace_drawing_buffer();
281        // 2. Let configuration be context.[[configuration]]
282        let configuration = self.configuration.borrow();
283        // 3. If configuration is not null:
284        if let Some(configuration) = configuration.as_ref() {
285            // 3.1. Set context.[[textureDescriptor]] to the
286            // GPUTextureDescriptor for the canvas and configuration(canvas, configuration).
287            self.texture_descriptor.replace(Some(
288                self.texture_descriptor_for_canvas_and_configuration(configuration),
289            ));
290        }
291    }
292
293    fn reset_bitmap(&self) {
294        warn!("The GPUCanvasContext 'reset_bitmap' is not implemented yet");
295    }
296
297    /// <https://gpuweb.github.io/gpuweb/#ref-for-abstract-opdef-get-a-copy-of-the-image-contents-of-a-context%E2%91%A5>
298    fn get_image_data(&self) -> Option<Snapshot> {
299        // 1. Return a copy of the image contents of context.
300        Some(if self.cleared.get() {
301            Snapshot::cleared(self.size())
302        } else {
303            let (sender, receiver) = generic_channel::channel().unwrap();
304            self.droppable
305                .channel
306                .0
307                .send(WebGPURequest::GetImage {
308                    context_id: self.context_id(),
309                    // We need to read from the pending texture, if one exists.
310                    pending_texture: self.pending_texture(),
311                    sender,
312                })
313                .ok()?;
314            receiver.recv().ok()?.to_owned()
315        })
316    }
317
318    fn canvas(&self) -> Option<RootedHTMLCanvasElementOrOffscreenCanvas> {
319        Some(RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas))
320    }
321
322    fn mark_as_dirty(&self) {
323        self.canvas.mark_as_dirty();
324    }
325}
326
327impl GPUCanvasContextMethods<crate::DomTypeHolder> for GPUCanvasContext {
328    /// <https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-canvas>
329    fn Canvas(&self) -> RootedHTMLCanvasElementOrOffscreenCanvas {
330        RootedHTMLCanvasElementOrOffscreenCanvas::from(&self.canvas)
331    }
332
333    /// <https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-configure>
334    fn Configure(&self, configuration: &GPUCanvasConfiguration) -> Fallible<()> {
335        // 1. Let device be configuration.device
336        let device = &configuration.device;
337
338        // 6. Let descriptor be the GPUTextureDescriptor for the canvas and configuration.
339        let descriptor = self.texture_descriptor_for_canvas_and_configuration(configuration);
340
341        // 2. Validate texture format required features of configuration.format with device.[[device]].
342        // 3. Validate texture format required features of each element of configuration.viewFormats with device.[[device]].
343        let (mut wgpu_descriptor, _) =
344            convert_texture_descriptor::<crate::DomTypeHolder>(&descriptor, device)?;
345        wgpu_descriptor.label = Some(Cow::Borrowed(
346            "dummy texture for texture descriptor validation",
347        ));
348
349        // 4. If Supported context formats does not contain configuration.format, throw a TypeError
350        if !supported_context_format(configuration.format) {
351            return Err(Error::Type(cformat!(
352                "Unsupported context format: {:?}",
353                configuration.format
354            )));
355        }
356
357        // 5. If configuration.usage includes the TRANSIENT_ATTACHMENT bit, throw a TypeError.
358        if configuration.usage & GPUTextureUsageConstants::TRANSIENT_ATTACHMENT != 0 {
359            return Err(Error::Type(
360                c"configuration.usage includes the TRANSIENT_ATTACHMENT bit".into(),
361            ));
362        }
363
364        // 7. Let this.[[configuration]] to configuration.
365        self.configuration.replace(Some(configuration.clone()));
366
367        // 8. Set this.[[textureDescriptor]] to descriptor.
368        self.texture_descriptor.replace(Some(descriptor));
369
370        // 9. Replace the drawing buffer of this.
371        self.replace_drawing_buffer();
372
373        // 10. Issue the subsequent steps on the Device timeline of device.
374        // 10.1. Validate texture descriptor
375        let texture_id = self.global().wgpu_id_hub().create_texture_id();
376        self.droppable
377            .channel
378            .0
379            .send(WebGPURequest::ValidateTextureDescriptor {
380                device_id: device.id().0,
381                texture_id,
382                descriptor: wgpu_descriptor,
383            })
384            .expect("Failed to create WebGPU SwapChain");
385
386        Ok(())
387    }
388
389    /// <https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-unconfigure>
390    fn Unconfigure(&self) {
391        // 1. Set this.[[configuration]] to null.
392        self.configuration.take();
393        // 2. Set this.[[textureDescriptor]] to null.
394        self.current_texture.take();
395        // 3. Replace the drawing buffer of this.
396        self.replace_drawing_buffer();
397    }
398
399    /// <https://www.w3.org/TR/webgpu/#dom-gpucanvascontext-getconfiguration>
400    fn GetConfiguration(&self) -> Option<RootedTraceableBox<GPUCanvasConfiguration>> {
401        self.configuration
402            .borrow()
403            .clone()
404            .map(RootedTraceableBox::new)
405    }
406
407    /// <https://gpuweb.github.io/gpuweb/#dom-gpucanvascontext-getcurrenttexture>
408    fn GetCurrentTexture(&self, cx: &mut JSContext) -> Fallible<DomRoot<GPUTexture>> {
409        // 1. If this.[[configuration]] is null, throw an InvalidStateError and return.
410        let configuration = self.configuration.borrow();
411        let Some(configuration) = configuration.as_ref() else {
412            return Err(Error::InvalidState(Some(
413                "GPUCanvasContext is not configured".into(),
414            )));
415        };
416        // 2. Assert this.[[textureDescriptor]] is not null.
417        let texture_descriptor = self.texture_descriptor.borrow();
418        let texture_descriptor = texture_descriptor.as_ref().unwrap();
419        // 3. Let device be this.[[configuration]].device.
420        let device = &configuration.device;
421        let current_texture = if let Some(current_texture) = self.current_texture.get() {
422            current_texture
423        } else {
424            // If this.[[currentTexture]] is null:
425            // 4.1. Replace the drawing buffer of this.
426            self.replace_drawing_buffer();
427            // 4.2. Set this.[[currentTexture]] to the result of calling device.createTexture() with this.[[textureDescriptor]],
428            // except with the GPUTexture’s underlying storage pointing to this.[[drawingBuffer]].
429            let current_texture = device.CreateTexture(cx, texture_descriptor)?;
430            self.current_texture.set(Some(&current_texture));
431
432            // The content of the texture is the content of the canvas.
433            self.cleared.set(false);
434
435            current_texture
436        };
437        // 6. Return this.[[currentTexture]].
438        Ok(current_texture)
439    }
440}