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
// The vertex/index vectors are plain `Vec`s (the bucket is built on the
// worker thread and shared with `Arc`); the render layer copies them into
// the shared gfx vectors its drawables reference.

use std::sync::Arc;
use std::sync::atomic::Ordering;

use geometry::Point;
use mln_gfx::shaders::segment::{MAX_SEGMENT_VERTICES, SegmentBase};
use mln_map_types::TransformState;
use mln_style::PropertyEvaluationParameters;
use mln_style::evaluated::Evaluated;
use mln_style::expression::{Image, Value};
use mln_style::layers::FillExtrusion;
use mln_style::layers::fill_extrusion_layer_properties::{FillExtrusionLayoutProperties, FillExtrusionPaintProperties};
use mln_style_types::LightAnchorType;
use mln_style_types::image::ImagePositions;
use mln_tile::geometry_tile_data::{classify_rings, limit_holes, round_polygon_corners};
use mln_tile_id::CanonicalTileID;
use mln_tile_id::geometry_tile_data::{GeometryCollection, GeometryCoordinates, GeometryTileFeature};
use mln_util::Color;
use mln_util::error::Error;
use mln_util::mat3::{Mat3, matrix as mat3};
use mln_util::subdivision_granularity::SubdivisionGranularitySetting;
use mln_util::vectors::Vec3f;
use mln_vec_map::VecMap;
use parking_lot::RwLock;

use crate::bucket::{Bucket, BucketBase};
use crate::bucket_geometry::GeometryVec;
use crate::gfx::context::Context;
use crate::gfx::fill_large_mesh_arrays::fill_large_mesh_arrays;
use crate::layer_type::EvaluatedLayer;
use crate::layout::pattern_layout::{PatternLayerMap, PatternLayoutSpec};
use crate::paint_property_binder::{CrossFadedPaintPropertyBinder, PaintPropertyBinder};
use crate::util::subdivision::{SubdivisionResult, subdivide_polygon, subdivide_vertex_line};
use crate::util::triangulate::triangulate;

crate::paint_property_binders!(
    pub struct FillExtrusionBinders for FillExtrusionPaintProperties::PossiblyEvaluated {
        fill_extrusion_base => PaintPropertyBinder<f32>,
        fill_extrusion_color => PaintPropertyBinder<Color>,
        fill_extrusion_height => PaintPropertyBinder<f32>,
        fill_extrusion_pattern => CrossFadedPaintPropertyBinder<Image>,
    }
);

/// A vertex of the roof, and the wall instance from it to the next vertex of
/// its ring.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub(crate) struct FillExtrusionLayoutVertex {
    pub(crate) a1: [i16; 2],
    pub(crate) a2: [u16; 2],
}

/// A corner of the wall quad every instance draws: x picks the instance's
/// vertex (0) or the next one (1), y the base (0) or the top (1).
pub(crate) type FillExtrusionStaticVertex = [i16; 2];

/// A corner of a wall drawn without instancing, and the outline vertex the
/// wall starts at. A wall reads the next outline vertex four corners
/// further on.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub(crate) struct FillExtrusionWallVertex {
    pub(crate) corner: FillExtrusionStaticVertex,
    pub(crate) vertex: FillExtrusionLayoutVertex,
}

pub(crate) use crate::render_light::EvaluatedLight;

#[derive(mln_wire::Wire)]
pub(crate) struct FillExtrusionBucket {
    pub(crate) base: BucketBase,
    pub(crate) layout: FillExtrusionLayoutProperties::PossiblyEvaluated,

    pub(crate) vertices: GeometryVec<FillExtrusionLayoutVertex>,
    pub(crate) triangles: GeometryVec<u16>,
    pub(crate) triangle_segments: Vec<SegmentBase>,
    pub(crate) subdivision_granularity: SubdivisionGranularitySetting,

    /// Behind `RwLock`s: `update` (feature state) changes them while the
    /// bucket is shared.
    pub(crate) paint_property_binders: VecMap<String, RwLock<FillExtrusionBinders>>,
}

static EMPTY_FORMATTED_SECTION: Value = Value::Null;

