map-expressions 0.1.0

Deterministic map-label selection, projection, and collision handling
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
//! Deterministic map-label selection and collision handling.
//!
//! The crate turns already-supplied geographic features into normalized screen
//! positions. It does not download map data, choose a legal data license, or
//! replace a full cartographic projection engine.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;

/// Official GSI explanation of vector-tile map expression.
pub const GSI_VECTOR_TILE_URL: &str = "https://maps.gsi.go.jp/development/vt_expt.html";

/// Official GSI Maps Vector viewer.
pub const GSI_MAPS_VECTOR_URL: &str = "https://maps.gsi.go.jp/vector/";

/// A validated WGS84-style latitude and longitude pair in degrees.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GeoPoint {
    latitude: f64,
    longitude: f64,
}

impl GeoPoint {
    /// Creates a point with latitude in `[-90, 90]` and longitude in `[-180, 180]`.
    pub fn new(latitude: f64, longitude: f64) -> Result<Self, MapError> {
        if !latitude.is_finite() || !(-90.0..=90.0).contains(&latitude) {
            return Err(MapError::InvalidLatitude);
        }
        if !longitude.is_finite() || !(-180.0..=180.0).contains(&longitude) {
            return Err(MapError::InvalidLongitude);
        }
        Ok(Self {
            latitude,
            longitude,
        })
    }

    /// Returns latitude in degrees.
    pub const fn latitude(self) -> f64 {
        self.latitude
    }

    /// Returns longitude in degrees.
    pub const fn longitude(self) -> f64 {
        self.longitude
    }
}

/// Geographic area displayed by a map, including antimeridian-wrapping areas.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Viewport {
    south: f64,
    west: f64,
    north: f64,
    east: f64,
}

impl Viewport {
    /// Creates a viewport. `west > east` represents wrapping across ±180°.
    pub fn new(south: f64, west: f64, north: f64, east: f64) -> Result<Self, MapError> {
        GeoPoint::new(south, west)?;
        GeoPoint::new(north, east)?;
        if south >= north {
            return Err(MapError::InvalidViewport);
        }
        Ok(Self {
            south,
            west,
            north,
            east,
        })
    }

    /// Returns true when the point is inside this viewport.
    pub fn contains(self, point: GeoPoint) -> bool {
        let latitude_inside = (self.south..=self.north).contains(&point.latitude);
        let longitude_inside = if self.west <= self.east {
            (self.west..=self.east).contains(&point.longitude)
        } else {
            point.longitude >= self.west || point.longitude <= self.east
        };
        latitude_inside && longitude_inside
    }

    /// Projects a contained point to normalized screen coordinates.
    pub fn project(self, point: GeoPoint) -> Option<ScreenPoint> {
        if !self.contains(point) {
            return None;
        }
        let width = if self.west <= self.east {
            self.east - self.west
        } else {
            (180.0 - self.west) + (self.east + 180.0)
        };
        let offset = if self.west <= self.east || point.longitude >= self.west {
            point.longitude - self.west
        } else {
            (180.0 - self.west) + (point.longitude + 180.0)
        };
        let x = if width == 0.0 { 0.5 } else { offset / width };
        let y = (self.north - point.latitude) / (self.north - self.south);
        Some(ScreenPoint { x, y })
    }
}

/// Normalized screen coordinate with `(0, 0)` at the top left.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScreenPoint {
    x: f64,
    y: f64,
}

impl ScreenPoint {
    /// Returns normalized horizontal position.
    pub const fn x(self) -> f64 {
        self.x
    }

    /// Returns normalized vertical position.
    pub const fn y(self) -> f64 {
        self.y
    }
}

/// Localized label text with explicit fallback.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LocalizedLabel {
    values: BTreeMap<String, String>,
}

