mln-rs-style 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. 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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
// The geometry tests take differences and products of tile coordinates in
// `i128`, where they are exact. Rings and lines with fewer than two points
// have no edges.

use geo_types::{Coord, Geometry, LineString, Polygon};
use geojson::GeoJson;
use geometry::Point;

use crate::constants::EXTENT;
use crate::conversion::{Convertible, Error};
use crate::crs::WorldMapping;
use crate::expression::parse::{ParseResult, ParsingContext};
use crate::expression::{EvaluationContext, Expr, Node};
use crate::feature::{Feature, GeometryCoordinates, GeometryTileFeature, Value as FeatureValue};
use crate::geometry::FeatureType;
use crate::log_target;
use crate::sources::geojson::features_to_world;
use crate::tile_id::CanonicalTileID;

/// A bounding box: min x, min y, max x, max y.
type WithinBBox = [i64; 4];
const DEFAULT_WITHIN_BBOX: WithinBBox = [i64::MAX, i64::MAX, i64::MIN, i64::MIN];

type TilePolygon = Vec<Vec<Point<i64>>>;

/// Whether a point on a polygon's boundary is within it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum BoundaryMode {
    Inside,
    Outside,
}

fn update_bbox(bbox: &mut WithinBBox, p: &Point<i64>) {
    bbox[0] = bbox[0].min(p.x);
    bbox[1] = bbox[1].min(p.y);
    bbox[2] = bbox[2].max(p.x);
    bbox[3] = bbox[3].max(p.y);
}

/// Check if bbox1 is within bbox2.
fn box_within_box(bbox1: &WithinBBox, bbox2: &WithinBBox) -> bool {
    if bbox1[0] <= bbox2[0] {
        return false;
    }
    if bbox1[2] >= bbox2[2] {
        return false;
    }
    if bbox1[1] <= bbox2[1] {
        return false;
    }
    if bbox1[3] >= bbox2[3] {
        return false;
    }
    true
}

/// The largest polygon coordinate, in magnitude. A feature's coordinates,
/// from a tile's `u32` coordinates and `i16` offsets, shifted by at most a
/// world's width toward the polygon, stay within 2^63 of it. Differences
/// then fit in 64 bits and cross products of two differences in `i128`.
const COORDINATE_LIMIT: i64 = 1 << 61;

/// `to - from`, widened for products.
fn delta(from: &Point<i64>, to: &Point<i64>) -> Point<i128> {
    Point::new(i128::from(to.x) - i128::from(from.x), i128::from(to.y) - i128::from(from.y))
}

/// The z component of the cross product of `u` and `v`.
fn cross(u: &Point<i128>, v: &Point<i128>) -> i128 {
    u.x * v.y - u.y * v.x
}

/// Whether a ray from `p` toward +x crosses the edge from `p1` to `p2`.
fn ray_intersect(p: &Point<i64>, p1: &Point<i64>, p2: &Point<i64>) -> bool {
    if (p1.y > p.y) == (p2.y > p.y) {
        return false;
    }
    // Whether p is left of where the edge crosses p's y, with both sides
    // multiplied by the edge's height, which isn't 0, to stay exact.
    let edge = delta(p1, p2);
    let to_p = delta(p1, p);
    let (lhs, rhs) = (to_p.x * edge.y, edge.x * to_p.y);
    if edge.y > 0 { lhs < rhs } else { lhs > rhs }
}

/// Check if point p is on line segment with end points p1 and p2.
fn point_on_boundary(p: &Point<i64>, p1: &Point<i64>, p2: &Point<i64>) -> bool {
    // requirements of point p on line segment:
    // 1. colinear: cross product of vector p->p1 and vector p->p2 equals 0
    // 2. p is between p1 and p2
    let v1 = delta(p1, p);
    let v2 = delta(p2, p);
    cross(&v1, &v2) == 0 && v1.x * v2.x <= 0 && v1.y * v2.y <= 0
}

