mln-rs-renderer 0.0.13

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::rc::Rc;

use mln_gfx::gpu::{ColorAttachment, DepthStencilAttachment, Gpu, GpuError, LoadOp, PassDesc, TargetFormats};
use mln_gfx::stencil_mode::Test;
use mln_gfx::types::{DepthFunctionType, StencilOpType};
use mln_gfx::{DepthMaskType, DepthMode, ScissorRect, StencilMode};
use mln_map_types::{MapDebugOptions, ProjectionData, TransformState, ViewportMode};
use mln_tile_id::UnwrappedTileID;
use mln_util::identity::SimpleIdentity;
use mln_util::logging::{Event, Log};
use mln_util::mat4::Mat4;
use mln_util::range::Range;
use mln_util::size::Size;
use mln_vec_map::VecMap;

use crate::clip_masks::ClipMasks;
use crate::gfx::context::Context;
use crate::layer_composite::LayerComposite;
use crate::line_atlas::LineAtlas;
use crate::pattern_atlas::PatternAtlas;
use crate::render_pass::RenderPass;
use crate::render_static_data::RenderStaticData;

pub(crate) struct TransformParameters {
    pub(crate) proj_matrix: Mat4,
    pub(crate) aligned_proj_matrix: Mat4,
    pub(crate) near_clipped_proj_matrix: Mat4,
    /// The near plane of `near_clipped_proj_matrix`, in pixels.
    pub(crate) near_clipped_near_z: f64,
    pub(crate) state: TransformState,
}

impl TransformParameters {
    pub(crate) fn new(state: &TransformState) -> Self {
        let state = state.clone();
        // Update the default matrices to the current viewport dimensions.
        let proj_matrix = state.get_proj_matrix(1, false);

        // Also compute a projection matrix that aligns with the current pixel
        // grid, taking into account odd viewport sizes.
        let aligned_proj_matrix = state.get_proj_matrix(1, true);

        // Calculate a second projection matrix with the near plane moved
        // further, to a tenth of the far value, so as not to waste depth
        // buffer precision on very close empty space, for layer types
        // (fill-extrusion) that use the depth buffer to emulate real-world
        // space.
        let near_z = (0.1 * f64::from(state.get_camera_to_center_distance())) as u16;
        let near_clipped_proj_matrix = state.get_proj_matrix(near_z, false);

        TransformParameters {
            proj_matrix,
            aligned_proj_matrix,
            near_clipped_proj_matrix,
            near_clipped_near_z: f64::from(near_z),
            state,
        }
    }
}

/// A pass of the backend's `Gpu` that drawables draw into, and its
/// attachments' size and formats.
#[derive(Clone, Copy)]
pub(crate) struct OpenPass {
    pub(crate) label: &'static str,
    pub(crate) color: Option<ColorAttachment>,
    pub(crate) depth_stencil: Option<DepthStencilAttachment>,
    pub(crate) size: Size,
    pub(crate) targets: TargetFormats,
}

impl OpenPass {
    /// The pass over the same attachments that loads them, with the
    /// stencil as `stencil` says.
    fn loading(&self, stencil: LoadOp<u32>) -> OpenPass {
        OpenPass {
            color: self.color.map(|color| ColorAttachment { load: LoadOp::Load, ..color }),
            depth_stencil: self.depth_stencil.map(|depth_stencil| DepthStencilAttachment {
                depth: LoadOp::Load,
                stencil,
                ..depth_stencil
            }),
            ..*self
        }
    }

    fn desc(&self) -> PassDesc<'static> {
        PassDesc { label: self.label, color: self.color, depth_stencil: self.depth_stencil }
    }
}

pub(crate) struct PaintParameters<'a> {
    pub(crate) context: &'a Context,
    /// The pass of the backend's `Gpu` that drawables draw into, while one
    /// is open.
    open_pass: Cell<Option<OpenPass>>,

    pub(crate) transform_params: &'a TransformParameters,
    pub(crate) state: &'a TransformState,
    /// conformance: `const EvaluatedLight& evaluatedLight` (a copy; the
    /// renderer sets it from the render tree's parameters).
    pub(crate) evaluated_light: crate::render_light::EvaluatedLight,
    pub(crate) static_data: &'a RenderStaticData,
    /// The orchestrator's line atlas. `new` starts with an empty one, and the
    /// renderer assigns the orchestrator's.
    pub(crate) line_atlas: Rc<RefCell<LineAtlas>>,
    pub(crate) pattern_atlas: Rc<RefCell<PatternAtlas>>,

    pub(crate) pass: RenderPass,
    pub(crate) debug_options: MapDebugOptions,

    pub(crate) pixel_ratio: f32,
    pub(crate) renderable_size: Size,
    pub(crate) pixels_to_gl_units: [f32; 2],

    /// The masks of the tiles that the frame's layer groups can clip to.
    pub(crate) clip_masks: ClipMasks,
    /// What the frame's layers drawn as a whole draw into and composite with.
    pub(crate) layer_composite: LayerComposite,
    /// The stencil value of each tile whose mask the stencil buffer holds.
    tile_clipping_mask_ids: VecMap<UnwrappedTileID, i32>,
    next_stencil_id: i32,

    pub(crate) current_layer: u32,
    pub(crate) depth_range_size: f32,
    pub(crate) opaque_pass_cutoff: u32,
    pub(crate) symbol_fade_change: f32,

    pub(crate) scissor_rect: ScissorRect,
    /// The frame that custom layers draw into, set before their prerender.
    pub(crate) custom_layer_frame: Option<mln_style::layers::CustomLayerFrame>,
}

