Skip to main content

geolith_tiles_builder/layers/
water.rs

1//! Water layer — ocean, lakes, rivers.
2//!
3//! Processes features from multiple data sources:
4//! - **`WaterPolygons`** (z6+): Pre-processed ocean water polygons from shapefile
5//! - **`NaturalEarth`** (z0-5): `ne_50m_ocean`/`ne_50m_lakes` (z0-4),
6//!   `ne_10m_ocean`/`ne_10m_lakes` (z5)
7//! - **OSM**: 17+ water feature types (rivers, streams, canals, etc.)
8//! - **Overture**: `base/water` features with subtype mapping
9
10use geo::{Area, Centroid};
11use std::sync::Arc;
12
13use crate::layers::Layer;
14use crate::source::input::{DataSource, InputFeature};
15use crate::tile::feature::PropValue;
16
17use super::buildings::ProcessedFeature;
18
19/// Process a feature into a water layer feature.
20///
21/// Routes to the appropriate handler based on data source.
22pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
23    match &feature.source {
24        DataSource::Overture { .. } => process_overture(feature),
25        DataSource::WaterPolygons => process_water_polygons(feature),
26        DataSource::NaturalEarth { .. } => process_ne(feature),
27        DataSource::Osm { .. } => process_osm(feature),
28        _ => None,
29    }
30}
31
32/// Compute area-based `min_zoom` for water polygon features.
33///
34/// Mirrors Planetiler's approach: polygon area determines the zoom level
35/// at which a water feature first appears. Larger water bodies show at
36/// lower zooms, smaller ones only at higher zooms.
37///
38/// Area is in WGS84 degrees² (approximate, varies by latitude).
39/// At mid-latitudes (~20°N): 1 deg² ≈ 10,000 km².
40#[must_use]
41fn area_based_min_zoom(geometry: &geo::Geometry<f64>, kind_floor: u8) -> u8 {
42    let area = match geometry {
43        geo::Geometry::Polygon(p) => p.unsigned_area(),
44        geo::Geometry::MultiPolygon(mp) => mp.unsigned_area(),
45        // Point/LineString water features (springs, waterfalls, swimming pools)
46        // should never appear at low zoom — clamp to at least z13.
47        _ => return kind_floor.max(13),
48    };
49
50    let zoom: u8 = if area > 0.1 {
51        3 // ~1000+ km² (Great Lakes)
52    } else if area > 0.01 {
53        5 // ~100+ km² (major reservoirs)
54    } else if area > 0.001 {
55        7 // ~10+ km² (significant lakes)
56    } else if area > 0.0001 {
57        9 // ~1+ km² (medium lakes)
58    } else if area > 0.00001 {
59        11 // ~0.1+ km² (small lakes, talav)
60    } else {
61        13 // tiny ponds
62    };
63
64    zoom.max(kind_floor)
65}
66
67/// Map an Overture water `class` or `subtype` value to (kind, `min_zoom`).
68fn water_kind(value: &str) -> Option<(&'static str, u8)> {
69    Some(match value {
70        "ocean" => ("ocean", 0u8),
71        "sea" => ("sea", 3),
72        "lake" => ("lake", 6),
73        "pond" => ("pond", 10),
74        "reservoir" => ("lake", 6),
75        "river" => ("river", 9),
76        "stream" => ("stream", 13),
77        "canal" => ("canal", 10),
78        "drain" => ("drain", 15),
79        "ditch" => ("ditch", 15),
80        "reef" => ("reef", 11),
81        "swimming_pool" => ("swimming_pool", 14),
82        "fountain" => ("fountain", 14),
83        "dock" => ("dock", 12),
84        "fjord" => ("fjord", 6),
85        "strait" => ("strait", 6),
86        "bay" => ("bay", 6),
87        "basin" => ("basin", 12),
88        "playa" => ("playa", 6),
89        "spring" => ("spring", 14),
90        "waterfall" => ("waterfall", 13),
91        "hot_spring" => ("spring", 14),
92        "water_well" => ("water", 15),
93        "fishpond" => ("pond", 10),
94        "oxbow" | "lagoon" => ("lake", 6),
95        "moat" => ("canal", 10),
96        _ => return None,
97    })
98}
99
100/// Process Overture `base/water` features.
101///
102/// Classified by `class` first, then `subtype`. Overture subtypes are broad
103/// (`canal` holds ditches and drains, `human_made` holds swimming pools,
104/// `physical` holds bays and waterfalls), so a subtype-only match drew
105/// 651k ditches as z10 canals and lost pools, bays, and waterfalls.
106fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
107    let (kind, base_min_zoom) = feature
108        .get_str("class")
109        .and_then(water_kind)
110        .or_else(|| feature.get_str("subtype").and_then(water_kind))
111        .unwrap_or(("water", 6));
112
113    // Adjust min_zoom based on polygon area for lake-type features.
114    // Small lakes/reservoirs get higher min_zoom so they only appear when
115    // zoomed in enough (mirrors Planetiler's area-based zoom assignment).
116    let min_zoom = match kind {
117        "lake" | "pond" | "basin" | "playa" | "water" => {
118            area_based_min_zoom(feature.geometry.as_ref(), base_min_zoom)
119        }
120        _ => base_min_zoom,
121    };
122
123    let mut properties = Vec::with_capacity(3);
124    properties.push(("kind".into(), PropValue::Str(kind.into())));
125
126    if let Some(name) = feature.get_str("names.primary").or(feature.get_str("name")) {
127        properties.push(("name".into(), PropValue::Str(name.to_string())));
128    }
129
130    if let Some(detail) = feature.get_str("class") {
131        properties.push(("kind_detail".into(), PropValue::Str(detail.to_string())));
132    }
133
134    Some(ProcessedFeature {
135        id: feature.id,
136        geometry: feature.geometry.clone(),
137        layer: Layer::Water,
138        min_zoom,
139        max_zoom: 15,
140        sort_rank: 200,
141        properties,
142    })
143}
144
145/// Process pre-processed water polygons (z6+).
146///
147/// These are the `water-polygons-split-3857` polygons reprojected to WGS84.
148fn process_water_polygons(feature: &InputFeature) -> Option<ProcessedFeature> {
149    let properties = vec![("kind".into(), PropValue::Str("ocean".into()))];
150
151    Some(ProcessedFeature {
152        id: feature.id,
153        geometry: feature.geometry.clone(),
154        layer: Layer::Water,
155        min_zoom: 6,
156        max_zoom: 15,
157        sort_rank: 200,
158        properties,
159    })
160}
161
162/// Process Natural Earth ocean/lake features (z0-5).
163///
164/// - `ne_50m_ocean` / `ne_50m_lakes` → z0-4
165/// - `ne_10m_ocean` / `ne_10m_lakes` → z5
166fn process_ne(feature: &InputFeature) -> Option<ProcessedFeature> {
167    let source_layer = feature.ne_source_layer()?;
168
169    let (kind, min_zoom, max_zoom) = match source_layer {
170        "ne_50m_ocean" => ("ocean", 0u8, 4u8),
171        "ne_50m_lakes" => ("lake", 0, 4),
172        "ne_10m_ocean" => ("ocean", 5, 5),
173        "ne_10m_lakes" => ("lake", 5, 5),
174        _ => return None,
175    };
176
177    // Map NE featurecla to kind for lakes
178    let resolved_kind = if kind == "lake" {
179        match feature.get_str("featurecla") {
180            Some("Playa") => "playa",
181            Some("Reservoir") => "lake",
182            Some("Alkaline Lake") => "lake",
183            _ => "lake",
184        }
185    } else {
186        kind
187    };
188
189    let mut properties = Vec::with_capacity(2);
190    properties.push(("kind".into(), PropValue::Str(resolved_kind.into())));
191
192    if let Some(name) = feature.get_str("name") {
193        properties.push(("name".into(), PropValue::Str(name.to_string())));
194    }
195
196    Some(ProcessedFeature {
197        id: feature.id,
198        geometry: feature.geometry.clone(),
199        layer: Layer::Water,
200        min_zoom,
201        max_zoom,
202        sort_rank: 200,
203        properties,
204    })
205}
206
207/// Process OSM water features.
208///
209/// Handles 20+ water types including rivers, streams, canals, natural=water,
210/// springs, waterfalls, swimming pools, reservoirs, basins, and named polygon
211/// centroid labels.
212fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
213    // Check waterway tag first (linear features)
214    if let Some(waterway) = feature.get_str("waterway") {
215        return process_osm_waterway(feature, waterway);
216    }
217
218    // natural=water (polygon features)
219    if feature.has_tag("natural", "water") {
220        let water_type = feature.get_str("water").unwrap_or("");
221        let (kind, min_zoom) = match water_type {
222            "river" | "riverbank" => ("river", 9u8),
223            "lake" => ("lake", 6),
224            "reservoir" => ("lake", 6),
225            "pond" => ("pond", 10),
226            "basin" => ("basin", 12),
227            "canal" => ("canal", 10),
228            "stream" => ("stream", 13),
229            _ => ("water", 6),
230        };
231        return emit_water_feature(feature, kind, min_zoom, true);
232    }
233
234    // natural=spring (point features — water sources)
235    if feature.has_tag("natural", "spring") || feature.has_tag("natural", "hot_spring") {
236        return emit_water_feature(feature, "spring", 14, false);
237    }
238
239    // natural=waterfall
240    if feature.has_tag("natural", "waterfall") || feature.has_tag("waterway", "waterfall") {
241        return emit_water_feature(feature, "waterfall", 13, false);
242    }
243
244    // natural=reef
245    if feature.has_tag("natural", "reef") {
246        return emit_water_feature(feature, "reef", 11, false);
247    }
248
249    // leisure=swimming_pool
250    if feature.has_tag("leisure", "swimming_pool") {
251        return emit_water_feature(feature, "swimming_pool", 14, false);
252    }
253
254    // landuse=reservoir or landuse=basin
255    if feature.has_tag("landuse", "reservoir") {
256        return emit_water_feature(feature, "lake", 6, true);
257    }
258    if feature.has_tag("landuse", "basin") {
259        return emit_water_feature(feature, "basin", 12, false);
260    }
261
262    // natural=bay, natural=fjord, natural=strait
263    if feature.has_tag("natural", "bay") {
264        return emit_water_feature(feature, "bay", 6, true);
265    }
266    if feature.has_tag("natural", "fjord") {
267        return emit_water_feature(feature, "fjord", 6, true);
268    }
269    if feature.has_tag("natural", "strait") {
270        return emit_water_feature(feature, "strait", 6, true);
271    }
272
273    // amenity=fountain
274    if feature.has_tag("amenity", "fountain") {
275        return emit_water_feature(feature, "fountain", 14, false);
276    }
277
278    // waterway=dock or waterway=boatyard
279    if feature.has_tag("waterway", "dock") || feature.has_tag("waterway", "boatyard") {
280        return emit_water_feature(feature, "dock", 12, false);
281    }
282
283    // natural=sea
284    if feature.has_tag("natural", "sea") {
285        return emit_water_feature(feature, "sea", 3, true);
286    }
287
288    // place=ocean
289    if feature.has_tag("place", "ocean") {
290        return emit_water_feature(feature, "ocean", 0, true);
291    }
292
293    None
294}
295
296/// Process OSM waterway tags (linear features).
297fn process_osm_waterway(feature: &InputFeature, waterway: &str) -> Option<ProcessedFeature> {
298    let (kind, base_zoom) = match waterway {
299        "river" => ("river", 9u8),
300        "stream" => ("stream", 13),
301        "canal" => ("canal", 10),
302        "drain" => ("drain", 15),
303        "ditch" => ("ditch", 15),
304        "riverbank" => ("river", 6),
305        _ => return None,
306    };
307
308    // Lines get min_zoom = base + 1 per spec (except riverbank which is polygon)
309    let min_zoom = if feature.can_be_line() && !feature.can_be_polygon() {
310        base_zoom.saturating_add(1)
311    } else {
312        base_zoom
313    };
314
315    emit_water_feature(feature, kind, min_zoom, false)
316}
317
318/// Emit a water feature, optionally generating a centroid label
319/// for named polygons.
320fn emit_water_feature(
321    feature: &InputFeature,
322    kind: &str,
323    min_zoom: u8,
324    generate_label: bool,
325) -> Option<ProcessedFeature> {
326    let mut properties = Vec::with_capacity(3);
327
328    // For polygon lake-type features, adjust min_zoom based on area.
329    let min_zoom = match kind {
330        "lake" | "pond" | "basin" | "water" => {
331            area_based_min_zoom(feature.geometry.as_ref(), min_zoom)
332        }
333        _ => min_zoom,
334    };
335    properties.push(("kind".into(), PropValue::Str(kind.into())));
336
337    if let Some(name) = feature.get_str("name") {
338        properties.push(("name".into(), PropValue::Str(name.to_string())));
339    }
340
341    // For named polygon water features, generate centroid label instead
342    if generate_label && feature.has_key("name") && feature.can_be_polygon() {
343        let label_geom = match feature.geometry.as_ref() {
344            geo::Geometry::Polygon(p) => p.centroid().map(|c| Arc::new(geo::Geometry::Point(c))),
345            geo::Geometry::MultiPolygon(mp) => {
346                mp.centroid().map(|c| Arc::new(geo::Geometry::Point(c)))
347            }
348            _ => None,
349        };
350
351        if let Some(geom) = label_geom {
352            return Some(ProcessedFeature {
353                id: feature.id,
354                geometry: geom,
355                layer: Layer::Water,
356                min_zoom,
357                max_zoom: 15,
358                sort_rank: 200,
359                properties,
360            });
361        }
362    }
363
364    Some(ProcessedFeature {
365        id: feature.id,
366        geometry: feature.geometry.clone(),
367        layer: Layer::Water,
368        min_zoom,
369        max_zoom: 15,
370        sort_rank: 200,
371        properties,
372    })
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use crate::source::input::{DataSource, OsmElementType};
379    use std::collections::HashMap;
380
381    fn small_poly() -> Arc<geo::Geometry<f64>> {
382        Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
383            geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]),
384            vec![],
385        )))
386    }
387
388    fn big_poly() -> Arc<geo::Geometry<f64>> {
389        Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
390            geo::LineString::from(vec![
391                (0.0, 0.0),
392                (10.0, 0.0),
393                (10.0, 10.0),
394                (0.0, 10.0),
395                (0.0, 0.0),
396            ]),
397            vec![],
398        )))
399    }
400
401    fn tiny_poly() -> Arc<geo::Geometry<f64>> {
402        Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
403            geo::LineString::from(vec![(0.0, 0.0), (0.001, 0.0), (0.001, 0.001), (0.0, 0.0)]),
404            vec![],
405        )))
406    }
407
408    fn multipoly() -> Arc<geo::Geometry<f64>> {
409        Arc::new(geo::Geometry::MultiPolygon(geo::MultiPolygon(vec![
410            geo::Polygon::new(
411                geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]),
412                vec![],
413            ),
414        ])))
415    }
416
417    fn line() -> Arc<geo::Geometry<f64>> {
418        Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
419            (0.0, 0.0),
420            (1.0, 1.0),
421        ])))
422    }
423
424    fn point() -> Arc<geo::Geometry<f64>> {
425        Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0)))
426    }
427
428    fn make_with(
429        props: &[(&str, PropValue)],
430        geom: Arc<geo::Geometry<f64>>,
431        source: DataSource,
432    ) -> InputFeature {
433        let mut properties = HashMap::new();
434        for (k, v) in props {
435            properties.insert(k.to_string(), v.clone());
436        }
437        InputFeature {
438            id: 1,
439            geometry: geom,
440            properties,
441            bbox: None,
442            source,
443        }
444    }
445
446    fn make_feature(props: &[(&str, PropValue)]) -> InputFeature {
447        make_with(props, small_poly(), overture_src())
448    }
449
450    fn overture_src() -> DataSource {
451        DataSource::Overture {
452            theme: String::new(),
453            otype: String::new(),
454        }
455    }
456
457    fn osm_src() -> DataSource {
458        DataSource::Osm {
459            element_type: OsmElementType::Way,
460            relations: vec![],
461        }
462    }
463
464    fn ne_src(layer: &str) -> DataSource {
465        DataSource::NaturalEarth {
466            source_layer: layer.to_string(),
467        }
468    }
469
470    fn has_kind(feat: &ProcessedFeature, k: &str) -> bool {
471        feat.properties
472            .iter()
473            .any(|(key, v)| key == "kind" && *v == PropValue::Str(k.into()))
474    }
475
476    #[test]
477    fn ocean_z0() {
478        let feat = make_feature(&[("subtype", PropValue::Str("ocean".into()))]);
479        let r = process(&feat).unwrap();
480        assert_eq!(r.layer, Layer::Water);
481        assert_eq!(r.min_zoom, 0);
482        assert!(has_kind(&r, "ocean"));
483    }
484
485    #[test]
486    fn lake_z6() {
487        let feat = make_feature(&[("subtype", PropValue::Str("lake".into()))]);
488        assert_eq!(process(&feat).unwrap().min_zoom, 6);
489    }
490
491    #[test]
492    fn river_z9() {
493        let feat = make_feature(&[("subtype", PropValue::Str("river".into()))]);
494        let r = process(&feat).unwrap();
495        assert_eq!(r.min_zoom, 9);
496        assert!(has_kind(&r, "river"));
497    }
498
499    #[test]
500    fn stream_z13() {
501        let feat = make_feature(&[("subtype", PropValue::Str("stream".into()))]);
502        assert_eq!(process(&feat).unwrap().min_zoom, 13);
503    }
504
505    #[test]
506    fn default_water_z6() {
507        let feat = make_feature(&[]);
508        let r = process(&feat).unwrap();
509        assert_eq!(r.min_zoom, 6);
510        assert_eq!(r.sort_rank, 200);
511    }
512
513    #[test]
514    fn overture_all_subtypes() {
515        let cases = [
516            ("sea", 3u8),
517            ("pond", 10),
518            ("reservoir", 6),
519            ("canal", 10),
520            ("drain", 15),
521            ("ditch", 15),
522            ("reef", 11),
523            ("swimming_pool", 14),
524            ("fountain", 14),
525            ("dock", 12),
526            ("fjord", 6),
527            ("strait", 6),
528            ("bay", 6),
529            ("playa", 6),
530            ("spring", 14),
531            ("waterfall", 13),
532            ("hot_spring", 14),
533            ("water_well", 15),
534        ];
535        for (sub, _expected_min) in cases {
536            let feat = make_feature(&[("subtype", PropValue::Str(sub.into()))]);
537            let r = process(&feat).unwrap();
538            assert!(r.min_zoom >= 3 || sub == "ocean");
539        }
540    }
541
542    #[test]
543    fn overture_basin_uses_area() {
544        let feat = make_with(
545            &[("subtype", PropValue::Str("basin".into()))],
546            tiny_poly(),
547            overture_src(),
548        );
549        let r = process(&feat).unwrap();
550        assert!(r.min_zoom >= 12);
551    }
552
553    #[test]
554    fn overture_with_name_and_class() {
555        let feat = make_feature(&[
556            ("subtype", PropValue::Str("lake".into())),
557            ("names.primary", PropValue::Str("Tahoe".into())),
558            ("class", PropValue::Str("alpine".into())),
559        ]);
560        let r = process(&feat).unwrap();
561        assert!(
562            r.properties
563                .iter()
564                .any(|(k, v)| k == "name" && *v == PropValue::Str("Tahoe".into()))
565        );
566        assert!(
567            r.properties
568                .iter()
569                .any(|(k, v)| k == "kind_detail" && *v == PropValue::Str("alpine".into()))
570        );
571    }
572
573    #[test]
574    fn overture_falls_back_to_name_property() {
575        let feat = make_feature(&[
576            ("subtype", PropValue::Str("river".into())),
577            ("name", PropValue::Str("Nile".into())),
578        ]);
579        let r = process(&feat).unwrap();
580        assert!(
581            r.properties
582                .iter()
583                .any(|(k, v)| k == "name" && *v == PropValue::Str("Nile".into()))
584        );
585    }
586
587    /// (subtype, class) pairs from the 2026-08-19.0 release: the class, not
588    /// the broad subtype, decides the kind.
589    #[test]
590    fn overture_class_decides_over_subtype() {
591        let cases = [
592            ("canal", "ditch", "ditch", 15),
593            ("canal", "drain", "drain", 15),
594            ("canal", "moat", "canal", 10),
595            ("human_made", "swimming_pool", "swimming_pool", 14),
596            ("physical", "waterfall", "waterfall", 13),
597            ("spring", "hot_spring", "spring", 14),
598        ];
599        for (subtype, class, kind, zoom) in cases {
600            let feat = make_with(
601                &[
602                    ("subtype", PropValue::Str(subtype.into())),
603                    ("class", PropValue::Str(class.into())),
604                ],
605                Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
606                    (0.0, 0.0),
607                    (1.0, 1.0),
608                ]))),
609                overture_src(),
610            );
611            let r = process(&feat).unwrap();
612            assert!(has_kind(&r, kind), "{subtype}/{class}");
613            assert_eq!(r.min_zoom, zoom, "{subtype}/{class}");
614        }
615    }
616
617    #[test]
618    fn overture_bay_and_lagoon_classes() {
619        for (subtype, class, kind) in [
620            ("physical", "bay", "bay"),
621            ("lake", "lagoon", "lake"),
622            ("pond", "fishpond", "pond"),
623        ] {
624            let feat = make_feature(&[
625                ("subtype", PropValue::Str(subtype.into())),
626                ("class", PropValue::Str(class.into())),
627            ]);
628            assert!(
629                has_kind(&process(&feat).unwrap(), kind),
630                "{subtype}/{class}"
631            );
632        }
633    }
634
635    #[test]
636    fn overture_unknown_subtype() {
637        let feat = make_feature(&[("subtype", PropValue::Str("mystery".into()))]);
638        let r = process(&feat).unwrap();
639        assert!(has_kind(&r, "water"));
640    }
641
642    #[test]
643    fn water_polygons_z6() {
644        let feat = make_with(&[], small_poly(), DataSource::WaterPolygons);
645        let r = process(&feat).unwrap();
646        assert_eq!(r.min_zoom, 6);
647        assert!(has_kind(&r, "ocean"));
648    }
649
650    #[test]
651    fn ne_50m_ocean() {
652        let feat = make_with(&[], small_poly(), ne_src("ne_50m_ocean"));
653        let r = process(&feat).unwrap();
654        assert_eq!(r.min_zoom, 0);
655        assert_eq!(r.max_zoom, 4);
656        assert!(has_kind(&r, "ocean"));
657    }
658
659    #[test]
660    fn ne_50m_lakes() {
661        let feat = make_with(&[], small_poly(), ne_src("ne_50m_lakes"));
662        let r = process(&feat).unwrap();
663        assert_eq!(r.min_zoom, 0);
664        assert!(has_kind(&r, "lake"));
665    }
666
667    #[test]
668    fn ne_10m_ocean_z5() {
669        let feat = make_with(&[], small_poly(), ne_src("ne_10m_ocean"));
670        let r = process(&feat).unwrap();
671        assert_eq!(r.min_zoom, 5);
672        assert_eq!(r.max_zoom, 5);
673    }
674
675    #[test]
676    fn ne_10m_lakes_z5() {
677        let feat = make_with(&[], small_poly(), ne_src("ne_10m_lakes"));
678        assert_eq!(process(&feat).unwrap().min_zoom, 5);
679    }
680
681    #[test]
682    fn ne_lake_featurecla_playa() {
683        let feat = make_with(
684            &[("featurecla", PropValue::Str("Playa".into()))],
685            small_poly(),
686            ne_src("ne_50m_lakes"),
687        );
688        let r = process(&feat).unwrap();
689        assert!(has_kind(&r, "playa"));
690    }
691
692    #[test]
693    fn ne_lake_featurecla_reservoir() {
694        let feat = make_with(
695            &[("featurecla", PropValue::Str("Reservoir".into()))],
696            small_poly(),
697            ne_src("ne_50m_lakes"),
698        );
699        let r = process(&feat).unwrap();
700        assert!(has_kind(&r, "lake"));
701    }
702
703    #[test]
704    fn ne_lake_featurecla_alkaline() {
705        let feat = make_with(
706            &[("featurecla", PropValue::Str("Alkaline Lake".into()))],
707            small_poly(),
708            ne_src("ne_50m_lakes"),
709        );
710        assert!(has_kind(&process(&feat).unwrap(), "lake"));
711    }
712
713    #[test]
714    fn ne_with_name() {
715        let feat = make_with(
716            &[("name", PropValue::Str("Lake X".into()))],
717            small_poly(),
718            ne_src("ne_50m_lakes"),
719        );
720        let r = process(&feat).unwrap();
721        assert!(
722            r.properties
723                .iter()
724                .any(|(k, v)| k == "name" && *v == PropValue::Str("Lake X".into()))
725        );
726    }
727
728    #[test]
729    fn ne_unknown_layer() {
730        let feat = make_with(&[], small_poly(), ne_src("ne_50m_admin"));
731        assert!(process(&feat).is_none());
732    }
733
734    #[test]
735    fn osm_waterway_river_line_bumps_zoom() {
736        let feat = make_with(
737            &[("waterway", PropValue::Str("river".into()))],
738            line(),
739            osm_src(),
740        );
741        let r = process(&feat).unwrap();
742        assert_eq!(r.min_zoom, 10);
743        assert!(has_kind(&r, "river"));
744    }
745
746    #[test]
747    fn osm_waterway_stream() {
748        let feat = make_with(
749            &[("waterway", PropValue::Str("stream".into()))],
750            line(),
751            osm_src(),
752        );
753        assert_eq!(process(&feat).unwrap().min_zoom, 14);
754    }
755
756    #[test]
757    fn osm_waterway_canal() {
758        let feat = make_with(
759            &[("waterway", PropValue::Str("canal".into()))],
760            line(),
761            osm_src(),
762        );
763        let r = process(&feat).unwrap();
764        assert_eq!(r.min_zoom, 11);
765        assert!(has_kind(&r, "canal"));
766    }
767
768    #[test]
769    fn osm_waterway_drain() {
770        let feat = make_with(
771            &[("waterway", PropValue::Str("drain".into()))],
772            line(),
773            osm_src(),
774        );
775        let r = process(&feat).unwrap();
776        assert!(r.min_zoom >= 15);
777        assert!(has_kind(&r, "drain"));
778    }
779
780    #[test]
781    fn osm_waterway_ditch() {
782        let feat = make_with(
783            &[("waterway", PropValue::Str("ditch".into()))],
784            line(),
785            osm_src(),
786        );
787        assert!(has_kind(&process(&feat).unwrap(), "ditch"));
788    }
789
790    #[test]
791    fn osm_waterway_riverbank_polygon() {
792        let feat = make_with(
793            &[("waterway", PropValue::Str("riverbank".into()))],
794            small_poly(),
795            osm_src(),
796        );
797        let r = process(&feat).unwrap();
798        assert_eq!(r.min_zoom, 6);
799        assert!(has_kind(&r, "river"));
800    }
801
802    #[test]
803    fn osm_waterway_unknown() {
804        let feat = make_with(
805            &[("waterway", PropValue::Str("unknown".into()))],
806            line(),
807            osm_src(),
808        );
809        assert!(process(&feat).is_none());
810    }
811
812    #[test]
813    fn osm_natural_water_default() {
814        let feat = make_with(
815            &[("natural", PropValue::Str("water".into()))],
816            small_poly(),
817            osm_src(),
818        );
819        let r = process(&feat).unwrap();
820        assert!(has_kind(&r, "water"));
821    }
822
823    #[test]
824    fn osm_natural_water_river() {
825        let feat = make_with(
826            &[
827                ("natural", PropValue::Str("water".into())),
828                ("water", PropValue::Str("river".into())),
829            ],
830            small_poly(),
831            osm_src(),
832        );
833        let r = process(&feat).unwrap();
834        assert!(has_kind(&r, "river"));
835        assert_eq!(r.min_zoom, 9);
836    }
837
838    #[test]
839    fn osm_natural_water_lake_with_name_emits_label() {
840        let feat = make_with(
841            &[
842                ("natural", PropValue::Str("water".into())),
843                ("water", PropValue::Str("lake".into())),
844                ("name", PropValue::Str("L".into())),
845            ],
846            small_poly(),
847            osm_src(),
848        );
849        let r = process(&feat).unwrap();
850        assert!(matches!(r.geometry.as_ref(), geo::Geometry::Point(_)));
851    }
852
853    #[test]
854    fn osm_natural_water_lake_multipolygon_label() {
855        let feat = make_with(
856            &[
857                ("natural", PropValue::Str("water".into())),
858                ("water", PropValue::Str("lake".into())),
859                ("name", PropValue::Str("L".into())),
860            ],
861            multipoly(),
862            osm_src(),
863        );
864        let r = process(&feat).unwrap();
865        assert!(matches!(r.geometry.as_ref(), geo::Geometry::Point(_)));
866    }
867
868    #[test]
869    fn osm_natural_water_lake_no_name_keeps_polygon() {
870        let feat = make_with(
871            &[
872                ("natural", PropValue::Str("water".into())),
873                ("water", PropValue::Str("lake".into())),
874            ],
875            small_poly(),
876            osm_src(),
877        );
878        let r = process(&feat).unwrap();
879        assert!(matches!(r.geometry.as_ref(), geo::Geometry::Polygon(_)));
880    }
881
882    #[test]
883    fn osm_natural_water_kinds() {
884        for (water, kind) in [
885            ("riverbank", "river"),
886            ("reservoir", "lake"),
887            ("pond", "pond"),
888            ("basin", "basin"),
889            ("canal", "canal"),
890            ("stream", "stream"),
891        ] {
892            let feat = make_with(
893                &[
894                    ("natural", PropValue::Str("water".into())),
895                    ("water", PropValue::Str(water.into())),
896                ],
897                small_poly(),
898                osm_src(),
899            );
900            assert!(has_kind(&process(&feat).unwrap(), kind), "{water}");
901        }
902    }
903
904    #[test]
905    fn osm_spring() {
906        let feat = make_with(
907            &[("natural", PropValue::Str("spring".into()))],
908            point(),
909            osm_src(),
910        );
911        let r = process(&feat).unwrap();
912        assert!(has_kind(&r, "spring"));
913        assert_eq!(r.min_zoom, 14);
914    }
915
916    #[test]
917    fn osm_hot_spring() {
918        let feat = make_with(
919            &[("natural", PropValue::Str("hot_spring".into()))],
920            point(),
921            osm_src(),
922        );
923        assert!(has_kind(&process(&feat).unwrap(), "spring"));
924    }
925
926    #[test]
927    fn osm_natural_waterfall() {
928        let feat = make_with(
929            &[("natural", PropValue::Str("waterfall".into()))],
930            point(),
931            osm_src(),
932        );
933        let r = process(&feat).unwrap();
934        assert_eq!(r.min_zoom, 13);
935        assert!(has_kind(&r, "waterfall"));
936    }
937
938    #[test]
939    fn osm_reef() {
940        let feat = make_with(
941            &[("natural", PropValue::Str("reef".into()))],
942            small_poly(),
943            osm_src(),
944        );
945        assert!(has_kind(&process(&feat).unwrap(), "reef"));
946    }
947
948    #[test]
949    fn osm_swimming_pool() {
950        let feat = make_with(
951            &[("leisure", PropValue::Str("swimming_pool".into()))],
952            small_poly(),
953            osm_src(),
954        );
955        let r = process(&feat).unwrap();
956        assert_eq!(r.min_zoom, 14);
957        assert!(has_kind(&r, "swimming_pool"));
958    }
959
960    #[test]
961    fn osm_landuse_reservoir_emits_lake_label() {
962        let feat = make_with(
963            &[
964                ("landuse", PropValue::Str("reservoir".into())),
965                ("name", PropValue::Str("R".into())),
966            ],
967            small_poly(),
968            osm_src(),
969        );
970        let r = process(&feat).unwrap();
971        assert!(has_kind(&r, "lake"));
972        assert!(matches!(r.geometry.as_ref(), geo::Geometry::Point(_)));
973    }
974
975    #[test]
976    fn osm_landuse_basin() {
977        let feat = make_with(
978            &[("landuse", PropValue::Str("basin".into()))],
979            small_poly(),
980            osm_src(),
981        );
982        let r = process(&feat).unwrap();
983        assert!(has_kind(&r, "basin"));
984    }
985
986    #[test]
987    fn osm_natural_bay_fjord_strait() {
988        for nat in ["bay", "fjord", "strait"] {
989            let feat = make_with(
990                &[("natural", PropValue::Str(nat.into()))],
991                small_poly(),
992                osm_src(),
993            );
994            assert!(has_kind(&process(&feat).unwrap(), nat));
995        }
996    }
997
998    #[test]
999    fn osm_amenity_fountain() {
1000        let feat = make_with(
1001            &[("amenity", PropValue::Str("fountain".into()))],
1002            point(),
1003            osm_src(),
1004        );
1005        assert!(has_kind(&process(&feat).unwrap(), "fountain"));
1006    }
1007
1008    #[test]
1009    fn osm_natural_sea() {
1010        let feat = make_with(
1011            &[("natural", PropValue::Str("sea".into()))],
1012            small_poly(),
1013            osm_src(),
1014        );
1015        let r = process(&feat).unwrap();
1016        assert_eq!(r.min_zoom, 3);
1017        assert!(has_kind(&r, "sea"));
1018    }
1019
1020    #[test]
1021    fn osm_place_ocean() {
1022        let feat = make_with(
1023            &[("place", PropValue::Str("ocean".into()))],
1024            small_poly(),
1025            osm_src(),
1026        );
1027        let r = process(&feat).unwrap();
1028        assert_eq!(r.min_zoom, 0);
1029        assert!(has_kind(&r, "ocean"));
1030    }
1031
1032    #[test]
1033    fn osm_unrelated_returns_none() {
1034        let feat = make_with(
1035            &[("highway", PropValue::Str("primary".into()))],
1036            line(),
1037            osm_src(),
1038        );
1039        assert!(process(&feat).is_none());
1040    }
1041
1042    #[test]
1043    fn other_source_returns_none() {
1044        let feat = make_with(&[], small_poly(), DataSource::IndiaBoundary);
1045        assert!(process(&feat).is_none());
1046        let feat = make_with(&[], small_poly(), DataSource::LandPolygons);
1047        assert!(process(&feat).is_none());
1048    }
1049
1050    #[test]
1051    fn area_zoom_huge_polygon() {
1052        let g = big_poly();
1053        assert_eq!(area_based_min_zoom(g.as_ref(), 0), 3);
1054    }
1055
1056    #[test]
1057    fn area_zoom_multipolygon() {
1058        let g = multipoly();
1059        let z = area_based_min_zoom(g.as_ref(), 0);
1060        assert!(z >= 3);
1061    }
1062
1063    #[test]
1064    fn area_zoom_point_clamps_to_13() {
1065        let g = point();
1066        assert_eq!(area_based_min_zoom(g.as_ref(), 0), 13);
1067        assert_eq!(area_based_min_zoom(g.as_ref(), 14), 14);
1068    }
1069
1070    #[test]
1071    fn area_zoom_respects_floor() {
1072        let g = big_poly();
1073        assert_eq!(area_based_min_zoom(g.as_ref(), 8), 8);
1074    }
1075
1076    #[test]
1077    fn area_zoom_tiers() {
1078        // Build polygons with specific areas to hit each tier.
1079        let mk = |side: f64| {
1080            geo::Geometry::Polygon(geo::Polygon::new(
1081                geo::LineString::from(vec![
1082                    (0.0, 0.0),
1083                    (side, 0.0),
1084                    (side, side),
1085                    (0.0, side),
1086                    (0.0, 0.0),
1087                ]),
1088                vec![],
1089            ))
1090        };
1091        // area > 0.01: side ≈ 0.2 → area = 0.04
1092        assert_eq!(area_based_min_zoom(&mk(0.2), 0), 5);
1093        // area > 0.001: side ≈ 0.05 → area = 0.0025
1094        assert_eq!(area_based_min_zoom(&mk(0.05), 0), 7);
1095        // area > 0.0001: side ≈ 0.015 → area ≈ 0.000225
1096        assert_eq!(area_based_min_zoom(&mk(0.015), 0), 9);
1097        // area > 0.00001: side ≈ 0.005 → area ≈ 0.000025
1098        assert_eq!(area_based_min_zoom(&mk(0.005), 0), 11);
1099        // tiny: side = 0.001 → area = 0.000001
1100        assert_eq!(area_based_min_zoom(&mk(0.001), 0), 13);
1101    }
1102}