fn segment_intersect_segment(a: &Point<i64>, b: &Point<i64>, c: &Point<i64>, d: &Point<i64>) -> bool {
    // a, b are end points for line segment1, c and d are end points for
    // line segment2

    // check if two segments are parallel or not
    // precondition is end point a, b is inside polygon, if line a->b is
    // parallel to polygon edge c->d, then a->b won't intersect with c->d
    if cross(&delta(c, d), &delta(a, b)) == 0 {
        return false;
    }

    // check if p1 and p2 are in different sides of line segment q1->q2
    let two_sided = |p1: &Point<i64>, p2: &Point<i64>, q1: &Point<i64>, q2: &Point<i64>| {
        let q = delta(q1, q2);
        let ret1 = cross(&delta(q1, p1), &q);
        let ret2 = cross(&delta(q1, p2), &q);
        (ret1 > 0 && ret2 < 0) || (ret1 < 0 && ret2 > 0)
    };

    // If lines are intersecting with each other, the relative location
    // should be: a and b lie in different sides of segment c->d, c and d lie
    // in different sides of segment a->b
    two_sided(a, b, c, d) && two_sided(c, d, a, b)
}

fn line_intersect_polygon(p1: &Point<i64>, p2: &Point<i64>, polygon: &TilePolygon) -> bool {
    // loop through every edge of every ring
    polygon.iter().any(|ring| ring.windows(2).any(|edge| segment_intersect_segment(p1, p2, &edge[0], &edge[1])))
}

/// Ray casting algorithm for detecting if point is in polygon.
fn point_within_polygon(point: &Point<i64>, polygon: &TilePolygon, boundary_mode: BoundaryMode) -> bool {
    let mut within = false;
    for ring in polygon {
        // loop through every edge of the ring
        for edge in ring.windows(2) {
            if point_on_boundary(point, &edge[0], &edge[1]) {
                return boundary_mode == BoundaryMode::Inside;
            }
            if ray_intersect(point, &edge[0], &edge[1]) {
                within = !within;
            }
        }
    }
    within
}

fn point_within_polygons(point: &Point<i64>, polygons: &[TilePolygon], boundary_mode: BoundaryMode) -> bool {
    polygons.iter().any(|polygon| point_within_polygon(point, polygon, boundary_mode))
}

fn line_string_within_polygon(line: &[Point<i64>], polygon: &TilePolygon) -> bool {
    // First, check if geometry points of line segments are all inside polygon
    if !line.iter().all(|point| point_within_polygon(point, polygon, BoundaryMode::Outside)) {
        return false;
    }

    // Second, check if there is line segment intersecting polygon edge
    !line.windows(2).any(|segment| line_intersect_polygon(&segment[0], &segment[1], polygon))
}

fn line_string_within_polygons(line: &[Point<i64>], polygons: &[TilePolygon]) -> bool {
    polygons.iter().any(|polygon| line_string_within_polygon(line, polygon))
}

/// `point`, a place in the world square, in the coordinates of the tiles at
/// `canonical`'s zoom.
fn world_to_tile_coordinates(point: &Coord<f64>, canonical: &CanonicalTileID) -> Point<i64> {
    let size = f64::from(EXTENT) * 2f64.powi(i32::from(canonical.z));
    // A coordinate beyond the limit, far outside the square, is clamped to it.
    let limit = COORDINATE_LIMIT as f64;
    Point::new((point.x * size).clamp(-limit, limit) as i64, (point.y * size).clamp(-limit, limit) as i64)
}

fn tile_polygon(
    polygon: &Polygon<f64>,
    bbox: &mut WithinBBox,
    to_tile: &impl Fn(&Coord<f64>) -> Point<i64>,
) -> TilePolygon {
    let mut result = Vec::with_capacity(1 + polygon.interiors().len());
    for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
        let mut temp = Vec::with_capacity(ring.0.len());
        for p in &ring.0 {
            let coord = to_tile(p);
            temp.push(coord);
            update_bbox(bbox, &coord);
        }
        result.push(temp);
    }
    result
}

/// The polygons of `polygon_geo_set` in tile coordinates, each of its
/// positions converted by `to_tile`.
fn tile_polygons(
    polygon_geo_set: &Geometry<f64>,
    bbox: &mut WithinBBox,
    to_tile: &impl Fn(&Coord<f64>) -> Point<i64>,
) -> Vec<TilePolygon> {
    match polygon_geo_set {
        Geometry::MultiPolygon(polygons) => polygons.iter().map(|pg| tile_polygon(pg, bbox, to_tile)).collect(),
        Geometry::Polygon(polygon) => vec![tile_polygon(polygon, bbox, to_tile)],
        Geometry::Rect(rect) => vec![tile_polygon(&rect.to_polygon(), bbox, to_tile)],
        Geometry::Triangle(triangle) => vec![tile_polygon(&triangle.to_polygon(), bbox, to_tile)],
        _ => Vec::new(),
    }
}