/// The distance from `a` to `b`, cast to `u16` as C++'s
/// `static_cast<uint16_t>` does on x86-64: through a wider integer, keeping
/// the low bits.
fn dist_u16(a: Point<f64>, b: Point<f64>) -> u16 {
    let dx = b.x - a.x;
    let dy = b.y - a.y;
    ((dx * dx + dy * dy).sqrt() as i64) as u16
}

impl FillExtrusionBucket {
    #[must_use]
    pub(crate) fn new(
        layout: FillExtrusionLayoutProperties::PossiblyEvaluated,
        layer_paint_properties: &VecMap<String, Arc<EvaluatedLayer<FillExtrusion>>>,
        zoom: f32,
        _overscaling: u32,
    ) -> Self {
        let mut paint_property_binders = VecMap::new();
        for (id, properties) in layer_paint_properties {
            paint_property_binders
                .entry(id.clone())
                .or_insert_with(|| RwLock::new(FillExtrusionBinders::new(&properties.paint, zoom)));
        }
        FillExtrusionBucket {
            base: BucketBase::default(),
            layout,
            vertices: GeometryVec::default(),
            triangles: GeometryVec::default(),
            triangle_segments: Vec::new(),
            subdivision_granularity: SubdivisionGranularitySetting::none(),
            paint_property_binders,
        }
    }

    pub(crate) fn set_subdivision_granularity(&mut self, value: &SubdivisionGranularitySetting) {
        self.subdivision_granularity = *value;
    }

    #[must_use]
    pub(crate) fn layout_vertex(p: Point<f64>, edge_distance: u16, is_discarded: bool) -> FillExtrusionLayoutVertex {
        let int_part = Point::new(p.x.floor(), p.y.floor());
        // Multiply factional part by 2^7 to pack them into integers [0..127]
        let frac_x = ((p.x - int_part.x) * 128.0) as u8;
        let frac_y = ((p.y - int_part.y) * 128.0) as u8;

        FillExtrusionLayoutVertex {
            a1: [int_part.x as i16, int_part.y as i16],
            a2: [
                // We pack a bool (`isDiscarded`) indicating whether this
                // instance is discarded
                ((i32::from(frac_x) * 256 + i32::from(frac_y)) * 2 + i32::from(is_discarded)) as u16,
                // The edgeDistance attribute is used for wrapping
                // fill_extrusion patterns
                edge_distance,
            ],
        }
    }

    /// Appends the outline of `polygon`: each vertex of a ring is a wall
    /// instance up to the next one, the last vertex ends the ring.
    fn add_outline<T: Copy + Into<f64>, R: AsRef<[Point<T>]>>(&mut self, polygon: &[R]) {
        let vertices = self.vertices.get_mut();
        for ring in polygon {
            let ring = ring.as_ref();
            let mut edge_distance: usize = 0;
            for (i, p) in ring.iter().enumerate() {
                let p1 = Point::new(p.x.into(), p.y.into());
                let p2 = ring.get(i + 1).map(|p| Point::new(p.x.into(), p.y.into()));

                // processRingPoints(p1, p2, edgeDistance)
                vertices.push(Self::layout_vertex(p1, edge_distance as u16, p2.is_none()));

                if let Some(p2) = p2 {
                    let dist = usize::from(dist_u16(p1, p2));
                    if edge_distance + dist > usize::from(u16::MAX) {
                        edge_distance = 0;
                    }

                    edge_distance += dist;
                }
            }
        }
    }

