Skip to main content

mln_engine/layers/
custom.rs

1//! The `custom` layer type, whose layers a host draws with its own GPU
2//! commands: its style half ([`Custom`]) and its render half.
3
4// Differences from C++:
5// - The host's callbacks get the backend's live commands as an `Any` of the
6//   backend crate's type, where C++ has a parameters subclass per backend.
7//   Each frame's view and projection come with them, so the host never reads
8//   a camera newer than the frame.
9// - There is no `initialize`: the first prerender or render after the host
10//   starts, or after a `deinitialize` or `context_lost`, is for a new session.
11// - The style's layer holds the host, and its style data only refers to it,
12//   so a renderer that is leaked with its style data, because its graphics
13//   objects are gone, doesn't keep the host.
14//
15// How a custom layer draws differently from the others:
16// - The host's prerender runs in a step of its own after the layers' draws
17//   upload (`RenderLayer::prerender`), not in `update`, so it gets the frame's
18//   final projection, whose depth range depends on how many draw groups the
19//   frame has.
20// - What it draws is a draw group of its own (`DrawGroup::Custom`), whose
21//   `render` lends the frame's pass to the host
22//   (`PaintParameters::lend_pass`, through `Gpu::lend`).
23// - A host that drew is told the renderer stopped once the layer leaves it,
24//   after the GPU finished the host's work (`Gpu::flush`), or that
25//   its graphics objects are lost (`Renderer::lose_custom_layers`). A layer
26//   leaves (`RenderLayer::leave`) without a `Gpu` at hand, so its host waits
27//   in the orchestrator's `EndedHosts` until the renderer ends it with one
28//   (`end_hosts`).
29
30use std::any::Any;
31use std::sync::{Arc, Weak};
32
33use mln_gfx::gpu::Gpu;
34use mln_style::StyleRegistry;
35use mln_style::layer::{Layer, LayerStyle, LayerTypeInfo, NoProperties, SourceKind, StyleLayerType};
36use mln_style::property::table::{PropertyTable, PropertyVisitor};
37
38use crate::camera::{FrameProjection, MapView};
39use crate::draw::context::Context;
40use crate::layer::bucket::NoBucket;
41use crate::layer::layer_drawing::{DrawGroup, DrawOrder, LayerDrawing, TileMap};
42use crate::layer::layer_type::{EvaluatedLayer, LayerType};
43use crate::layer::layout::NoLayout;
44use crate::layer::render_layer::{LayerValues, Parts, PartsMut, RenderLayer, RenderLayerBase, TypedLayer};
45use crate::log_target;
46use crate::render::paint_parameters::PaintParameters;
47use crate::render::pass::RenderPass;
48use crate::render::tile::NoTileBucket;
49
50/// The frame that a custom layer draws into.
51#[derive(Clone, Copy, Debug, PartialEq)]
52pub struct CustomLayerFrame {
53    /// The camera, extent and scale factor that the frame shows.
54    pub view: MapView,
55    /// Where the frame draws the map, and the depth it writes there.
56    pub projection: FrameProjection,
57    /// The size of the frame's attachments, in physical pixels.
58    pub width: u32,
59    pub height: u32,
60}
61
62/// What [`CustomLayerHost::prerender`] gets.
63pub struct CustomLayerPrerenderParameters<'a> {
64    /// The frame's commands outside the map's render pass, as the backend's
65    /// type: `mln_vulkan::CustomLayerEncoder`, `mln_mtl::CustomLayerEncoder`,
66    /// `mln_gl::CustomLayerEncoder` or `mln_webgpu::CustomLayerEncoder`.
67    pub encoder: &'a mut dyn Any,
68    pub frame: &'a CustomLayerFrame,
69}
70
71/// What [`CustomLayerHost::render`] gets.
72pub struct CustomLayerRenderParameters<'a> {
73    /// The map's render pass, as the backend's type:
74    /// `mln_vulkan::CustomLayerPass`, `mln_mtl::CustomLayerPass`,
75    /// `mln_gl::CustomLayerPass` or `mln_webgpu::CustomLayerPass`, whose
76    /// docs say what the host may change.
77    pub pass: &'a mut dyn Any,
78    pub frame: &'a CustomLayerFrame,
79    /// The depth that the map's 2D layers write at the layer's place in the
80    /// style. The map draws its opaque 2D layers before `render`, those above
81    /// the layer too, and those wrote less depth.
82    pub layer_depth: f64,
83}
84
85/// Draws a custom layer with the host's own GPU commands, on the thread that
86/// renders the map.
87///
88/// Each frame that shows the layer calls `prerender` for every custom layer,
89/// bottom to top, before the map's render pass begins, then `render` at the
90/// layer's place in the pass. Once a renderer stops drawing the layer, it
91/// calls `deinitialize`, or `context_lost` when the renderer's graphics
92/// objects may be gone. The next `prerender` or `render` is for a new
93/// renderer, which can be on another device or backend.
94pub trait CustomLayerHost: Send + Sync {
95    fn prerender(&self, _parameters: &mut CustomLayerPrerenderParameters<'_>) {}
96
97    fn render(&self, _parameters: &mut CustomLayerRenderParameters<'_>) {}
98
99    /// Destroy the GPU objects made for the renderer that stopped: the GPU
100    /// no longer uses them.
101    fn deinitialize(&self) {}
102
103    /// Forget the GPU objects made for the renderer that stopped, without
104    /// destroying them.
105    fn context_lost(&self) {}
106}
107
108/// The `custom` layer type, whose layers a [`CustomLayerHost`] draws.
109pub struct Custom;
110
111static PROPERTIES: PropertyTable = PropertyTable::new(&[], &[]);
112
113impl StyleLayerType for Custom {
114    const INFO: LayerTypeInfo = LayerTypeInfo {
115        name: "custom",
116        source: SourceKind::None,
117        pass_3d: false,
118        fading_tiles: false,
119        cross_tile_index: false,
120        from_json: false,
121    };
122    const PROPERTIES: &'static PropertyTable = &PROPERTIES;
123
124    type LayoutProperties = NoProperties;
125    type PaintProperties = NoProperties;
126    type Extra = CustomHost;
127
128    fn visit_property<V: PropertyVisitor<LayerStyle<Self>>>(_slot: usize, _visitor: V) -> Option<V::Output> {
129        None
130    }
131}
132
133impl Custom {
134    /// A layer named `id` that `host` draws, whose filter and visibility
135    /// parse against `registry`'s functions. The layer holds `host`, and
136    /// its style data only refers to it.
137    #[must_use]
138    pub fn layer(registry: &StyleRegistry, id: &str, host: Arc<dyn CustomLayerHost>) -> Layer {
139        let mut style = LayerStyle::<Custom>::new(id.to_owned(), String::new());
140        style.extra = CustomHost(Arc::downgrade(&host));
141        Layer::from_style_holding(Arc::new(style), Arc::clone(registry.functions()), Arc::new(host))
142    }
143}
144
145/// The host of a custom layer, as its style data refers to it: there while
146/// the style has the layer or a renderer draws it.
147#[derive(Clone)]
148pub struct CustomHost(Weak<dyn CustomLayerHost>);
149
150impl Default for CustomHost {
151    /// No host.
152    fn default() -> Self {
153        struct NoHost;
154        impl CustomLayerHost for NoHost {}
155        CustomHost(Weak::<NoHost>::new())
156    }
157}
158
159impl CustomHost {
160    /// The host, unless the style no longer has the layer and no renderer
161    /// draws it.
162    #[must_use]
163    pub fn get(&self) -> Option<Arc<dyn CustomLayerHost>> {
164        self.0.upgrade()
165    }
166
167    /// Whether `host` is this one.
168    #[must_use]
169    pub fn is(&self, host: &Arc<dyn CustomLayerHost>) -> bool {
170        std::ptr::addr_eq(self.0.as_ptr(), Arc::as_ptr(host))
171    }
172}
173
174impl LayerType for Custom {
175    type Layout = NoLayout;
176    type Bucket = NoBucket;
177    type TileBucket<'a> = NoTileBucket;
178
179    fn render_layer(style: Arc<LayerStyle<Custom>>) -> Box<dyn RenderLayer> {
180        Box::new(RenderCustomLayer::new(style))
181    }
182}
183
184pub(crate) struct RenderCustomLayer {
185    base: RenderLayerBase,
186    values: LayerValues<Custom>,
187    drawing: CustomDrawing,
188}
189
190/// The layer's drawing, which keeps no tiles and no draws of its own: its
191/// one draw group is what the host draws.
192#[derive(Default)]
193pub(crate) struct CustomDrawing {
194    /// The host, while the renderer draws through it.
195    host: Option<Arc<dyn CustomLayerHost>>,
196    /// The frame the host last prerendered for.
197    frame: Option<CustomLayerFrame>,
198    /// Whether a callback ran since the renderer took the host, which then
199    /// has to hear that the renderer stopped.
200    used: bool,
201    /// Whether the layer draws, which it does from the first frame that
202    /// draws it.
203    updated: bool,
204}
205
206impl RenderCustomLayer {
207    pub(crate) fn new(impl_: Arc<LayerStyle<Custom>>) -> Self {
208        let host = impl_.extra.get();
209        let (mut base, values) = LayerValues::new(impl_);
210        base.passes = RenderPass::Translucent;
211        let drawing = CustomDrawing { host, frame: None, used: false, updated: false };
212        RenderCustomLayer { base, values, drawing }
213    }
214}
215
216/// The hosts of custom layers that left the renderer after they drew, which
217/// [`end_hosts`] tells that it stopped.
218pub(crate) type EndedHosts = Vec<Arc<dyn CustomLayerHost>>;
219
220/// Tells `hosts`, which left the renderer after drawing with `gpu`, that it
221/// stopped, once `gpu` finished their work, so that they free what they drew
222/// with.
223pub(crate) fn end_hosts(gpu: &mut dyn Gpu, hosts: EndedHosts) {
224    if hosts.is_empty() {
225        return;
226    }
227    if let Err(error) = gpu.flush(true) {
228        log::error!(target: log_target::RENDER, "Waiting for a custom layer's frames failed: {error}");
229    }
230    for host in hosts {
231        host.deinitialize();
232    }
233}
234
235impl CustomDrawing {
236    /// Lets go of the host, and returns it if it drew.
237    fn take_host(&mut self) -> Option<Arc<dyn CustomLayerHost>> {
238        self.host.take().filter(|_| std::mem::take(&mut self.used))
239    }
240
241    /// Lets go of the host, telling it that its graphics objects are lost if
242    /// it drew.
243    fn lose(&mut self) {
244        if let Some(host) = self.take_host() {
245            host.context_lost();
246        }
247    }
248
249    /// In the translucent pass, lends the live pass to the host.
250    fn lend_pass(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
251        if parameters.pass_target().is_none() || parameters.pass != RenderPass::Translucent {
252            return;
253        }
254        let (Some(host), Some(frame)) = (&self.host, self.frame) else {
255            return;
256        };
257        let layer_depth = f64::from(parameters.layer_depth());
258        let lent = parameters.lend_pass(gpu, &mut |pass| {
259            host.render(&mut CustomLayerRenderParameters { pass, frame: &frame, layer_depth });
260        });
261        match lent {
262            Ok(lent) => {
263                self.used |= lent;
264            }
265            Err(error) => parameters.context.fail(format!("Lending a custom layer the pass failed: {error}")),
266        }
267    }
268}
269
270impl Drop for CustomDrawing {
271    /// A layer dropped without leaving, as with a renderer dropped without
272    /// its tear-down, loses its host's graphics objects.
273    fn drop(&mut self) {
274        self.lose();
275    }
276}
277
278impl LayerDrawing for CustomDrawing {
279    type Tile = ();
280
281    fn tiles(&mut self) -> Option<&mut TileMap<()>> {
282        None
283    }
284
285    fn visit_groups<'a>(&'a self, visit: &mut dyn FnMut(DrawGroup<'a>)) {
286        if self.updated {
287            visit(DrawGroup::Custom);
288        }
289    }
290
291    fn clear(&mut self) {}
292
293    /// The layer draws in every frame it is renderable in.
294    fn begin_frame(&mut self) {
295        self.updated = true;
296    }
297
298    fn clear_frame(&mut self) {}
299
300    fn upload(&mut self, _gpu: &mut dyn Gpu, _context: &mut Context) {}
301
302    fn render(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>, order: DrawOrder) {
303        if self.updated {
304            self.lend_pass(gpu, parameters);
305            order.step(parameters);
306        }
307    }
308}
309
310impl TypedLayer for RenderCustomLayer {
311    type Type = Custom;
312    type Drawing = CustomDrawing;
313
314    fn parts(&self) -> Parts<'_, Self> {
315        Parts { base: &self.base, values: &self.values, drawing: &self.drawing }
316    }
317
318    fn parts_mut(&mut self) -> PartsMut<'_, Self> {
319        PartsMut { base: &mut self.base, values: &mut self.values, drawing: &mut self.drawing }
320    }
321
322    fn passes(&self, _evaluated: &EvaluatedLayer<Custom>) -> RenderPass {
323        RenderPass::Translucent
324    }
325
326    /// A new host for the same layer ID is a new layer to the host: the old
327    /// one goes to `ended`, to hear that the renderer stopped.
328    fn style_changed(&mut self, ended: &mut EndedHosts) {
329        let drawing = &mut self.drawing;
330        let same = drawing.host.as_ref().is_some_and(|host| self.values.style.extra.is(host));
331        if !same {
332            ended.extend(drawing.take_host());
333            drawing.host = self.values.style.extra.get();
334        }
335    }
336}
337
338impl RenderLayer for RenderCustomLayer {
339    /// The layer has no properties: it only keeps drawing in the
340    /// translucent pass.
341    fn prerender(&mut self, gpu: &mut dyn Gpu, parameters: &mut PaintParameters<'_>) {
342        let Some(frame) = parameters.custom_layer_frame else {
343            return;
344        };
345        let drawing = &mut self.drawing;
346        drawing.frame = Some(frame);
347        let Some(host) = &drawing.host else { return };
348        let lent = gpu.lend(&mut |encoder| {
349            host.prerender(&mut CustomLayerPrerenderParameters { encoder, frame: &frame });
350        });
351        match lent {
352            Ok(()) => drawing.used = true,
353            Err(error) => parameters.context.fail(format!("Lending a custom layer the commands failed: {error}")),
354        }
355    }
356
357    fn leave(&mut self, ended: &mut EndedHosts) {
358        ended.extend(self.drawing.take_host());
359    }
360
361    fn lose_context(&mut self) {
362        self.drawing.lose();
363    }
364}
365
366#[cfg(test)]
367mod tests {
368    use std::sync::Arc;
369
370    use mln_style::layer::LayerStyle;
371
372    use super::{Custom, CustomLayerHost};
373    use crate::Registry;
374
375    struct Host;
376
377    impl CustomLayerHost for Host {}
378
379    /// A renderer that is leaked with the style data, because its graphics
380    /// objects are gone, must not keep the host, whose user data the C API
381    /// releases once the host goes.
382    #[test]
383    fn the_style_data_of_a_removed_layer_doesnt_keep_its_host() {
384        let host: Arc<dyn CustomLayerHost> = Arc::new(Host);
385        let layer = Custom::layer(Registry::with_builtins().style(), "custom", Arc::clone(&host));
386        let style = LayerStyle::<Custom>::recover(layer.style()).unwrap();
387        assert!(style.extra.is(&host));
388        assert!(style.extra.get().is_some());
389        drop(layer);
390        assert!(style.extra.get().is_some(), "the caller still holds the host");
391        drop(host);
392        assert!(style.extra.get().is_none());
393    }
394}