Skip to main content

mln_webgpu/
renderable_resource.rs

1// Ports include/mln/webgpu/renderable_resource.hpp
2//
3// `gfx::Renderable` stores its resource as `Rc<dyn gfx::RenderableResource>`.
4// The WebGPU resources are wrapped in `RenderableResourceBox`, the one
5// concrete type the backend downcasts to (`as_webgpu`), standing in for the
6// C++ `getResource<webgpu::RenderableResource>()` static_cast.
7//
8// `getBackend()`, `getCommandEncoder()` and `getRenderPassEncoder()` return
9// dummies in every C++ implementation; they are not ported.
10
11use mln_gfx::renderable;
12use std::any::Any;
13use std::rc::Rc;
14
15pub trait RenderableResource {
16    /// WebGPU binding happens at the command encoder level; a no-op.
17    fn bind(&self) {}
18
19    /// Renderable resources that require a swap function to be called
20    /// explicitly can override this method.
21    fn swap(&self) {}
22
23    /// The color attachment view for render passes targeting this resource,
24    /// or `None` if the backend supplies it (swapchain).
25    fn get_color_texture_view(&self) -> Option<wgpu::TextureView> {
26        None
27    }
28    fn get_color_texture_format(&self) -> Option<wgpu::TextureFormat> {
29        None
30    }
31    /// The depth/stencil view, if the resource manages one.
32    fn get_depth_stencil_texture_view(&self) -> Option<wgpu::TextureView> {
33        None
34    }
35    fn get_depth_stencil_texture_format(&self) -> Option<wgpu::TextureFormat> {
36        None
37    }
38
39    fn as_any(&self) -> &dyn Any;
40}
41
42/// The `gfx::RenderableResource` of every WebGPU renderable.
43pub struct RenderableResourceBox(pub Box<dyn RenderableResource>);
44
45impl renderable::RenderableResource for RenderableResourceBox {
46    fn bind(&self) {
47        self.0.bind();
48    }
49    fn as_any(&self) -> &dyn Any {
50        self
51    }
52}
53
54impl RenderableResourceBox {
55    pub fn new_rc(resource: impl RenderableResource + 'static) -> Rc<dyn renderable::RenderableResource> {
56        Rc::new(RenderableResourceBox(Box::new(resource)))
57    }
58}
59
60/// `renderable.getResource<webgpu::RenderableResource>()`
61pub fn as_webgpu(resource: &dyn renderable::RenderableResource) -> Option<&dyn RenderableResource> {
62    resource.as_any().downcast_ref::<RenderableResourceBox>().map(|b| b.0.as_ref())
63}
64
65/// `renderable.getResource<T>()` for a concrete WebGPU resource type.
66pub fn downcast_resource<T: 'static>(resource: &dyn renderable::RenderableResource) -> Option<&T> {
67    as_webgpu(resource)?.as_any().downcast_ref::<T>()
68}