/// The polygons of `polygon_geo_set`, in lng/lat, in the coordinates of the
/// tiles at `canonical`'s zoom of the world square of `world`: at their
/// places on its plane ([`WorldMapping::places_from_lng_lats`]), past
/// Mercator's latitude limit too, where tile buffers reach. Where the
/// projection has no finite place for one of their positions, they go where
/// a GeoJSON source of a map drawn in it places them ([`features_to_world`]).
fn tile_polygons_in_world(
    polygon_geo_set: &Geometry<f64>,
    canonical: &CanonicalTileID,
    world: &WorldMapping,
    bbox: &mut WithinBBox,
) -> Vec<TilePolygon> {
    let polygons: Vec<Polygon<f64>> = match polygon_geo_set {
        Geometry::MultiPolygon(polygons) => polygons.0.clone(),
        Geometry::Polygon(polygon) => vec![polygon.clone()],
        Geometry::Rect(rect) => vec![rect.to_polygon()],
        Geometry::Triangle(triangle) => vec![triangle.to_polygon()],
        _ => Vec::new(),
    };
    let rings = |polygon: &Polygon<f64>| {
        std::iter::once(polygon.exterior().clone()).chain(polygon.interiors().iter().cloned()).collect::<Vec<_>>()
    };
    let lng_lats: Vec<[f64; 2]> = polygons.iter().flat_map(rings).flat_map(|ring| ring.0).map(|c| [c.x, c.y]).collect();
    let mut places = vec![[0.0; 2]; lng_lats.len()];
    world.places_from_lng_lats(&lng_lats, &mut places);
    if places.iter().all(|[x, y]| x.is_finite() && y.is_finite()) {
        let mut places = places.into_iter().map(|[x, y]| Coord { x, y });
        let mut place_ring = |ring: LineString<f64>| LineString(ring.0.iter().filter_map(|_| places.next()).collect());
        let placed: Vec<Polygon<f64>> = polygons
            .iter()
            .map(|polygon| {
                let mut rings = rings(polygon).into_iter().map(&mut place_ring);
                let exterior = rings.next().unwrap_or_else(|| LineString(Vec::new()));
                Polygon::new(exterior, rings.collect())
            })
            .collect();
        return tile_polygons(&Geometry::MultiPolygon(placed.into()), bbox, &|p| {
            world_to_tile_coordinates(p, canonical)
        });
    }
    let places = features_to_world(vec![Feature::new(polygon_geo_set.clone())], world);
    match places.first().and_then(|feature| feature.geometry.as_ref()) {
        Some(places) => tile_polygons(places, bbox, &|p| world_to_tile_coordinates(p, canonical)),
        None => Vec::new(),
    }
}

fn update_point(p: &mut Point<i64>, bbox: &mut WithinBBox, poly_bbox: &WithinBBox, world_size: i64) {
    if p.x < poly_bbox[0] || p.x > poly_bbox[2] {
        let get_shift = |point: &Point<i64>, polygon_side: i64, size: i64| -> i64 {
            if point.x - polygon_side > size / 2 {
                return -size;
            }
            if polygon_side - point.x > size / 2 {
                return size;
            }
            0
        };

        let mut shift = get_shift(p, poly_bbox[0], world_size);
        if shift == 0 {
            shift = get_shift(p, poly_bbox[2], world_size);
        }
        p.x += shift;
    }
    update_bbox(bbox, p);
}

/// The world coordinate of a tile's edge, from its tile coordinate.
fn tile_shift(coordinate: u32) -> i64 {
    i64::from(EXTENT) * i64::from(coordinate)
}

fn world_size(canonical: &CanonicalTileID) -> i64 {
    (f64::from(EXTENT) * 2f64.powi(i32::from(canonical.z))) as i64
}