    /// Adds the walls and the roof of one polygon (its outer ring, then its
    /// holes), with integer or, after corner rounding, float coordinates.
    /// The outline's vertices are the roof's, unless a subdivided `roof`
    /// (the globe's) is that mesh, with vertices of its own: the outline
    /// then stays out of the segments, as only its walls draw it.
    fn add_polygon<T: Copy + Into<f64>, R: AsRef<[Point<T>]>>(
        &mut self,
        polygon: &[R],
        roof: Option<&SubdivisionResult>,
    ) -> Result<(), Error> {
        let mut total_vertices: usize = 0;
        for ring in polygon {
            total_vertices += ring.as_ref().len();
            if total_vertices > usize::from(u16::MAX) {
                return Err(crate::bucket::geometry_too_long());
            }
        }

        if total_vertices == 0 {
            return Ok(());
        }

        if let Some(roof) = roof {
            self.add_outline(polygon);
            // The roof's vertices have no walls.
            fill_large_mesh_arrays(
                self.vertices.get_mut(),
                |x, y| Self::layout_vertex(Point::new(f64::from(x), f64::from(y)), 0, true),
                &mut self.triangle_segments,
                self.triangles.get_mut(),
                &roof.vertices,
                &roof.triangle_indices,
                None,
                MAX_SEGMENT_VERTICES,
            );
            return Ok(());
        }

        // The roof continues the last segment if that ends at the outline
        // and has room for it.
        let start_vertices = self.vertices.len();
        let continues = self.triangle_segments.last().is_some_and(|last| {
            last.vertex_offset + last.vertex_length == start_vertices
                && last.vertex_length + total_vertices <= MAX_SEGMENT_VERTICES
        });
        if !continues {
            self.triangle_segments.push(SegmentBase::new(start_vertices, self.triangles.len()));
        }
        let segment_index = self.triangle_segments.len() - 1;
        let first_index = self.triangle_segments[segment_index].vertex_length;

        self.add_outline(polygon);

        let indices: Vec<u32> = triangulate(polygon);
        debug_assert!(indices.len().is_multiple_of(3));
        let index = |i: u32| (first_index + i as usize) as u16;
        for triangle in indices.as_chunks::<3>().0 {
            // Counter-Clockwise winding order.
            self.triangles.get_mut().extend_from_slice(&[index(triangle[0]), index(triangle[2]), index(triangle[1])]);
        }

        let segment = &mut self.triangle_segments[segment_index];
        segment.vertex_length += total_vertices;
        segment.index_length += indices.len();
        Ok(())
    }

    #[must_use]
    pub(crate) fn light_color(light: &EvaluatedLight) -> [f32; 3] {
        let color = light.light_color.uniform();
        [color.r, color.g, color.b]
    }

    pub(crate) fn light_position(light: &EvaluatedLight, state: &TransformState) -> [f32; 3] {
        let mut light_pos: Vec3f = light.light_position.uniform().get_cartesian();
        let mut light_mat: Mat3 = [0.0; 9];
        mat3::identity(&mut light_mat);
        if *light.light_anchor.uniform() == LightAnchorType::Viewport {
            let a = light_mat;
            mat3::rotate(&mut light_mat, &a, -state.get_bearing());
        }
        let a = light_pos;
        mat3::transform_mat3f(&mut light_pos, &a, &light_mat);
        light_pos
    }

    #[must_use]
    pub(crate) fn light_intensity(light: &EvaluatedLight) -> f32 {
        *light.light_intensity.uniform()
    }
}

impl Bucket for FillExtrusionBucket {
    fn base(&self) -> &BucketBase {
        &self.base
    }

    fn add_feature(
        &mut self,
        feature: &dyn GeometryTileFeature,
        geometry: &GeometryCollection,
        pattern_positions: &ImagePositions,
        pattern_dependencies: &PatternLayerMap,
        index: usize,
        canonical: &CanonicalTileID,
    ) -> Result<(), Error> {
        for mut polygon in classify_rings(geometry) {
            // Optimize polygons with many interior rings for earcut
            // tessellation.
            limit_holes(&mut polygon, 500);

            let rounded_corner_distance = f64::from(*self.layout.fill_extrusion_rounded_corner_distance.uniform());
            if rounded_corner_distance > 0.0 {
                self.add_polygon(&round_polygon_corners(&polygon, rounded_corner_distance), None)?;
                continue;
            }

            // On the globe the walls follow subdivided rings and the roof is a
            // subdivided mesh of its own, spread over as many segments as it
            // needs. Rings with more vertices than a polygon may have are
            // extruded as on Mercator. Rounded corners are not subdivided.
            let granularity = self.subdivision_granularity.fill.get_granularity_for_zoom_level(canonical.z);
            if granularity >= 2 {
                let subdivided_rings: Vec<GeometryCoordinates> =
                    polygon.iter().map(|ring| subdivide_vertex_line(ring, granularity, true)).collect();
                let ring_vertices: usize = subdivided_rings.iter().map(Vec::len).sum();
                if ring_vertices <= MAX_SEGMENT_VERTICES {
                    let roof = subdivide_polygon(&polygon, canonical, granularity, false);
                    self.add_polygon(&subdivided_rings, Some(&roof))?;
                    continue;
                }
            }
            self.add_polygon(&polygon[..], None)?;
        }

        let length = self.vertices.len();
        for (id, binders) in &mut self.paint_property_binders {
            binders.get_mut().populate_vertex_vectors(
                feature,
                length,
                index,
                pattern_positions,
                pattern_dependencies.get(id),
                canonical,
                &EMPTY_FORMATTED_SECTION,
            );
        }
        Ok(())
    }

