Skip to main content

mln_expression/
within.rs

1// Ports include/mln/style/expression/within.hpp,
2// src/mln/style/expression/within.cpp and the int64_t instantiations of
3// src/mln/util/geometry_util.{hpp,cpp} (point/line-in-polygon tests), whose
4// only user is this expression.
5//
6// Integer arithmetic on tile coordinates wraps where the C++ int64_t
7// arithmetic could overflow (UB in C++; it wraps on the targets we build
8// for). Rings and lines with fewer than two points walk no edges (C++ reads
9// out of bounds for an empty one).
10
11use crate::expression::{
12    Dependency, EvaluationContext, EvaluationResult, Expression, ExpressionBase, Kind, downcast,
13};
14use crate::parsing_context::{ParseResult, ParsingContext};
15use crate::type_::Type;
16use crate::value::Value;
17use maplibre_native_base::{Geometry, Point, Value as MbglValue, ValueObject};
18use mln_conversion::{Convertible, Error};
19use mln_tile_id::CanonicalTileID;
20use mln_tile_id::geometry_tile_data::{GeometryCoordinates, GeometryTileFeature};
21use mln_util::constants::{DEGREES_MAX, EXTENT, LONGITUDE_MAX};
22use mln_util::geometry::{FeatureType, to_feature_type};
23use mln_util::logging::{Event, Log};
24use std::f64::consts::PI;
25
26// --- util/geometry_util ---
27
28/// `GeometryBBox<int64_t>`: minX, minY, maxX, maxY.
29type WithinBBox = [i64; 4];
30/// `DefaultWithinBBox`.
31const DEFAULT_WITHIN_BBOX: WithinBBox = [i64::MAX, i64::MAX, i64::MIN, i64::MIN];
32
33type TilePolygon = Vec<Vec<Point<i64>>>;
34
35fn update_bbox(bbox: &mut WithinBBox, p: &Point<i64>) {
36    bbox[0] = bbox[0].min(p.x);
37    bbox[1] = bbox[1].min(p.y);
38    bbox[2] = bbox[2].max(p.x);
39    bbox[3] = bbox[3].max(p.y);
40}
41
42/// Check if bbox1 is within bbox2.
43fn box_within_box(bbox1: &WithinBBox, bbox2: &WithinBBox) -> bool {
44    if bbox1[0] <= bbox2[0] {
45        return false;
46    }
47    if bbox1[2] >= bbox2[2] {
48        return false;
49    }
50    if bbox1[1] <= bbox2[1] {
51        return false;
52    }
53    if bbox1[3] >= bbox2[3] {
54        return false;
55    }
56    true
57}
58
59fn ray_intersect(p: &Point<i64>, p1: &Point<i64>, p2: &Point<i64>) -> bool {
60    ((p1.y > p.y) != (p2.y > p.y))
61        && (p.x
62            < (p2.x.wrapping_sub(p1.x))
63                .wrapping_mul(p.y.wrapping_sub(p1.y))
64                .wrapping_div(p2.y.wrapping_sub(p1.y))
65                .wrapping_add(p1.x))
66}
67
68/// Check if point p is on line segment with end points p1 and p2.
69fn point_on_boundary(p: &Point<i64>, p1: &Point<i64>, p2: &Point<i64>) -> bool {
70    // requirements of point p on line segment:
71    // 1. colinear: cross product of vector p->p1(x1, y1) and vector
72    //    p->p2(x2, y2) equals to 0
73    // 2. p is between p1 and p2
74    let x1 = p.x.wrapping_sub(p1.x);
75    let y1 = p.y.wrapping_sub(p1.y);
76    let x2 = p.x.wrapping_sub(p2.x);
77    let y2 = p.y.wrapping_sub(p2.y);
78    (x1.wrapping_mul(y2).wrapping_sub(x2.wrapping_mul(y1)) == 0)
79        && (x1.wrapping_mul(x2) <= 0)
80        && (y1.wrapping_mul(y2) <= 0)
81}
82
83fn segment_intersect_segment(a: &Point<i64>, b: &Point<i64>, c: &Point<i64>, d: &Point<i64>) -> bool {
84    // a, b are end points for line segment1, c and d are end points for
85    // line segment2
86    let perp = |v1: &Point<i64>, v2: &Point<i64>| v1.x.wrapping_mul(v2.y).wrapping_sub(v1.y.wrapping_mul(v2.x));
87
88    // check if two segments are parallel or not
89    // precondition is end point a, b is inside polygon, if line a->b is
90    // parallel to polygon edge c->d, then a->b won't intersect with c->d
91    let vector_p = Point::new(b.x.wrapping_sub(a.x), b.y.wrapping_sub(a.y));
92    let vector_q = Point::new(d.x.wrapping_sub(c.x), d.y.wrapping_sub(c.y));
93    if perp(&vector_q, &vector_p) == 0 {
94        return false;
95    }
96
97    // check if p1 and p2 are in different sides of line segment q1->q2
98    let two_sided = |p1: &Point<i64>, p2: &Point<i64>, q1: &Point<i64>, q2: &Point<i64>| {
99        // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3)
100        let x1 = p1.x.wrapping_sub(q1.x);
101        let y1 = p1.y.wrapping_sub(q1.y);
102        let x2 = p2.x.wrapping_sub(q1.x);
103        let y2 = p2.y.wrapping_sub(q1.y);
104        let x3 = q2.x.wrapping_sub(q1.x);
105        let y3 = q2.y.wrapping_sub(q1.y);
106        let ret1 = x1.wrapping_mul(y3).wrapping_sub(x3.wrapping_mul(y1));
107        let ret2 = x2.wrapping_mul(y3).wrapping_sub(x3.wrapping_mul(y2));
108        (ret1 > 0 && ret2 < 0) || (ret1 < 0 && ret2 > 0)
109    };
110
111    // If lines are intersecting with each other, the relative location
112    // should be: a and b lie in different sides of segment c->d, c and d lie
113    // in different sides of segment a->b
114    two_sided(a, b, c, d) && two_sided(c, d, a, b)
115}
116
117fn line_intersect_polygon(p1: &Point<i64>, p2: &Point<i64>, polygon: &TilePolygon) -> bool {
118    // loop through every edge of every ring
119    polygon
120        .iter()
121        .any(|ring| ring.windows(2).any(|edge| segment_intersect_segment(p1, p2, &edge[0], &edge[1])))
122}
123
124/// Ray casting algorithm for detecting if point is in polygon.
125fn point_within_polygon(point: &Point<i64>, polygon: &TilePolygon, true_on_boundary: bool) -> bool {
126    let mut within = false;
127    for ring in polygon {
128        // loop through every edge of the ring
129        for edge in ring.windows(2) {
130            if point_on_boundary(point, &edge[0], &edge[1]) {
131                return true_on_boundary;
132            }
133            if ray_intersect(point, &edge[0], &edge[1]) {
134                within = !within;
135            }
136        }
137    }
138    within
139}
140
141fn point_within_polygons(point: &Point<i64>, polygons: &[TilePolygon], true_on_boundary: bool) -> bool {
142    polygons.iter().any(|polygon| point_within_polygon(point, polygon, true_on_boundary))
143}
144
145fn line_string_within_polygon(line: &[Point<i64>], polygon: &TilePolygon) -> bool {
146    // First, check if geometry points of line segments are all inside polygon
147    if !line.iter().all(|point| point_within_polygon(point, polygon, false)) {
148        return false;
149    }
150
151    // Second, check if there is line segment intersecting polygon edge
152    !line.windows(2).any(|segment| line_intersect_polygon(&segment[0], &segment[1], polygon))
153}
154
155fn line_string_within_polygons(line: &[Point<i64>], polygons: &[TilePolygon]) -> bool {
156    polygons.iter().any(|polygon| line_string_within_polygon(line, polygon))
157}
158
159// --- within.cpp ---
160
161/// `latLonToTileCoodinates`.
162fn lat_lon_to_tile_coordinates(point: &Point<f64>, canonical: &CanonicalTileID) -> Point<i64> {
163    let size = EXTENT as f64 * 2f64.powi(canonical.z as i32);
164
165    let x = (point.x + LONGITUDE_MAX) * size / DEGREES_MAX;
166    let y = (LONGITUDE_MAX - mln_math::rad2deg((point.y * PI / DEGREES_MAX + PI / 4.0).tan().ln())) * size
167        / DEGREES_MAX;
168
169    // `util::clamp<int64_t>(static_cast<int64_t>(x), min, max)`; `as`
170    // saturates where the C++ cast is UB.
171    Point::new(x as i64, y as i64)
172}
173
174fn get_tile_polygon(polygon: &[Vec<Point<f64>>], canonical: &CanonicalTileID, bbox: &mut WithinBBox) -> TilePolygon {
175    let mut result = Vec::with_capacity(polygon.len());
176    for ring in polygon {
177        let mut temp = Vec::with_capacity(ring.len());
178        for p in ring {
179            let coord = lat_lon_to_tile_coordinates(p, canonical);
180            temp.push(coord);
181            update_bbox(bbox, &coord);
182        }
183        result.push(temp);
184    }
185    result
186}
187
188fn get_tile_polygons(
189    polygon_geo_set: &Geometry<f64>,
190    canonical: &CanonicalTileID,
191    bbox: &mut WithinBBox,
192) -> Vec<TilePolygon> {
193    match polygon_geo_set {
194        Geometry::MultiPolygon(polygons) => polygons.iter().map(|pg| get_tile_polygon(pg, canonical, bbox)).collect(),
195        Geometry::Polygon(polygon) => vec![get_tile_polygon(polygon, canonical, bbox)],
196        _ => Vec::new(),
197    }
198}
199
200fn update_point(p: &mut Point<i64>, bbox: &mut WithinBBox, poly_bbox: &WithinBBox, world_size: i64) {
201    if p.x < poly_bbox[0] || p.x > poly_bbox[2] {
202        let get_shift = |point: &Point<i64>, polygon_side: i64, size: i64| -> i64 {
203            if point.x.wrapping_sub(polygon_side) > size / 2 {
204                return -size;
205            }
206            if polygon_side.wrapping_sub(point.x) > size / 2 {
207                return size;
208            }
209            0
210        };
211
212        let mut shift = get_shift(p, poly_bbox[0], world_size);
213        if shift == 0 {
214            shift = get_shift(p, poly_bbox[2], world_size);
215        }
216        p.x = p.x.wrapping_add(shift);
217    }
218    update_bbox(bbox, p);
219}
220
221/// `util::EXTENT * canonical.x`: an int32 times a uint32 is a uint32
222/// product in C++, widened to int64_t afterwards.
223fn tile_shift(coordinate: u32) -> i64 {
224    (EXTENT as u32).wrapping_mul(coordinate) as i64
225}
226
227/// `static_cast<int64_t>(util::EXTENT * std::pow(2, canonical.z))`.
228fn world_size(canonical: &CanonicalTileID) -> i64 {
229    (EXTENT as f64 * 2f64.powi(canonical.z as i32)) as i64
230}
231
232fn get_tile_points(
233    points: &GeometryCoordinates,
234    canonical: &CanonicalTileID,
235    bbox: &mut WithinBBox,
236    poly_bbox: &WithinBBox,
237) -> Vec<Point<i64>> {
238    let x_shift = tile_shift(canonical.x);
239    let y_shift = tile_shift(canonical.y);
240    let world_size = world_size(canonical);
241    let mut results = Vec::with_capacity(points.len());
242    for p in points {
243        let mut point = Point::new(p.x as i64 + x_shift, p.y as i64 + y_shift);
244        update_point(&mut point, bbox, poly_bbox, world_size);
245        results.push(point);
246    }
247    results
248}
249
250fn get_tile_lines(
251    lines: &[GeometryCoordinates],
252    canonical: &CanonicalTileID,
253    bbox: &mut WithinBBox,
254    poly_bbox: &WithinBBox,
255) -> Vec<Vec<Point<i64>>> {
256    let x_shift = tile_shift(canonical.x);
257    let y_shift = tile_shift(canonical.y);
258    let mut results = Vec::with_capacity(lines.len());
259    for line in lines {
260        let mut line_string = Vec::with_capacity(line.len());
261        for p in line {
262            let point = Point::new(p.x as i64 + x_shift, p.y as i64 + y_shift);
263            update_bbox(bbox, &point);
264            line_string.push(point);
265        }
266        results.push(line_string);
267    }
268
269    let world_size = world_size(canonical);
270    if bbox[2].wrapping_sub(bbox[0]) <= world_size / 2 {
271        *bbox = DEFAULT_WITHIN_BBOX;
272        for line in &mut results {
273            for p in line.iter_mut() {
274                update_point(p, bbox, poly_bbox, world_size);
275            }
276        }
277    }
278    results
279}
280
281fn feature_within_polygons(
282    feature: &dyn GeometryTileFeature,
283    canonical: &CanonicalTileID,
284    polygon_geo_set: &Geometry<f64>,
285) -> bool {
286    let mut poly_bbox = DEFAULT_WITHIN_BBOX;
287    let polygons = get_tile_polygons(polygon_geo_set, canonical, &mut poly_bbox);
288    debug_assert!(!polygons.is_empty());
289    let geometries = feature.get_geometries();
290    match feature.get_type() {
291        FeatureType::Point => {
292            // C++ asserts a geometry and reads `geometries.at(0)` (which
293            // throws when there is none).
294            let Some(first) = geometries.first() else {
295                return false;
296            };
297            let mut point_bbox = DEFAULT_WITHIN_BBOX;
298            let points = get_tile_points(first, canonical, &mut point_bbox, &poly_bbox);
299            if !box_within_box(&point_bbox, &poly_bbox) {
300                return false;
301            }
302
303            points.iter().all(|p| point_within_polygons(p, &polygons, false))
304        }
305        FeatureType::LineString => {
306            let mut line_bbox = DEFAULT_WITHIN_BBOX;
307            let multi_line_string = get_tile_lines(geometries, canonical, &mut line_bbox, &poly_bbox);
308            if !box_within_box(&line_bbox, &poly_bbox) {
309                return false;
310            }
311
312            multi_line_string.iter().all(|line| line_string_within_polygons(line, &polygons))
313        }
314        _ => false,
315    }
316}
317
318const POLYGON_REQUIRED: &str = "'within' expression requires valid geojson source that contains polygon geometry type.";
319
320fn parse_value(value: &Convertible<'_>, ctx: &mut ParsingContext) -> Option<geojson::GeoJSON> {
321    if value.is_object() {
322        let mut error = Error::default();
323        let geojson = value.to_geojson(&mut error);
324        if let Some(geojson) = geojson
325            && error.message.is_empty()
326        {
327            return Some(geojson);
328        }
329        ctx.error(error.message);
330    }
331
332    ctx.error(POLYGON_REQUIRED.to_owned());
333    None
334}
335
336fn get_polygon_info(geometry: &Geometry<f64>, ctx: &mut ParsingContext) -> Option<Geometry<f64>> {
337    if to_feature_type(geometry) == FeatureType::Polygon {
338        return Some(geometry.clone());
339    }
340    ctx.error(POLYGON_REQUIRED.to_owned());
341    None
342}
343
344/// `expression::Within`.
345pub struct Within {
346    base: ExpressionBase,
347    geojson_source: geojson::GeoJSON,
348    geometries: Geometry<f64>,
349}
350
351impl Within {
352    pub fn new(geojson: geojson::GeoJSON, geometries: Geometry<f64>) -> Self {
353        Within {
354            base: ExpressionBase::new(Kind::Within, Type::Boolean, Dependency::FEATURE),
355            geojson_source: geojson,
356            geometries,
357        }
358    }
359
360    pub fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
361        if value.is_array() {
362            // object value, quoted with ["within", value]
363            if value.array_length() != 2 {
364                ctx.error(format!(
365                    "'within' expression requires exactly one argument, but found {} instead.",
366                    mln_util::string::to_string_u64(value.array_length().wrapping_sub(1) as u64)
367                ));
368                return None;
369            }
370
371            let parsed_value = parse_value(&value.array_member(1), ctx)?;
372
373            let geometries: Vec<&Geometry<f64>> = match &parsed_value {
374                geojson::GeoJSON::Geometry(geometry_set) => vec![geometry_set],
375                geojson::GeoJSON::Feature(feature) => vec![&feature.geometry],
376                geojson::GeoJSON::FeatureCollection(features) => {
377                    features.iter().map(|feature| &feature.geometry).collect()
378                }
379            };
380            // The first polygon wins; every non-polygon before it reports an
381            // error.
382            for geometry in geometries {
383                if let Some(ret) = get_polygon_info(geometry, ctx) {
384                    return Some(Box::new(Within::new(parsed_value.clone(), ret)));
385                }
386            }
387            return None;
388        }
389        ctx.error("'within' expression needs to be an array with exactly one argument.".to_owned());
390        None
391    }
392}
393
394/// `valueConverter(const rapidjson_value&)`.
395fn value_converter(v: &serde_json::Value) -> MbglValue {
396    match v {
397        serde_json::Value::Number(n) => {
398            if let Some(i) = n.as_i64() {
399                MbglValue::Int(i)
400            } else if let Some(u) = n.as_u64() {
401                MbglValue::Uint(u)
402            } else {
403                MbglValue::Double(n.as_f64().unwrap_or(0.0))
404            }
405        }
406        serde_json::Value::Bool(b) => MbglValue::Bool(*b),
407        serde_json::Value::String(s) => MbglValue::String(s.clone()),
408        serde_json::Value::Array(a) => MbglValue::Array(a.iter().map(value_converter).collect()),
409        serde_json::Value::Object(o) => {
410            MbglValue::Object(o.iter().map(|(k, v)| (k.clone(), value_converter(v))).collect())
411        }
412        // Ignore other types as valid geojson only contains above types.
413        serde_json::Value::Null => MbglValue::Null,
414    }
415}
416
417impl Expression for Within {
418    fn base(&self) -> &ExpressionBase {
419        &self.base
420    }
421
422    fn evaluate(&self, params: &EvaluationContext<'_>) -> EvaluationResult {
423        let (Some(feature), Some(canonical)) = (params.feature, params.canonical) else {
424            return Ok(Value::Bool(false));
425        };
426        let geometry_type = feature.get_type();
427        // Currently only support Point and LineString types in Polygon/Polygons
428        if geometry_type == FeatureType::Point || geometry_type == FeatureType::LineString {
429            return Ok(Value::Bool(feature_within_polygons(feature, canonical, &self.geometries)));
430        }
431        Log::warning(
432            Event::General,
433            "within expression currently only support Point/LineString geometry type.",
434        );
435
436        Ok(Value::Bool(false))
437    }
438
439    fn each_child<'a>(&'a self, _visit: &mut dyn FnMut(&'a dyn Expression)) {}
440
441    fn equals(&self, e: &dyn Expression) -> bool {
442        if e.get_kind() == Kind::Within
443            && let Some(rhs) = downcast::<Within>(e)
444        {
445            return self.geojson_source == rhs.geojson_source && self.geometries == rhs.geometries;
446        }
447        false
448    }
449
450    fn possible_outputs(&self) -> Vec<Option<Value>> {
451        vec![Some(Value::Bool(true)), Some(Value::Bool(false))]
452    }
453
454    fn serialize(&self) -> MbglValue {
455        let value = geojson::to_json(&self.geojson_source);
456        let serialized: ValueObject = match &value {
457            serde_json::Value::Object(o) => o.iter().map(|(k, v)| (k.clone(), value_converter(v))).collect(),
458            _ => {
459                Log::error(
460                    Event::General,
461                    "Failed to serialize 'within' expression, converted rapidJSON is not an object",
462                );
463                ValueObject::new()
464            }
465        };
466        MbglValue::Array(vec![MbglValue::String(self.get_operator()), MbglValue::Object(serialized)])
467    }
468
469    fn get_operator(&self) -> String {
470        "within".to_owned()
471    }
472}