/// The points of `points`, in `canonical`, in the coordinates of the tiles
/// at its zoom. Where the world `wraps`, a point more than half the world
/// east or west of the polygons moves a world toward them.
fn tile_points(
    points: &GeometryCoordinates,
    canonical: &CanonicalTileID,
    wraps: bool,
    bbox: &mut WithinBBox,
    poly_bbox: &WithinBBox,
) -> Vec<Point<i64>> {
    let x_shift = tile_shift(canonical.x);
    let y_shift = tile_shift(canonical.y);
    let world_size = world_size(canonical);
    let mut results = Vec::with_capacity(points.len());
    for p in points {
        let mut point = Point::new(i64::from(p.x) + x_shift, i64::from(p.y) + y_shift);
        if wraps {
            update_point(&mut point, bbox, poly_bbox, world_size);
        } else {
            update_bbox(bbox, &point);
        }
        results.push(point);
    }
    results
}

/// The lines of `lines`, in `canonical`, in the coordinates of the tiles at
/// its zoom. Where the world `wraps`, lines that span less than half the
/// world move as points do.
fn tile_lines(
    lines: &[GeometryCoordinates],
    canonical: &CanonicalTileID,
    wraps: bool,
    bbox: &mut WithinBBox,
    poly_bbox: &WithinBBox,
) -> Vec<Vec<Point<i64>>> {
    let x_shift = tile_shift(canonical.x);
    let y_shift = tile_shift(canonical.y);
    let mut results = Vec::with_capacity(lines.len());
    for line in lines {
        let mut line_string = Vec::with_capacity(line.len());
        for p in line {
            let point = Point::new(i64::from(p.x) + x_shift, i64::from(p.y) + y_shift);
            update_bbox(bbox, &point);
            line_string.push(point);
        }
        results.push(line_string);
    }

    let world_size = world_size(canonical);
    // An empty bbox, max below min, is narrow too.
    if wraps && bbox[2].saturating_sub(bbox[0]) <= world_size / 2 {
        *bbox = DEFAULT_WITHIN_BBOX;
        for line in &mut results {
            for p in line.iter_mut() {
                update_point(p, bbox, poly_bbox, world_size);
            }
        }
    }
    results
}

/// Whether `feature`, in `canonical` of the world square of `world`, lies
/// inside `polygon_geo_set`.
fn feature_within_polygons(
    feature: &dyn GeometryTileFeature,
    canonical: &CanonicalTileID,
    world: &WorldMapping,
    polygon_geo_set: &Geometry<f64>,
) -> bool {
    let mut poly_bbox = DEFAULT_WITHIN_BBOX;
    let polygons = tile_polygons_in_world(polygon_geo_set, canonical, world, &mut poly_bbox);
    let wraps = world.wraps();
    // An empty multi-polygon contains nothing.
    if polygons.is_empty() {
        return false;
    }
    // A geometry that can't be decoded is within nothing.
    let Ok(geometries) = feature.geometries() else {
        return false;
    };
    match feature.feature_type() {
        FeatureType::Point => {
            // A point feature without a geometry is within nothing.
            let Some(first) = geometries.first() else {
                return false;
            };
            let mut point_bbox = DEFAULT_WITHIN_BBOX;
            let points = tile_points(first, canonical, wraps, &mut point_bbox, &poly_bbox);
            if !box_within_box(&point_bbox, &poly_bbox) {
                return false;
            }

            points.iter().all(|p| point_within_polygons(p, &polygons, BoundaryMode::Outside))
        }
        FeatureType::LineString => {
            let mut line_bbox = DEFAULT_WITHIN_BBOX;
            let multi_line_string = tile_lines(&geometries, canonical, wraps, &mut line_bbox, &poly_bbox);
            if !box_within_box(&line_bbox, &poly_bbox) {
                return false;
            }

            multi_line_string.iter().all(|line| line_string_within_polygons(line, &polygons))
        }
        _ => false,
    }
}

const POLYGON_REQUIRED: &str = "'within' expression requires valid geojson source that contains polygon geometry type.";

fn parse_value(value: &Convertible<'_>, ctx: &mut ParsingContext) -> Option<GeoJson> {
    if value.is_object() {
        let mut error = Error::default();
        let geojson = value.to_geojson(&mut error);
        if let Some(geojson) = geojson
            && error.message.is_empty()
        {
            return Some(geojson);
        }
        ctx.error(error.message);
    }

    ctx.error(POLYGON_REQUIRED.to_owned());
    None
}