    fn upload(&self, _context: &Context) {
        self.base.uploaded.store(true, Ordering::SeqCst);
    }

    fn has_data(&self) -> bool {
        !self.triangle_segments.is_empty()
    }

    fn write_wire(&self, w: &mut mln_wire::Writer) {
        mln_wire::Wire::write(self, w);
    }

    fn update(
        &self,
        states: &crate::bucket::FeatureStates,
        layer: &mln_tile::TileLayer<'_>,
        layer_id: &str,
        image_positions: &ImagePositions,
    ) {
        if let Some(binders) = self.paint_property_binders.get(layer_id) {
            binders.write().update_vertex_vectors(states, layer, image_positions);
            self.base.uploaded.store(false, Ordering::SeqCst);

            // sharedVertices->updateModified()
            self.base.version.fetch_add(1, Ordering::SeqCst);
        }
    }
}

/// The pattern layout of fill-extrusion layers, which have no sort key.
pub(crate) struct FillExtrusionLayoutSpec;

impl PatternLayoutSpec for FillExtrusionLayoutSpec {
    type Type = FillExtrusion;
    type Bucket = FillExtrusionBucket;
    type Layout = FillExtrusionLayoutProperties::PossiblyEvaluated;

    fn evaluate_layout(
        layer: &EvaluatedLayer<FillExtrusion>,
        parameters: &PropertyEvaluationParameters,
    ) -> Self::Layout {
        layer.style.layout.evaluate(parameters)
    }

    fn pattern_property(layer: &EvaluatedLayer<FillExtrusion>) -> &Evaluated<Image> {
        &layer.paint.fill_extrusion_pattern
    }

    fn sorted(_leader: &EvaluatedLayer<FillExtrusion>) -> bool {
        // conformance: FillExtrusionLayerFactory::createLayout (no sort key)
        false
    }

    fn sort_key(
        _layout: &Self::Layout,
        _feature: &dyn GeometryTileFeature,
        _zoom: f32,
        _canonical: &CanonicalTileID,
    ) -> f32 {
        // SortKeyPropertyType = void
        0.0
    }

    fn constant_sort_key(_layout: &Self::Layout) -> Option<f32> {
        None
    }

    fn create_bucket(
        layout: &Self::Layout,
        layer_properties_map: &VecMap<String, Arc<EvaluatedLayer<FillExtrusion>>>,
        zoom: f32,
        overscaling: u32,
    ) -> FillExtrusionBucket {
        FillExtrusionBucket::new(layout.clone(), layer_properties_map, zoom, overscaling)
    }
    fn set_subdivision_granularity(bucket: &mut FillExtrusionBucket, value: &SubdivisionGranularitySetting) {
        bucket.set_subdivision_granularity(value);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn layout_vertex_packs_like_cpp() {
        let v = FillExtrusionBucket::layout_vertex(Point::new(10.0, 20.0), 7, true);
        assert_eq!(v.a1, [10, 20]);
        assert_eq!(v.a2, [1, 7]);

        let v = FillExtrusionBucket::layout_vertex(Point::new(-1.5, 2.25), 9, false);
        assert_eq!(v.a1, [-2, 2]);
        assert_eq!(v.a2, [(64 * 256 + 32) * 2, 9]);
    }
}