impl<'a> PaintParameters<'a> {
    pub(crate) const NUM_SUBLAYERS: i32 = 3;
    pub(crate) const DEPTH_EPSILON: f32 = 1.0 / (1 << 16) as f32;
    pub(crate) const MAX_STENCIL_VALUE: i32 = 255;

    #[expect(clippy::too_many_arguments, reason = "each argument is a field of the paint parameters")]
    pub(crate) fn new(
        context: &'a Context,
        pixel_ratio: f32,
        debug_options: MapDebugOptions,
        transform_params: &'a TransformParameters,
        static_data: &'a RenderStaticData,
        pattern_atlas: Rc<RefCell<PatternAtlas>>,
        renderable_size: Size,
        scissor_rect: ScissorRect,
    ) -> Self {
        let state = &transform_params.state;
        let mut pixels_to_gl_units = [2.0f32 / state.get_size().width as f32, -2.0f32 / state.get_size().height as f32];

        if state.get_viewport_mode() == ViewportMode::FlippedY {
            pixels_to_gl_units[1] *= -1.0;
        }

        PaintParameters {
            context,
            open_pass: Cell::new(None),
            transform_params,
            state,
            static_data,
            evaluated_light: crate::render_light::EvaluatedLight::default(),
            line_atlas: Rc::new(RefCell::new(LineAtlas::new())),
            pattern_atlas,
            pass: RenderPass::Opaque,
            debug_options,
            pixel_ratio,
            renderable_size,
            pixels_to_gl_units,
            clip_masks: ClipMasks::default(),
            layer_composite: LayerComposite::default(),
            tile_clipping_mask_ids: VecMap::new(),
            next_stencil_id: 1,
            // The renderer sets these before use.
            current_layer: 0,
            depth_range_size: 1.0,
            opaque_pass_cutoff: 0,
            symbol_fade_change: 0.0,
            scissor_rect,
            custom_layer_frame: None,
        }
    }

    /// The size and formats of the attachments that drawables draw into
    /// now, `None` outside a pass.
    pub(crate) fn pass_target(&self) -> Option<(Size, TargetFormats)> {
        self.open_pass.get().map(|pass| (pass.size, pass.targets))
    }

    /// Begins `pass` on `gpu`, the context's, which drawables then draw
    /// into.
    pub(crate) fn begin_pass(&self, gpu: &mut dyn Gpu, pass: OpenPass) -> Result<(), GpuError> {
        gpu.begin_pass(&pass.desc())?;
        self.open_pass.set(Some(pass));
        Ok(())
    }

    /// Ends the pass begun on `gpu`, the context's, if any.
    pub(crate) fn end_pass(&self, gpu: &mut dyn Gpu) -> Result<(), GpuError> {
        match self.open_pass.take() {
            Some(_) => gpu.end_pass(),
            None => Ok(()),
        }
    }

    /// Ends the pass begun on `gpu`, the context's, and begins one over its
    /// attachments that loads them, with the stencil as `stencil` says.
    fn restart_pass(&self, gpu: &mut dyn Gpu, stencil: LoadOp<u32>) {
        let Some(pass) = self.open_pass.get() else {
            return;
        };
        let restarted = self.end_pass(gpu).and_then(|()| self.begin_pass(gpu, pass.loading(stencil)));
        if let Err(error) = restarted {
            Log::error(Event::Render, format!("Restarting the {} pass failed: {error}", pass.label));
        }
    }