/// The geometry of each feature of `geojson` that has one; a bare geometry
/// is one.
pub(crate) fn geojson_geometries(geojson: &GeoJson) -> Vec<&geojson::Geometry> {
    match geojson {
        GeoJson::Geometry(geometry) => vec![geometry],
        GeoJson::Feature(feature) => feature.geometry.iter().collect(),
        GeoJson::FeatureCollection(collection) => {
            collection.features.iter().filter_map(|f| f.geometry.as_ref()).collect()
        }
    }
}

/// `["within", geojson]`: whether the feature lies inside the polygons.
#[derive(Clone, PartialEq)]
pub(crate) struct Within {
    geojson_source: GeoJson,
    geometries: Geometry<f64>,
}

/// A `within` crosses as its GeoJSON, as the style writes it, and finds its
/// polygons again.
impl mln_wire::Wire for Within {
    fn write(&self, w: &mut mln_wire::Writer) {
        self.source_value().write(w);
    }

    fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
        Within::try_from(FeatureValue::read(r)?).ok().or_else(|| r.fail("invalid within GeoJSON"))
    }
}

impl TryFrom<FeatureValue> for Within {
    type Error = String;

    fn try_from(value: FeatureValue) -> Result<Self, String> {
        let mut ctx = ParsingContext::without_functions();
        parse_value(&Convertible::from(&value), &mut ctx)
            .and_then(|geojson_source| Within::from_source(geojson_source, &mut ctx))
            .ok_or_else(|| ctx.combined_errors())
    }
}

impl From<Within> for FeatureValue {
    fn from(within: Within) -> Self {
        within.source_value()
    }
}

impl Within {
    pub(crate) fn parse(value: &Convertible<'_>, ctx: &mut ParsingContext) -> ParseResult {
        // object value, quoted with ["within", value]
        if value.array_length() != 2 {
            ctx.error(format!(
                "'within' expression requires exactly one argument, but found {} instead.",
                value.array_length() - 1
            ));
            return None;
        }

        let parsed_value = parse_value(&value.array_member(1), ctx)?;
        Within::from_source(parsed_value, ctx).map(|within| Expr::new(Node::Within(Box::new(within))))
    }

    /// The `within` of a GeoJSON value: of every Polygon and `MultiPolygon` in
    /// it, skipping its other geometries. One without a Polygon or
    /// `MultiPolygon`, or with an invalid geometry, is an error.
    fn from_source(geojson_source: GeoJson, ctx: &mut ParsingContext) -> Option<Within> {
        let mut polygons = Vec::new();
        let mut found = false;
        for geometry in geojson_geometries(&geojson_source) {
            match crate::feature::geojson::geometry(geometry.clone()) {
                Ok(Geometry::Polygon(polygon)) => polygons.push(polygon),
                Ok(Geometry::MultiPolygon(multi_polygon)) => polygons.extend(multi_polygon),
                Ok(_) => continue,
                Err(e) => {
                    ctx.error(e.to_string());
                    return None;
                }
            }
            found = true;
        }
        if !found {
            ctx.error(POLYGON_REQUIRED.to_owned());
            return None;
        }
        Some(Within { geometries: Geometry::MultiPolygon(polygons.into()), geojson_source })
    }
}

impl Within {
    pub(crate) fn eval_bool(&self, params: &EvaluationContext<'_>) -> bool {
        let (Some(feature), Some(canonical)) = (params.feature, params.canonical) else {
            return false;
        };
        let geometry_type = feature.feature_type();
        // Currently only support Point and LineString types in Polygon/Polygons
        if geometry_type == FeatureType::Point || geometry_type == FeatureType::LineString {
            return feature_within_polygons(feature, canonical, params.world(), &self.geometries);
        }
        tracing::warn!(
            target: log_target::GENERAL,
            "within expression currently only support Point/LineString geometry type."
        );

        false
    }

    pub(crate) fn serialize(&self) -> FeatureValue {
        FeatureValue::Array(vec![FeatureValue::String("within".to_owned()), self.source_value()])
    }

