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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// The two C++ constructors are `CollisionFeature::new_text` (shaped text)
// and `CollisionFeature::new_icon` (shaped icon). C++ copies the
// `RefIndexedSubfeature` into an owning `IndexedSubfeature`; here both are
// `IndexedSubfeature`, so it is cloned.

use geometry::Point;
use glam::Vec2;
use mln_math::deg2radf;
use mln_style_types::SymbolPlacementType;
use mln_text::PositionedIcon;
use mln_text::glyph::Shaping;
use mln_tile_id::geometry_tile_data::{GeometryCoordinate, GeometryCoordinates};
use mln_util::Padding;
use mln_util::grid_index::{BBox, BCircle};

use crate::geometry::anchor::Anchor;
use crate::geometry::feature_index::IndexedSubfeature;
use crate::util::pool::PoolRange;

/// The distance from `a` to `b` as C++ computes it: an `f64` square root of
/// the integer sum, narrowed to `f32`.
fn dist(a: GeometryCoordinate, b: GeometryCoordinate) -> f32 {
    let dx = f64::from(i32::from(b.x) - i32::from(a.x));
    let dy = f64::from(i32::from(b.y) - i32::from(a.y));
    (dx * dx + dy * dy).sqrt() as f32
}

/// The first smallest of `values` by `<`, as `std::min` picks it.
fn min4(values: [f32; 4]) -> f32 {
    let mut smallest = values[0];
    for value in &values[1..] {
        if *value < smallest {
            smallest = *value;
        }
    }
    smallest
}