    /// Runs `draw` into the layer composite's texture, rather than into the
    /// pass begun on `gpu`, the context's, and then composites the texture
    /// onto that pass as the layer group `group` asks. Runs `draw` into the
    /// pass begun where the frame doesn't composite `group`.
    ///
    /// `draw` starts with the texture's stencil clear, and the pass begun
    /// keeps its stencil as it was.
    pub(crate) fn draw_composited(
        &mut self,
        gpu: &mut dyn Gpu,
        group: SimpleIdentity,
        draw: impl FnOnce(&mut dyn Gpu, &mut Self),
    ) {
        let Some((frame, composite)) =
            self.open_pass.get().zip(self.layer_composite.pass()).filter(|_| self.layer_composite.composites(group))
        else {
            return draw(gpu, self);
        };
        let mut layer_composite = std::mem::take(&mut self.layer_composite);
        let mut drawn = self.end_pass(gpu);
        if drawn.is_ok()
            && let Some(backdrop) = layer_composite.backdrop_pass(group)
        {
            drawn = self
                .begin_pass(gpu, backdrop)
                .map(|()| layer_composite.copy_frame(gpu, self))
                .and_then(|()| self.end_pass(gpu));
        }
        drawn = drawn.and_then(|()| self.begin_pass(gpu, composite));
        if let Err(error) = &drawn {
            Log::error(Event::Render, format!("Beginning the layer composite's pass failed: {error}"));
        } else {
            let tile_clipping_mask_ids = std::mem::take(&mut self.tile_clipping_mask_ids);
            let next_stencil_id = std::mem::replace(&mut self.next_stencil_id, 1);
            draw(gpu, self);
            self.tile_clipping_mask_ids = tile_clipping_mask_ids;
            self.next_stencil_id = next_stencil_id;
            if let Err(error) = self.end_pass(gpu) {
                Log::error(Event::Render, format!("Ending the layer composite's pass failed: {error}"));
            }
        }
        if let Err(error) = self.begin_pass(gpu, frame.loading(LoadOp::Load)) {
            Log::error(Event::Render, format!("Resuming the {} pass failed: {error}", frame.label));
        } else if drawn.is_ok() {
            layer_composite.draw(gpu, self, group);
        }
        self.layer_composite = layer_composite;
    }

    /// Ends the frame's pass, which drew into the layer composite's frame
    /// texture, and begins `present`, which the texture is copied into.
    /// Does nothing where the frame drew into its target.
    pub(crate) fn present_frame(&mut self, gpu: &mut dyn Gpu, present: OpenPass) {
        if self.layer_composite.frame_texture().is_none() {
            return;
        }
        if let Err(error) = self.end_pass(gpu).and_then(|()| self.begin_pass(gpu, present)) {
            Log::error(Event::Render, format!("Beginning the frame's copy failed: {error}"));
            return;
        }
        let mut layer_composite = std::mem::take(&mut self.layer_composite);
        layer_composite.copy_frame(gpu, self);
        self.layer_composite = layer_composite;
    }

    /// Runs `f` with `gpu`'s, the context's, commands inside the pass
    /// begun, after what drew there so far, as a custom layer draws: `f`
    /// gets the backend's `CustomLayerPass`. Returns whether `f` ran.
    pub(crate) fn lend_pass(&self, gpu: &mut dyn Gpu, f: &mut dyn FnMut(&mut dyn Any)) -> Result<bool, GpuError> {
        if self.open_pass.get().is_none() {
            return Ok(false);
        }
        gpu.lend(f).map(|()| true)
    }

    #[must_use]
    pub(crate) fn projection_data_for_tile(&self, tile_id: &UnwrappedTileID, aligned: bool) -> ProjectionData {
        self.state.get_projection_data_with(
            tile_id,
            if aligned { &self.transform_params.aligned_proj_matrix } else { &self.transform_params.proj_matrix },
        )
    }

    #[must_use]
    pub(crate) fn depth_mode_for_sublayer(&self, n: u8, mask: DepthMaskType) -> DepthMode {
        // On the globe, 2D layers are ordered by draw order alone; their Z is
        // the back-hemisphere clip.
        if self.current_layer < self.opaque_pass_cutoff || self.state.is_globe_rendering() {
            return DepthMode::disabled();
        }

        // Wrapping unsigned arithmetic, then a float product.
        let steps =
            (1u32.wrapping_add(self.current_layer)).wrapping_mul(Self::NUM_SUBLAYERS as u32).wrapping_add(u32::from(n));
        let depth = self.depth_range_size + steps as f32 * Self::DEPTH_EPSILON;
        DepthMode { func: DepthFunctionType::LessEqual, mask, range: Range::new(depth, depth) }
    }

    /// The depth of `depth_mode_for_sublayer(0, ..)` where 2D layers write
    /// depth, whether or not the current layer does.
    #[must_use]
    pub(crate) fn layer_depth(&self) -> f32 {
        let steps = (1u32.wrapping_add(self.current_layer)).wrapping_mul(Self::NUM_SUBLAYERS as u32);
        self.depth_range_size + steps as f32 * Self::DEPTH_EPSILON
    }

    #[must_use]
    pub(crate) fn depth_mode_for_3d(&self, mask: DepthMaskType) -> DepthMode {
        DepthMode { func: DepthFunctionType::LessEqual, mask, range: Range::new(0.0, self.depth_range_size) }
    }