    /// The GeoJSON, as a style value.
    fn source_value(&self) -> FeatureValue {
        crate::conversion::json_to_value(&serde_json::to_value(&self.geojson_source).unwrap_or_default())
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use super::*;
    use crate::expression::Functions;
    use crate::expression::value::Value;

    #[test]
    fn empty_feature_collection_is_a_parse_error() {
        let document = serde_json::json!(["within", {"type": "FeatureCollection", "features": []}]);
        let mut ctx = ParsingContext::new(&Functions::with_builtins());
        assert!(ctx.parse_expression(&Convertible::from(&document), None).is_none());
        assert_eq!(ctx.errors().len(), 1);
        assert_eq!(ctx.errors()[0].message, POLYGON_REQUIRED);
    }

    struct PointFeature(crate::feature::GeometryCollection);

    impl GeometryTileFeature for PointFeature {
        fn feature_type(&self) -> FeatureType {
            FeatureType::Point
        }

        fn value(&self, _key: &str) -> Option<FeatureValue> {
            None
        }

        fn geometries(&self) -> Result<Cow<'_, crate::feature::GeometryCollection>, crate::error::Error> {
            Ok(Cow::Borrowed(&self.0))
        }
    }

    /// A square around `center`, far out in tile coordinates, where the
    /// cross products of its edges overflow `i64`.
    fn far_square(half: i64, center: Point<i64>) -> Vec<Point<i64>> {
        [(-half, -half), (half, -half), (half, half), (-half, half), (-half, -half)]
            .into_iter()
            .map(|(x, y)| Point::new(center.x + x, center.y + y))
            .collect()
    }

    #[test]
    fn far_coordinates_do_not_overflow() {
        let half = 1 << 40;
        let center = Point::new(COORDINATE_LIMIT - half, -(COORDINATE_LIMIT - half));
        let polygon = vec![far_square(half, center)];
        assert!(point_within_polygon(&center, &polygon, BoundaryMode::Outside));
        let outside = Point::new(center.x - half - 1, center.y);
        assert!(!point_within_polygon(&outside, &polygon, BoundaryMode::Outside));
        let on_edge = Point::new(center.x + half, center.y + 3);
        assert!(point_within_polygon(&on_edge, &polygon, BoundaryMode::Inside));
        assert!(!point_within_polygon(&on_edge, &polygon, BoundaryMode::Outside));
        // A line from the center out of the square crosses its edge.
        assert!(!line_string_within_polygon(&[center, outside], &polygon));
        assert!(line_string_within_polygon(&[center, Point::new(center.x + 5, center.y - 7)], &polygon));
    }

    /// The edge's crossing of the point's y is compared exactly, not
    /// truncated: (1, 1) is left of the edge from (0, 0) to (3, 2), which
    /// crosses y = 1 at x = 1.5.
    #[test]
    fn ray_crossing_is_exact() {
        let (p1, p2) = (Point::new(0, 0), Point::new(3, 2));
        assert!(ray_intersect(&Point::new(1, 1), &p1, &p2));
        assert!(!ray_intersect(&Point::new(2, 1), &p1, &p2));
        assert!(ray_intersect(&Point::new(1, 1), &p2, &p1));
        assert!(!ray_intersect(&Point::new(2, 1), &p2, &p1));
    }