impl LocalizedLabel {
    /// Creates an empty localized label.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds or replaces a non-blank language and label value.
    pub fn insert(
        &mut self,
        language: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<(), MapError> {
        let language = language.into();
        let value = value.into();
        if language.trim().is_empty() || value.trim().is_empty() {
            return Err(MapError::EmptyLabelValue);
        }
        self.values.insert(language, value);
        Ok(())
    }

    /// Returns requested text, then fallback text when unavailable.
    pub fn get_with_fallback(&self, requested: &str, fallback: &str) -> Option<&str> {
        self.values
            .get(requested)
            .or_else(|| self.values.get(fallback))
            .map(String::as_str)
    }
}

/// Relative importance used when labels collide.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LabelPriority {
    /// Optional background context.
    Background,
    /// Local place information.
    Local,
    /// A major landmark.
    Landmark,
    /// A transport interchange or route anchor.
    Transit,
    /// Time-sensitive safety information.
    Emergency,
}

/// A labeled geographic feature and its visible zoom interval.
#[derive(Debug, Clone, PartialEq)]
pub struct MapFeature {
    id: String,
    point: GeoPoint,
    label: LocalizedLabel,
    priority: LabelPriority,
    min_zoom: u8,
    max_zoom: u8,
}

impl MapFeature {
    /// Creates a feature visible between the inclusive zoom limits.
    pub fn new(
        id: impl Into<String>,
        point: GeoPoint,
        label: LocalizedLabel,
        priority: LabelPriority,
        min_zoom: u8,
        max_zoom: u8,
    ) -> Result<Self, MapError> {
        let id = id.into();
        if id.trim().is_empty() {
            return Err(MapError::EmptyFeatureId);
        }
        if label.values.is_empty() {
            return Err(MapError::MissingLabel);
        }
        if min_zoom > max_zoom {
            return Err(MapError::InvalidZoomRange);
        }
        Ok(Self {
            id,
            point,
            label,
            priority,
            min_zoom,
            max_zoom,
        })
    }
}

/// A label selected for display.
#[derive(Debug, Clone, PartialEq)]
pub struct PlacedLabel {
    /// Stable feature identifier.
    pub id: String,
    /// Localized visible text.
    pub text: String,
    /// Normalized display position.
    pub position: ScreenPoint,
    /// Priority used during placement.
    pub priority: LabelPriority,
}

/// Deterministic label-layout policy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MapDisplay;

impl MapDisplay {
    /// Places visible labels by priority while suppressing nearby collisions.
    ///
    /// `minimum_gap` is Euclidean distance in normalized screen coordinates and
    /// must be finite and non-negative.
    pub fn layout(
        features: &[MapFeature],
        viewport: Viewport,
        zoom: u8,
        requested_language: &str,
        fallback_language: &str,
        minimum_gap: f64,
    ) -> Result<Vec<PlacedLabel>, MapError> {
        if !minimum_gap.is_finite() || minimum_gap < 0.0 {
            return Err(MapError::InvalidMinimumGap);
        }

        let mut candidates: Vec<_> = features
            .iter()
            .filter(|feature| (feature.min_zoom..=feature.max_zoom).contains(&zoom))
            .filter_map(|feature| {
                let position = viewport.project(feature.point)?;
                let text = feature
                    .label
                    .get_with_fallback(requested_language, fallback_language)?;
                Some((feature, position, text))
            })
            .collect();
        candidates.sort_by_key(|(feature, _, _)| (Reverse(feature.priority), feature.id.as_str()));

        let mut placed: Vec<PlacedLabel> = Vec::new();
        for (feature, position, text) in candidates {
            let collides = placed.iter().any(|existing| {
                let dx = existing.position.x - position.x;
                let dy = existing.position.y - position.y;
                dx.hypot(dy) < minimum_gap
            });
            if !collides {
                placed.push(PlacedLabel {
                    id: feature.id.clone(),
                    text: text.to_owned(),
                    position,
                    priority: feature.priority,
                });
            }
        }
        Ok(placed)
    }
}

