Skip to main content

mln_gfx/
context.rs

1// Ports include/mln/gfx/context.hpp and src/mln/gfx/context.cpp
2//
3// All methods take `&self`: the context is reached from everywhere
4// (`PaintParameters`, render layers, upload passes) and wgpu's API is `&self`
5// too; the backend keeps mutable state in cells.
6//
7// TODO(port): `createDynamicTexture`, `createRenderTarget` (RenderTarget is a
8// renderer type), `createRenderbuffer`, `createDrawScope`,
9// `visualizeStencilBuffer`/`visualizeDepthBuffer` (debug builds) and
10// `threadSafeAccessRenderingStats` arrive with their first user.
11
12use std::any::Any;
13use std::cell::{Ref, RefCell, RefMut};
14
15use mln_util::size::Size;
16
17use crate::backend::Type as BackendType;
18use crate::command_encoder::CommandEncoder;
19use crate::drawable_builder::UniqueDrawableBuilder;
20use crate::globe_clip_mask::{GlobeClipMask, GlobeClipMeshFn};
21use crate::offscreen_texture::OffscreenTexture;
22use crate::projection_variant::ProjectionVariant;
23use crate::render_pass::RenderPass;
24use crate::renderer::layer_group::LayerGroupBasePtr;
25use crate::rendering_stats::RenderingStats;
26use crate::shader_registry::ShaderRegistry;
27use crate::shaders::clipping_mask_ubo::ClipUBO;
28use crate::shaders::shader_program_base::ShaderProgramBasePtr;
29use crate::texture2d::Texture2DPtr;
30use crate::types::TextureChannelDataType;
31use crate::uniform_buffer::{UniformBufferArray, UniformBufferPtr};
32use crate::vertex_attribute::VertexAttributeArrayPtr;
33
34/// The data members of `gfx::Context`.
35#[derive(Default)]
36pub struct ContextBase {
37    stats: RefCell<RenderingStats>,
38}
39
40pub trait Context: Any {
41    fn context_base(&self) -> &ContextBase;
42    fn as_any(&self) -> &dyn Any;
43
44    /// The backend this context is of. C++ builds one backend and asks
45    /// `gfx::Backend::GetType()`; the port can build several and asks the
46    /// context.
47    fn backend_type(&self) -> BackendType;
48
49    fn begin_frame(&self);
50    fn end_frame(&self);
51    fn perform_cleanup(&self);
52    fn reduce_memory_usage(&self);
53
54    fn create_offscreen_texture(&self, size: Size, type_: TextureChannelDataType) -> Box<dyn OffscreenTexture>;
55    fn create_command_encoder(&self) -> Box<dyn CommandEncoder>;
56
57    fn rendering_stats(&self) -> RefMut<'_, RenderingStats> {
58        self.context_base().stats.borrow_mut()
59    }
60    fn thread_safe_copy_rendering_stats(&self) -> RenderingStats {
61        self.context_base().stats.borrow().clone()
62    }
63
64    fn create_vertex_attribute_array(&self) -> VertexAttributeArrayPtr;
65    fn create_drawable_builder(&self, name: String) -> UniqueDrawableBuilder;
66    fn create_uniform_buffer(&self, data: &[u8], persistent: bool, ssbo: bool) -> UniformBufferPtr;
67    fn get_generic_shader(
68        &self,
69        registry: &ShaderRegistry,
70        name: &str,
71        variant: ProjectionVariant,
72    ) -> Option<ShaderProgramBasePtr>;
73    fn create_tile_layer_group(
74        &self,
75        layer_index: i32,
76        initial_capacity: usize,
77        name: String,
78    ) -> Option<LayerGroupBasePtr>;
79    fn create_layer_group(&self, layer_index: i32, initial_capacity: usize, name: String) -> Option<LayerGroupBasePtr>;
80    fn create_texture_2d(&self) -> Texture2DPtr;
81
82    /// Creates the buffer if `ptr` is empty (returns true), else updates it.
83    fn emplace_or_update_uniform_buffer(
84        &self,
85        ptr: &mut Option<UniformBufferPtr>,
86        data: &[u8],
87        persistent: bool,
88    ) -> bool;
89
90    fn get_global_uniform_buffers(&self) -> Ref<'_, UniformBufferArray>;
91    fn mutable_global_uniform_buffers(&self) -> RefMut<'_, UniformBufferArray>;
92    fn bind_global_uniform_buffers(&self, render_pass: &dyn RenderPass);
93    fn unbind_global_uniform_buffers(&self, render_pass: &dyn RenderPass);
94
95    /// Draws the tile clipping masks into the stencil buffer of the current
96    /// render pass, one draw per UBO (stencil reference `ubo.stencil_ref`).
97    ///
98    /// C++: `webgpu::Context::renderTileClippingMasks(renderPass, staticData,
99    /// tileUBOs)`, called by `PaintParameters::renderTileClippingMasks` under
100    /// `MLN_RENDER_BACKEND_WEBGPU` (Metal has the same method). On the trait
101    /// because `mln_renderer` can't name `mln_webgpu`; `staticData` is reduced to
102    /// the shader registry, the only member used. Backends without it return
103    /// false.
104    fn render_tile_clipping_masks(
105        &self,
106        _render_pass: &dyn RenderPass,
107        _shaders: &ShaderRegistry,
108        _tile_ubos: &[ClipUBO],
109    ) -> bool {
110        false
111    }
112
113    /// Drops the meshes and drawables kept for the globe's tile clipping
114    /// masks; a Mercator frame calls it. (C++ makes it pure virtual; here
115    /// backends without globe masks keep the empty default.)
116    fn release_globe_clip_masks(&self) {}
117
118    /// The globe's tile clipping masks, each drawn over the pole-capped mesh
119    /// of its tile, with a border and then without.
120    ///
121    /// C++: `webgpu::Context::renderGlobeTileClippingMasks(renderPass,
122    /// staticData, masks)`; on the trait for the reason
123    /// `render_tile_clipping_masks` is. C++ builds the meshes with
124    /// `rawGlobeTileMesh(tile, borders, SubdivisionGranularitySetting::globe().stencil)`,
125    /// which lives in `mln_renderer`, so the caller passes that call as
126    /// `mesh`, returning the mesh's raw `Short2` vertices and its indices; the
127    /// context still keeps one per zoom, pole row and border. Backends without
128    /// it return false.
129    fn render_globe_tile_clipping_masks(
130        &self,
131        _render_pass: &dyn RenderPass,
132        _shaders: &ShaderRegistry,
133        _masks: &[GlobeClipMask],
134        _mesh: &GlobeClipMeshFn<'_>,
135    ) -> bool {
136        false
137    }
138}
139
140impl dyn Context {
141    /// `emplaceOrUpdateUniformBuffer<T>(ptr, const T* data)` for a `Pod` UBO.
142    pub fn emplace_or_update_uniform_buffer_pod<T: bytemuck::Pod>(
143        &self,
144        ptr: &mut Option<UniformBufferPtr>,
145        data: &T,
146    ) -> bool {
147        self.emplace_or_update_uniform_buffer(ptr, bytemuck::bytes_of(data), false)
148    }
149}