    /// A collection's polygons and multi-polygons all count, and its other
    /// geometries are skipped.
    #[test]
    fn within_a_collection_is_within_any_of_its_polygons() {
        // At z3, tile (4, 3) spans 0° to 45° east and 0° to about 41° north.
        let document = serde_json::json!(["within", {"type": "FeatureCollection", "features": [
            {"type": "Feature", "properties": {}, "geometry": {"type": "Polygon", "coordinates": [[[0, 0], [1, 0], [1, 1], [0, 0]]]}},
            {"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [10, 10]}},
            {"type": "Feature", "properties": {}, "geometry": null},
            {"type": "Feature", "properties": {}, "geometry": {"type": "MultiPolygon", "coordinates": [
                [[[2, 2], [3, 2], [3, 3], [2, 2]]],
                [[[30, 0], [40, 0], [40, 10], [30, 10], [30, 0]]]
            ]}}
        ]}]);
        let mut ctx = ParsingContext::new(&Functions::with_builtins());
        let within = ctx.parse_expression(&Convertible::from(&document), None).expect("parses");
        assert!(ctx.errors().is_empty(), "{:?}", ctx.errors());
        let canonical = CanonicalTileID::new(3, 4, 3);
        let is_within = |x, y| {
            let feature = PointFeature(vec![vec![Point::new(x, y)]].into());
            let params = EvaluationContext::from_feature(Some(&feature)).with_canonical_tile_id(Some(&canonical));
            within.evaluate(&params)
        };
        // 35°E 5°N, in the last polygon.
        assert_eq!(is_within(6372, 7281), Ok(Value::Bool(true)));
        // 20°E 5°N, in none.
        assert_eq!(is_within(3641, 7281), Ok(Value::Bool(false)));
    }

    /// An empty multi-polygon parses, and contains nothing.
    #[test]
    fn nothing_is_within_an_empty_multi_polygon() {
        let document = serde_json::json!(["within", {"type": "MultiPolygon", "coordinates": []}]);
        let mut ctx = ParsingContext::new(&Functions::with_builtins());
        let within = ctx.parse_expression(&Convertible::from(&document), None).expect("parses");
        let feature = PointFeature(vec![vec![Point::new(10, 10)]].into());
        let canonical = CanonicalTileID::new(3, 3, 3);
        let params = EvaluationContext::from_feature(Some(&feature)).with_canonical_tile_id(Some(&canonical));
        assert_eq!(within.evaluate(&params), Ok(Value::Bool(false)));
    }

    /// A polygon keeps its place past Mercator's latitude limit: a point on
    /// the top edge of the tile grid, about 85.05 N, is inside one that
    /// reaches 86 N, where the polygon's edge is above the grid.
    #[test]
    fn a_polygon_reaches_past_mercators_latitude_limit() {
        let document = serde_json::json!(["within", {"type": "Polygon",
            "coordinates": [[[-10, 80], [10, 80], [10, 86], [-10, 86], [-10, 80]]]}]);
        let mut ctx = ParsingContext::new(&Functions::with_builtins());
        let within = ctx.parse_expression(&Convertible::from(&document), None).expect("parses");
        let canonical = CanonicalTileID::new(0, 0, 0);
        let point = PointFeature(vec![vec![Point::new(4096, 0)]].into());
        let params = EvaluationContext::from_feature(Some(&point)).with_canonical_tile_id(Some(&canonical));
        assert_eq!(within.evaluate(&params), Ok(Value::Bool(true)));
    }

    /// A feature's tile coordinates are a place in the world square of its
    /// map's projection: in the identity's, where tile 0/0/0 spans -90 to 90
    /// on both axes, the point at 45 E, 45 N is three quarters across and a
    /// quarter down, which Web Mercator's formulas would put at 90 E, 66.5 N.
    #[test]
    fn features_are_within_in_the_world_of_their_tile() {
        let document = serde_json::json!(["within", {"type": "Polygon",
            "coordinates": [[[44, 44], [46, 44], [46, 46], [44, 46], [44, 44]]]}]);
        let mut ctx = ParsingContext::new(&Functions::with_builtins());
        let within = ctx.parse_expression(&Convertible::from(&document), None).expect("parses");
        let identity = WorldMapping::new(std::sync::Arc::new(crate::crs::Crs::identity()));
        let canonical = CanonicalTileID::new(0, 0, 0);
        let point = PointFeature(vec![vec![Point::new(6144, 2048)]].into());
        let params = EvaluationContext::from_feature(Some(&point)).with_canonical_tile_id(Some(&canonical));
        assert_eq!(within.evaluate(&params.with_world(Some(&identity))), Ok(Value::Bool(true)));
        assert_eq!(within.evaluate(&params), Ok(Value::Bool(false)));
        assert_eq!(within.evaluate(&params.with_world(Some(&WorldMapping::default()))), Ok(Value::Bool(false)));

        // A world that doesn't wrap has no copy to move a point to: one at
        // the identity's left edge, 90 W, stays there, where a world east
        // would put it at 90 E, inside the polygon.
        let document = serde_json::json!(["within", {"type": "Polygon",
            "coordinates": [[[80, -10], [100, -10], [100, 10], [80, 10], [80, -10]]]}]);
        let within = ctx.parse_expression(&Convertible::from(&document), None).expect("parses");
        let at_the_left_edge = PointFeature(vec![vec![Point::new(1, 4096)]].into());
        let params = EvaluationContext::from_feature(Some(&at_the_left_edge))
            .with_canonical_tile_id(Some(&canonical))
            .with_world(Some(&identity));
        assert_eq!(within.evaluate(&params), Ok(Value::Bool(false)));
    }
}