Skip to main content

mln_webgpu/
renderer_backend.rs

1// Ports include/mln/webgpu/renderer_backend.hpp and src/mln/webgpu/renderer_backend.cpp
2//
3// The C++ backend stores raw `WGPUDevice`/`WGPUQueue`/instance handles in its
4// `Impl` and every resource reaches them through `Context& -> getBackend()`.
5// Here the `Impl` is shared (`Rc<BackendImpl>`) by the backend and the
6// context, and resources hold an `Rc<Context>`.
7//
8// What the backend draws into is a target built on it (`OffscreenTarget`,
9// `SurfaceTarget`), whose draw targets give the render passes their views.
10
11use std::any::Any;
12use std::cell::{Cell, RefCell};
13use std::rc::Rc;
14
15use mln_gfx::context::Context as GfxContext;
16use mln_gfx::renderer_backend::{self, RendererBackendBase};
17use mln_gfx::shader_registry::ShaderRegistry;
18use mln_gfx::shaders::program_parameters::ProgramParameters;
19use mln_gfx::shaders::shader_source::BuiltIn;
20
21use crate::context::Context;
22use crate::device::Device;
23use crate::shaders::shader_group::ShaderGroup;
24use crate::shaders::shader_source::shader_source;
25use crate::writes::Writes;
26
27/// `RendererBackend::Impl`
28#[derive(Default)]
29pub struct BackendImpl {
30    instance: RefCell<Option<wgpu::Instance>>,
31    device: RefCell<Option<wgpu::Device>>,
32    queue: RefCell<Option<wgpu::Queue>>,
33    /// `wgpu::TextureFormat::Undefined` is `None`.
34    depth_stencil_format: Cell<Option<wgpu::TextureFormat>>,
35    color_format: Cell<Option<wgpu::TextureFormat>>,
36    writes: RefCell<Writes>,
37    /// The page that small uniform buffers are taken from, and how many of
38    /// its bytes are taken.
39    uniform_page: RefCell<Option<(wgpu::Buffer, u64)>>,
40}
41
42/// The size of the buffers that small uniform buffers share.
43const UNIFORM_PAGE: u64 = 16 << 10;
44
45impl BackendImpl {
46    pub fn set_instance(&self, instance: Option<wgpu::Instance>) {
47        *self.instance.borrow_mut() = instance;
48    }
49    pub fn set_device(&self, device: Option<wgpu::Device>) {
50        *self.device.borrow_mut() = device;
51        *self.writes.borrow_mut() = Writes::default();
52        *self.uniform_page.borrow_mut() = None;
53    }
54    pub fn set_queue(&self, queue: Option<wgpu::Queue>) {
55        *self.queue.borrow_mut() = queue;
56    }
57    pub fn get_instance(&self) -> Option<wgpu::Instance> {
58        self.instance.borrow().clone()
59    }
60    pub fn get_device(&self) -> Option<wgpu::Device> {
61        self.device.borrow().clone()
62    }
63    pub fn get_queue(&self) -> Option<wgpu::Queue> {
64        self.queue.borrow().clone()
65    }
66    pub fn set_depth_stencil_format(&self, format: Option<wgpu::TextureFormat>) {
67        self.depth_stencil_format.set(format);
68    }
69    pub fn get_depth_stencil_format(&self) -> Option<wgpu::TextureFormat> {
70        self.depth_stencil_format.get()
71    }
72    pub fn set_color_format(&self, format: Option<wgpu::TextureFormat>) {
73        self.color_format.set(format);
74    }
75    pub fn get_color_format(&self) -> Option<wgpu::TextureFormat> {
76        self.color_format.get()
77    }
78
79    /// Port-only: writes `data` at `offset` in `buffer` ahead of the next
80    /// [`submit`](Self::submit)'s commands, as `Queue::write_buffer` does,
81    /// but small writes are gathered and copied into place together.
82    pub(crate) fn write_buffer(&self, buffer: &wgpu::Buffer, offset: u64, data: &[u8]) {
83        if let (Some(device), Some(queue)) = (self.device.borrow().as_ref(), self.queue.borrow().as_ref()) {
84            self.writes.borrow_mut().write(device, queue, buffer, offset, data);
85        }
86    }
87
88    /// Port-only: [`write_buffer`](Self::write_buffer) where the bytes after
89    /// `data` up to `padded` bytes from `offset` already hold zeros
90    /// (`Writes::write_padded`).
91    pub(crate) fn write_buffer_padded(&self, buffer: &wgpu::Buffer, offset: u64, data: &[u8], padded: u64) {
92        if let (Some(device), Some(queue)) = (self.device.borrow().as_ref(), self.queue.borrow().as_ref()) {
93            self.writes.borrow_mut().write_padded(device, queue, buffer, offset, data, padded);
94        }
95    }
96
97    /// Port-only: `size` bytes (a multiple of 256) of a new uniform buffer,
98    /// zero filled: the buffer and their offset in it. Small ones are taken
99    /// in turn from a shared page, so that UBOs made together sit together
100    /// and their writes join one copy. A page is freed with the last of its
101    /// UBOs (and the bind groups and commands that use them).
102    pub(crate) fn allocate_uniform_buffer(&self, device: &wgpu::Device, size: u64) -> (wgpu::Buffer, u64) {
103        let create = |size| {
104            device.create_buffer(&wgpu::BufferDescriptor {
105                label: Some("Uniform Buffer"),
106                size,
107                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
108                mapped_at_creation: false,
109            })
110        };
111        if size > UNIFORM_PAGE / 4 {
112            return (create(size), 0);
113        }
114        let mut page = self.uniform_page.borrow_mut();
115        let (buffer, taken) = match &mut *page {
116            Some((buffer, taken)) if *taken + size <= UNIFORM_PAGE => (buffer, taken),
117            _ => {
118                let (buffer, taken) = page.insert((create(UNIFORM_PAGE), 0));
119                (buffer, taken)
120            }
121        };
122        let offset = *taken;
123        *taken += size;
124        (buffer.clone(), offset)
125    }
126
127    /// Port-only: writes the bytes of `data` at `offset` in `buffer`
128    /// straight from the JS array they're in (`Writes::write_from_host`).
129    /// `offset` is a multiple of 4; a length that isn't is padded with
130    /// zeros.
131    #[cfg(target_family = "wasm")]
132    pub(crate) fn write_buffer_from_host(
133        &self,
134        buffer: &wgpu::Buffer,
135        offset: u64,
136        data: &mln_util::host_bytes::HostBytes,
137    ) {
138        let (Some(device), Some(queue)) = (self.device.borrow().clone(), self.queue.borrow().clone()) else {
139            return;
140        };
141        let len = data.len() as u64;
142        let aligned = len & !(wgpu::COPY_BUFFER_ALIGNMENT - 1);
143        let mut writes = self.writes.borrow_mut();
144        writes.write_from_host(&device, &queue, buffer, offset, data, aligned);
145        if aligned < len
146            && let Some(array) = data.array()
147        {
148            // writeBuffer takes whole 4-byte words.
149            let mut tail = [0u8; wgpu::COPY_BUFFER_ALIGNMENT as usize];
150            array.subarray(aligned as u32, len as u32).copy_to(&mut tail[..(len - aligned) as usize]);
151            writes.write(&device, &queue, buffer, offset + aligned, &tail);
152        }
153    }
154
155    /// Port-only: submits `command_buffer` after the copies of the writes
156    /// gathered by [`write_buffer`](Self::write_buffer).
157    pub(crate) fn submit(&self, command_buffer: wgpu::CommandBuffer) {
158        let (Some(device), Some(queue)) = (self.device.borrow().clone(), self.queue.borrow().clone()) else {
159            return;
160        };
161        let writes = self.writes.borrow_mut().encode(&device, &queue);
162        queue.submit(writes.into_iter().chain([command_buffer]));
163    }
164}
165
166/// `webgpu::RendererBackend`: a renderer's context on a [`Device`].
167pub struct RendererBackend {
168    base: RendererBackendBase,
169    impl_: Rc<BackendImpl>,
170    device: Device,
171}
172
173/// The shader types registered by `initShaders`, in the C++ order, with the
174/// instanced fill extrusion shaders after their plain ones, as on Metal.
175const REGISTERED_SHADERS: &[BuiltIn] = &[
176    BuiltIn::BackgroundShader,
177    BuiltIn::BackgroundPatternShader,
178    BuiltIn::SkyShader,
179    BuiltIn::AtmosphereShader,
180    BuiltIn::CircleShader,
181    BuiltIn::ClippingMaskProgram,
182    BuiltIn::CollisionBoxShader,
183    BuiltIn::CollisionCircleShader,
184    BuiltIn::DebugShader,
185    BuiltIn::FillShader,
186    BuiltIn::FillOutlineShader,
187    BuiltIn::FillPatternShader,
188    BuiltIn::FillOutlinePatternShader,
189    BuiltIn::FillOutlineTriangulatedShader,
190    BuiltIn::FillExtrusionShader,
191    BuiltIn::FillExtrusionInstancedShader,
192    BuiltIn::FillExtrusionPatternShader,
193    BuiltIn::FillExtrusionPatternInstancedShader,
194    BuiltIn::HeatmapShader,
195    BuiltIn::HeatmapTextureShader,
196    BuiltIn::HillshadeShader,
197    BuiltIn::HillshadePrepareShader,
198    BuiltIn::ColorReliefShader,
199    BuiltIn::LineShader,
200    BuiltIn::LineGradientShader,
201    BuiltIn::LinePatternShader,
202    BuiltIn::LineSDFShader,
203    BuiltIn::LineGradientSDFShader,
204    BuiltIn::RasterShader,
205    BuiltIn::SymbolIconShader,
206    BuiltIn::SymbolSDFShader,
207    BuiltIn::SymbolTextAndIconShader,
208    BuiltIn::WideVectorShader,
209    BuiltIn::GlobeDepthShader,
210];
211
212impl RendererBackend {
213    /// A backend on `device`. Backends on one device render independently,
214    /// each submitting to the device's queue.
215    #[must_use]
216    pub fn new(device: &Device) -> Self {
217        let impl_ = BackendImpl::default();
218        impl_.set_instance(device.instance().cloned());
219        impl_.set_device(Some(device.device().clone()));
220        impl_.set_queue(Some(device.queue().clone()));
221        RendererBackend { base: RendererBackendBase::new(), impl_: Rc::new(impl_), device: device.clone() }
222    }
223
224    /// The device the backend renders on.
225    pub fn device(&self) -> &Device {
226        &self.device
227    }
228
229    /// The backend's context, made on first use. Call inside a
230    /// `BackendScope`.
231    pub fn webgpu_context(&self) -> Option<Rc<Context>> {
232        let context = renderer_backend::RendererBackend::get_context(self);
233        context.as_any().downcast_ref::<Context>().map(Context::rc)
234    }
235
236    pub fn backend_impl(&self) -> &Rc<BackendImpl> {
237        &self.impl_
238    }
239
240    /// `context.reset()`, which also releases the buffers the context caches
241    /// (`Context::release_cached_buffers`).
242    pub(crate) fn reset_context(&mut self) {
243        if let Some(context) = self.base.reset_context()
244            && let Some(context) = context.as_any().downcast_ref::<Context>()
245        {
246            context.release_cached_buffers();
247        }
248    }
249
250    /// `createContext()`
251    pub fn create_context(&self) -> Rc<Context> {
252        Context::new(self.impl_.clone())
253    }
254
255    /// `initShaders`: register one `webgpu::ShaderGroup` per built-in shader.
256    ///
257    /// C++ registers all 31 types; a type whose WGSL is not part of this
258    /// build is skipped (TODO(port): all sources once the
259    /// `@maplibre//:webgpu-shader-headers` filegroup feeds the extractor).
260    /// A duplicate registration is an error, as in C++ (which throws).
261    pub fn init_shaders(&self, registry: &ShaderRegistry, program_parameters: &ProgramParameters) {
262        for &shader_id in REGISTERED_SHADERS {
263            let Some(source) = shader_source(shader_id) else {
264                continue;
265            };
266            let group = Rc::new(ShaderGroup::new(shader_id, program_parameters.clone()));
267            if !registry.register_shader_group(group, source.name) {
268                panic!("Failed to register {} with shader registry!", source.name);
269            }
270        }
271    }
272
273    pub fn get_instance(&self) -> Option<wgpu::Instance> {
274        self.impl_.get_instance()
275    }
276    pub fn get_device(&self) -> Option<wgpu::Device> {
277        self.impl_.get_device()
278    }
279    pub fn get_queue(&self) -> Option<wgpu::Queue> {
280        self.impl_.get_queue()
281    }
282    pub fn set_depth_stencil_format(&self, format: Option<wgpu::TextureFormat>) {
283        self.impl_.set_depth_stencil_format(format);
284    }
285    pub fn get_depth_stencil_format(&self) -> Option<wgpu::TextureFormat> {
286        self.impl_.get_depth_stencil_format()
287    }
288    pub fn set_color_format(&self, format: Option<wgpu::TextureFormat>) {
289        self.impl_.set_color_format(format);
290    }
291    pub fn get_color_format(&self) -> Option<wgpu::TextureFormat> {
292        self.impl_.get_color_format()
293    }
294}
295
296impl renderer_backend::RendererBackend for RendererBackend {
297    fn renderer_backend_base(&self) -> &RendererBackendBase {
298        &self.base
299    }
300
301    fn as_any(&self) -> &dyn Any {
302        self
303    }
304
305    fn init_shaders(&self, registry: &ShaderRegistry, parameters: &ProgramParameters) {
306        RendererBackend::init_shaders(self, registry, parameters);
307    }
308
309    fn create_context(&self) -> Rc<dyn GfxContext> {
310        RendererBackend::create_context(self)
311    }
312
313    /// WebGPU has no context to make current.
314    fn activate(&self) {}
315    fn deactivate(&self) {}
316}
317
318impl Drop for RendererBackend {
319    fn drop(&mut self) {
320        self.reset_context();
321    }
322}