    pub(crate) fn clear_stencil(&mut self, gpu: &mut dyn Gpu) {
        self.next_stencil_id = 1;
        self.tile_clipping_mask_ids.clear();

        match self.stencil_clear_tile() {
            Some(tile) => self.draw_clip_masks(gpu, &[(tile, 0)]),
            None => self.restart_pass(gpu, LoadOp::Clear(0)),
        }
        self.context.rendering_stats().stencil_clears += 1;
    }

    /// The tile whose mask `clear_stencil` draws zero with, where the render
    /// pass clears the stencil buffer only where it begins.
    #[must_use]
    pub(crate) fn stencil_clear_tile(&self) -> Option<UnwrappedTileID> {
        (!self.context.caps().clear_stencil_with_pass).then(|| UnwrappedTileID::new(0, 0, 0))
    }

    fn draw_clip_masks(&mut self, gpu: &mut dyn Gpu, masks: &[(UnwrappedTileID, i32)]) {
        let mut clip_masks = std::mem::take(&mut self.clip_masks);
        clip_masks.draw(gpu, masks, self);
        self.clip_masks = clip_masks;
    }

    /// Renders the clipping masks of `tile_ids`, unless the stencil buffer
    /// already holds exactly theirs.
    pub(crate) fn render_tile_clipping_masks(&mut self, gpu: &mut dyn Gpu, tile_ids: &[UnwrappedTileID]) {
        let covered = self.tile_clipping_mask_ids.len() == tile_ids.len()
            && self.tile_clipping_mask_ids.keys().zip(tile_ids.iter()).all(|(a, b)| a == b);
        if covered || self.pass_target().is_none() {
            return;
        }

        self.tile_clipping_mask_ids.clear();

        // If the stencil value would overflow, clear the stencil buffer so
        // that none of the new values remain set somewhere in it. Otherwise
        // the masks overwrite it incrementally.
        if self.next_stencil_id as usize + tile_ids.len() > Self::MAX_STENCIL_VALUE as usize {
            self.clear_stencil(gpu);
        }

        let mut masks = Vec::with_capacity(tile_ids.len());
        for tile_id in tile_ids {
            if self.tile_clipping_mask_ids.contains_key(tile_id) {
                continue;
            }
            self.tile_clipping_mask_ids.insert(*tile_id, self.next_stencil_id);
            masks.push((*tile_id, self.next_stencil_id));
            self.next_stencil_id += 1;
        }

        if !masks.is_empty() {
            self.draw_clip_masks(gpu, &masks);
            self.context.rendering_stats().stencil_updates += 1;
        }
    }

    #[must_use]
    pub(crate) fn stencil_mode_for_clipping(&self, tile_id: &UnwrappedTileID) -> StencilMode {
        let it = self.tile_clipping_mask_ids.get(tile_id);
        debug_assert!(it.is_some());
        let id = it.copied().unwrap_or(0b0000_0000);
        StencilMode {
            test: Test::Equal { mask: 0b1111_1111 },
            ref_: id,
            mask: 0b0000_0000,
            fail: StencilOpType::Keep,
            depth_fail: StencilOpType::Keep,
            pass: StencilOpType::Replace,
        }
    }

    pub(crate) fn stencil_mode_for_3d(&mut self, gpu: &mut dyn Gpu) -> StencilMode {
        if self.next_stencil_id + 1 > Self::MAX_STENCIL_VALUE {
            self.clear_stencil(gpu);
        }

        // We're potentially destroying the stencil clipping mask in this
        // pass. That means we'll have to recreate it for the next source if
        // any.
        self.tile_clipping_mask_ids.clear();

        let id = self.next_stencil_id;
        self.next_stencil_id += 1;
        StencilMode {
            test: Test::NotEqual { mask: 0b1111_1111 },
            ref_: id,
            mask: 0b1111_1111,
            fail: StencilOpType::Keep,
            depth_fail: StencilOpType::Keep,
            pass: StencilOpType::Replace,
        }
    }

    /// Give each drawable a 3D stencil mode of its own, clearing the stencil
    /// buffer first if they would not all fit, so no value handed out before
    /// the clear is drawn after it. Returns false, handing out none, when
    /// there are more drawables than the buffer holds values: the caller then
    /// takes each one's value with `stencil_mode_for_3d` as it draws it, so a
    /// clear falls between two draws.
    pub(crate) fn stencil_modes_for_3d(&mut self, gpu: &mut dyn Gpu, modes: &mut [StencilMode]) -> bool {
        if modes.len() >= Self::MAX_STENCIL_VALUE as usize {
            return false;
        }
        if self.next_stencil_id as usize + modes.len() > Self::MAX_STENCIL_VALUE as usize {
            self.clear_stencil(gpu);
        }
        for mode in modes.iter_mut() {
            *mode = self.stencil_mode_for_3d(gpu);
        }
        true
    }
}