/// The first largest of `values` by `<`, as `std::max` picks it.
fn max4(values: [f32; 4]) -> f32 {
    let mut largest = values[0];
    for value in &values[1..] {
        if largest < *value {
            largest = *value;
        }
    }
    largest
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum ProjectedCollisionBoxType {
    #[default]
    Unknown,
    Box,
    Circle,
}

/// A projected collision box or circle.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct ProjectedCollisionBox {
    geometry: ProjectedCollisionBoxGeometry,
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum ProjectedCollisionBoxGeometry {
    #[default]
    Unknown,
    Box(BBox),
    Circle(BCircle),
}

impl ProjectedCollisionBox {
    #[must_use]
    pub(crate) fn new_box(x1: f32, y1: f32, x2: f32, y2: f32) -> Self {
        ProjectedCollisionBox {
            geometry: ProjectedCollisionBoxGeometry::Box(BBox::new(Point::new(x1, y1), Point::new(x2, y2))),
        }
    }

    #[must_use]
    pub(crate) fn new_circle(x: f32, y: f32, r: f32) -> Self {
        ProjectedCollisionBox { geometry: ProjectedCollisionBoxGeometry::Circle(BCircle::new(Point::new(x, y), r)) }
    }

    /// The box; panics if this is a circle.
    #[must_use]
    pub(crate) fn box_(&self) -> &BBox {
        match &self.geometry {
            ProjectedCollisionBoxGeometry::Box(b) => b,
            _ => panic!("ProjectedCollisionBox::box: not a box"),
        }
    }

    /// The circle; panics if this is a box.
    #[must_use]
    pub(crate) fn circle(&self) -> &BCircle {
        match &self.geometry {
            ProjectedCollisionBoxGeometry::Circle(c) => c,
            _ => panic!("ProjectedCollisionBox::circle: not a circle"),
        }
    }

    /// The `type` member.
    #[must_use]
    pub(crate) fn type_(&self) -> ProjectedCollisionBoxType {
        match self.geometry {
            ProjectedCollisionBoxGeometry::Unknown => ProjectedCollisionBoxType::Unknown,
            ProjectedCollisionBoxGeometry::Box(_) => ProjectedCollisionBoxType::Box,
            ProjectedCollisionBoxGeometry::Circle(_) => ProjectedCollisionBoxType::Circle,
        }
    }

    #[must_use]
    pub(crate) fn is_circle(&self) -> bool {
        self.type_() == ProjectedCollisionBoxType::Circle
    }

    #[must_use]
    pub(crate) fn is_box(&self) -> bool {
        self.type_() == ProjectedCollisionBoxType::Box
    }
}

#[derive(Clone, Copy, Debug, PartialEq, mln_wire::Wire)]
pub(crate) struct CollisionBox {
    /// the box is centered around the anchor point
    pub(crate) anchor: Vec2,

    // the offset of the box from the label's anchor point.
    // TODO: might be needed for #13526
    // Point<float> offset;

    // distances to the edges from the anchor
    pub(crate) x1: f32,
    pub(crate) y1: f32,
    pub(crate) x2: f32,
    pub(crate) y2: f32,

    pub(crate) signed_distance_from_anchor: f32,
}

impl CollisionBox {
    #[must_use]
    pub(crate) fn new(anchor: Vec2, x1: f32, y1: f32, x2: f32, y2: f32, signed_distance_from_anchor: f32) -> Self {
        CollisionBox { anchor, x1, y1, x2, y2, signed_distance_from_anchor }
    }
}

#[derive(Clone, Debug, mln_wire::Wire)]
pub(crate) struct CollisionFeature {
    /// The feature's boxes, in its bucket's `SymbolInstancePools`.
    pub(crate) boxes: PoolRange,
    pub(crate) indexed_feature: IndexedSubfeature,
    pub(crate) along_line: bool,
}

impl CollisionFeature {
    /// The constructor for text.
    #[expect(
        clippy::too_many_arguments,
        reason = "the line, anchor and shaped text, and the box scale, padding, placement, feature, overscaling and rotation of its boxes"
    )]
    #[must_use]
    pub(crate) fn new_text(
        line: &GeometryCoordinates,
        anchor: &Anchor,
        shaped_text: &Shaping,
        box_scale: f32,
        padding: f32,
        placement: SymbolPlacementType,
        indexed_feature: &IndexedSubfeature,
        overscaling: f32,
        rotate: f32,
        boxes: &mut Vec<CollisionBox>,
    ) -> Self {
        let mut feature = CollisionFeature {
            boxes: PoolRange::at_end(boxes),
            indexed_feature: indexed_feature.clone(),
            along_line: placement != SymbolPlacementType::Point,
        };
        feature.initialize(
            boxes,
            line,
            anchor,
            shaped_text.top,
            shaped_text.bottom,
            shaped_text.left,
            shaped_text.right,
            None,
            box_scale,
            &Padding::uniform(padding),
            overscaling,
            rotate,
        );
        feature
    }

    /// The constructor for icons.
    ///
    /// Icons collision features are always `SymbolPlacementType::Point`, which
    /// means the collision feature will be viewport-rotation-aligned even if the
    /// icon is map-rotation-aligned (e.g. `icon-rotation-alignment: map` _or_
    /// `symbol-placement: line`). We're relying on most icons being "close
    /// enough" to square that having incorrect rotation alignment doesn't throw
    /// off collision detection too much. See:
    /// <https://github.com/mapbox/mapbox-gl-js/issues/4861>
    #[expect(
        clippy::too_many_arguments,
        reason = "the line, anchor and shaped icon, the box scale, padding, feature and rotation, and the pool"
    )]
    #[must_use]
    pub(crate) fn new_icon(
        line: &GeometryCoordinates,
        anchor: &Anchor,
        shaped_icon: Option<&PositionedIcon>,
        box_scale: f32,
        padding: &Padding,
        indexed_feature: &IndexedSubfeature,
        rotate: f32,
        boxes: &mut Vec<CollisionBox>,
    ) -> Self {
        let mut feature = CollisionFeature {
            boxes: PoolRange::at_end(boxes),
            indexed_feature: indexed_feature.clone(),
            along_line: false,
        };
        if let Some(shaped_icon) = shaped_icon {
            let image = shaped_icon.image();
            let mut icon = shaped_icon.clone();
            if image.content.is_some() && (image.text_fit_width.is_some() || image.text_fit_height.is_some()) {
                icon = shaped_icon.apply_text_fit();
            }
            feature.initialize(
                boxes,
                line,
                anchor,
                icon.top(),
                icon.bottom(),
                icon.left(),
                icon.right(),
                Some(shaped_icon.collision_padding()),
                box_scale,
                padding,
                1.0,
                rotate,
            );
        } else {
            feature.initialize(boxes, line, anchor, 0.0, 0.0, 0.0, 0.0, None, box_scale, padding, 1.0, rotate);
        }
        feature
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "the pool, line, anchor and box edges, and the paddings, scales and rotation of the boxes"
    )]
    /// Appends the feature's boxes to `boxes`, the pool its range is at the
    /// end of.
    fn initialize(
        &mut self,
        boxes: &mut Vec<CollisionBox>,
        line: &GeometryCoordinates,
        anchor: &Anchor,
        top: f32,
        bottom: f32,
        left: f32,
        right: f32,
        collision_padding: Option<&Padding>,
        box_scale: f32,
        padding: &Padding,
        overscaling: f32,
        rotate: f32,
    ) {
        if top == 0.0 && bottom == 0.0 && left == 0.0 && right == 0.0 {
            return;
        }

        let mut y1 = top * box_scale - padding.top;
        let mut y2 = bottom * box_scale + padding.bottom;
        let mut x1 = left * box_scale - padding.left;
        let mut x2 = right * box_scale + padding.right;

        if let Some(collision_padding) = collision_padding {
            x1 -= collision_padding.left * box_scale;
            y1 -= collision_padding.top * box_scale;
            x2 += collision_padding.right * box_scale;
            y2 += collision_padding.bottom * box_scale;
        }

        if self.along_line {
            let mut height = y2 - y1;
            let length = x2 - x1;

            if height <= 0.0 {
                return;
            }

            // `std::max(10.0f * boxScale, height)`.
            let min_height = 10.0f32 * box_scale;
            height = if min_height < height { height } else { min_height };

            // `convertPoint<int16_t>(anchor.point)`.
            let mut anchor_point = GeometryCoordinate::new(anchor.point.x as i16, anchor.point.y as i16);
            self.bboxify_label(
                boxes,
                line,
                &mut anchor_point,
                anchor.segment.unwrap_or(0),
                length,
                height,
                overscaling,
            );
        } else if rotate != 0.0 {
            // Account for *-rotate in point collision boxes
            // Doesn't account for icon-text-fit
            let rotate_radians = deg2radf(rotate);

            let rotation = Vec2::from_angle(rotate_radians);
            let tl = rotation.rotate(Vec2::new(x1, y1));
            let tr = rotation.rotate(Vec2::new(x2, y1));
            let bl = rotation.rotate(Vec2::new(x1, y2));
            let br = rotation.rotate(Vec2::new(x2, y2));

            // Collision features require an "on-axis" geometry,
            // so take the envelope of the rotated geometry
            // (may be quite large for wide labels rotated 45 degrees)
            let x_min = min4([tl.x, tr.x, bl.x, br.x]);
            let x_max = max4([tl.x, tr.x, bl.x, br.x]);
            let y_min = min4([tl.y, tr.y, bl.y, br.y]);
            let y_max = max4([tl.y, tr.y, bl.y, br.y]);

            self.boxes.push(boxes, CollisionBox::new(anchor.point, x_min, y_min, x_max, y_max, 0.0));
        } else {
            self.boxes.push(boxes, CollisionBox::new(anchor.point, x1, y1, x2, y2, 0.0));
        }
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "the pool, the line and the anchor on it, and the label's length, box size and overscaling"
    )]
    fn bboxify_label(
        &mut self,
        boxes: &mut Vec<CollisionBox>,
        line: &GeometryCoordinates,
        anchor_point: &mut GeometryCoordinate,
        segment: usize,
        label_length: f32,
        box_size: f32,
        overscaling: f32,
    ) {
        let step = box_size / 2.0;
        // `std::max(static_cast<int>(std::floor(labelLength / step)), 1)`.
        let n_boxes = ((label_length / step).floor() as i32).max(1);

        // We calculate line collision circles out to 300% of what would normally be
        // our max size, to allow collision detection to work on labels that expand
        // as they move into the distance Vertically oriented labels in the distant
        // field can extend past this padding This is a noticeable problem in
        // overscaled tiles where the pitch 0-based symbol spacing will put labels
        // very close together in a pitched map. To reduce the cost of adding extra
        // collision circles, we slowly increase them for overscaled tiles.
        let overscaling_padding_factor: f64 = 1.0 + 0.4 * f64::from(overscaling).log2();
        let n_pitch_padding_boxes = (f64::from(n_boxes) * overscaling_padding_factor / 2.0).floor() as i32;

        // offset the center of the first box by half a box so that the edge of the
        // box is at the edge of the label.
        let first_box_offset = -box_size / 2.0;

        let p = anchor_point;
        let mut index: usize = segment + 1;
        let mut anchor_distance = first_box_offset;
        let label_start_distance = -label_length / 2.0;
        let padding_start_distance = label_start_distance - label_length / 8.0;

        // move backwards along the line to the first segment the label appears on
        loop {
            if index == 0 {
                if anchor_distance > label_start_distance {
                    // there isn't enough room for the label after the beginning of
                    // the line checkMaxAngle should have already caught this
                    return;
                }
                // The line doesn't extend far enough back for all of our padding,
                // but we got far enough to show the label under most conditions.
                index = 0;
                break;
            }

            index -= 1;
            anchor_distance -= dist(line[index], *p);
            *p = line[index];

            if anchor_distance <= padding_start_distance {
                break;
            }
        }

        let mut segment_length = dist(line[index], line[index + 1]);

        for i in -n_pitch_padding_boxes..n_boxes + n_pitch_padding_boxes {
            // the distance the box will be from the anchor
            let box_offset = i as f32 * step;
            let mut box_distance_to_anchor = label_start_distance + box_offset;

            // make the distance between pitch padding boxes bigger
            if box_offset < 0.0 {
                box_distance_to_anchor += box_offset;
            }
            if box_offset > label_length {
                box_distance_to_anchor += box_offset - label_length;
            }

            if box_distance_to_anchor < anchor_distance {
                // The line doesn't extend far enough back for this box, skip it
                // (This could allow for line collisions on distant tiles)
                continue;
            }

            // the box is not on the current segment. Move to the next segment.
            while anchor_distance + segment_length < box_distance_to_anchor {
                anchor_distance += segment_length;
                index += 1;

                // There isn't enough room before the end of the line.
                if index + 1 >= line.len() {
                    return;
                }

                segment_length = dist(line[index], line[index + 1]);
            }

            // the distance the box will be from the beginning of the segment
            let segment_box_distance = box_distance_to_anchor - anchor_distance;

            let p0 = &line[index];
            let p1 = &line[index + 1];

            let box_anchor = Vec2::new(
                f32::from(p0.x) + segment_box_distance / segment_length * (i32::from(p1.x) - i32::from(p0.x)) as f32,
                f32::from(p0.y) + segment_box_distance / segment_length * (i32::from(p1.y) - i32::from(p0.y)) as f32,
            );

            // If the box is within boxSize of the anchor, force the box to be used
            // (so even 0-width labels use at least one box)
            // Otherwise, the .8 multiplication gives us a little bit of conservative
            // padding in choosing which boxes to use (see CollisionIndex#placedCollisionCircles)
            let padded_anchor_distance = if (box_distance_to_anchor - first_box_offset).abs() < step {
                0.0f32
            } else {
                (box_distance_to_anchor - first_box_offset) * 0.8f32
            };

            self.boxes.push(
                boxes,
                CollisionBox::new(
                    box_anchor,
                    -box_size / 2.0,
                    -box_size / 2.0,
                    box_size / 2.0,
                    box_size / 2.0,
                    padded_anchor_distance,
                ),
            );
        }
    }
}