/// Invalid map-display input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MapError {
    /// Latitude was non-finite or outside `[-90, 90]`.
    InvalidLatitude,
    /// Longitude was non-finite or outside `[-180, 180]`.
    InvalidLongitude,
    /// Viewport had no positive latitude span.
    InvalidViewport,
    /// Language or label text was blank.
    EmptyLabelValue,
    /// Feature identifier was blank.
    EmptyFeatureId,
    /// Feature had no localized label.
    MissingLabel,
    /// Minimum zoom exceeded maximum zoom.
    InvalidZoomRange,
    /// Collision gap was negative or non-finite.
    InvalidMinimumGap,
}

impl fmt::Display for MapError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let message = match self {
            Self::InvalidLatitude => "latitude must be finite and within -90 to 90",
            Self::InvalidLongitude => "longitude must be finite and within -180 to 180",
            Self::InvalidViewport => "viewport must have a positive latitude span",
            Self::EmptyLabelValue => "label language and value must not be blank",
            Self::EmptyFeatureId => "feature id must not be blank",
            Self::MissingLabel => "feature must have at least one label",
            Self::InvalidZoomRange => "minimum zoom must not exceed maximum zoom",
            Self::InvalidMinimumGap => "minimum gap must be finite and non-negative",
        };
        formatter.write_str(message)
    }
}

impl Error for MapError {}

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

    fn label(text: &str) -> LocalizedLabel {
        let mut label = LocalizedLabel::new();
        label.insert("ja", text).unwrap();
        label
    }

    fn feature(id: &str, longitude: f64, priority: LabelPriority) -> MapFeature {
        MapFeature::new(
            id,
            GeoPoint::new(0.0, longitude).unwrap(),
            label(id),
            priority,
            0,
            20,
        )
        .unwrap()
    }

    #[test]
    fn invalid_coordinates_are_rejected() {
        assert_eq!(GeoPoint::new(91.0, 0.0), Err(MapError::InvalidLatitude));
        assert_eq!(
            GeoPoint::new(0.0, f64::NAN),
            Err(MapError::InvalidLongitude)
        );
    }

    #[test]
    fn antimeridian_viewport_projects_both_sides() {
        let viewport = Viewport::new(-10.0, 170.0, 10.0, -170.0).unwrap();
        let west_side = viewport
            .project(GeoPoint::new(0.0, 175.0).unwrap())
            .unwrap();
        let east_side = viewport
            .project(GeoPoint::new(0.0, -175.0).unwrap())
            .unwrap();
        assert!((west_side.x() - 0.25).abs() < 1e-12);
        assert!((east_side.x() - 0.75).abs() < 1e-12);
    }

    #[test]
    fn higher_priority_label_wins_collision() {
        let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
        let features = [
            feature("local", 0.0, LabelPriority::Local),
            feature("emergency", 0.01, LabelPriority::Emergency),
        ];
        let placed = MapDisplay::layout(&features, viewport, 10, "ja", "ja", 0.1).unwrap();
        assert_eq!(placed.len(), 1);
        assert_eq!(placed[0].id, "emergency");
    }

    #[test]
    fn zoom_and_language_filter_are_applied() {
        let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
        let mut localized = label("駅");
        localized.insert("en", "Station").unwrap();
        let feature = MapFeature::new(
            "station",
            GeoPoint::new(0.0, 0.0).unwrap(),
            localized,
            LabelPriority::Transit,
            8,
            12,
        )
        .unwrap();
        assert!(
            MapDisplay::layout(std::slice::from_ref(&feature), viewport, 7, "en", "ja", 0.0)
                .unwrap()
                .is_empty()
        );
        let placed = MapDisplay::layout(&[feature], viewport, 10, "en", "ja", 0.0).unwrap();
        assert_eq!(placed[0].text, "Station");
    }

    #[test]
    fn invalid_layout_gap_is_rejected() {
        let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
        assert_eq!(
            MapDisplay::layout(&[], viewport, 1, "ja", "ja", -0.1),
            Err(MapError::InvalidMinimumGap)
        );
    }
}