use crate::layers::Layer;
use crate::source::input::{DataSource, InputFeature};
use crate::tile::feature::PropValue;
use std::sync::Arc;
#[derive(Debug, Clone)]
pub struct ProcessedFeature {
pub id: u64,
pub geometry: Arc<geo::Geometry<f64>>,
pub layer: Layer,
pub min_zoom: u8,
pub max_zoom: u8,
pub sort_rank: i32,
pub properties: Vec<(String, PropValue)>,
}
pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
match &feature.source {
DataSource::Overture { .. } => process_overture(feature),
DataSource::Osm { .. } => process_osm(feature),
_ => None,
}
}
pub fn process_all(feature: &InputFeature) -> Vec<ProcessedFeature> {
let mut results = Vec::with_capacity(2);
if let Some(building) = process(feature) {
results.push(building);
}
if matches!(&feature.source, DataSource::Osm { .. })
&& let Some(addr) = extract_address(feature)
{
results.push(addr);
}
results
}
fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
let overture_otype = feature.overture_otype().unwrap_or("");
let kind = match overture_otype {
"building_part" => "building_part",
_ => "building",
};
let min_zoom = if kind == "building_part" { 14 } else { 11 };
let height = feature.get_f64("height");
let num_floors = feature.get_f64("num_floors");
let effective_height = height.or_else(|| num_floors.map(|f| f * 3.0));
let mut properties = Vec::with_capacity(4);
properties.push(("kind".into(), PropValue::Str(kind.into())));
if let Some(h) = effective_height {
properties.push(("height".into(), PropValue::F64(h)));
}
Some(ProcessedFeature {
id: feature.id,
geometry: feature.geometry.clone(),
layer: Layer::Buildings,
min_zoom,
max_zoom: 15,
sort_rank: 400,
properties,
})
}
fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
let has_building = feature.has_key("building");
let has_building_part = feature.has_key("building:part");
if !has_building && !has_building_part {
return None;
}
let (kind, min_zoom) = if has_building_part {
("building_part", 14u8)
} else {
("building", 11)
};
let effective_height = parse_osm_height(feature);
let mut properties = Vec::with_capacity(4);
properties.push(("kind".into(), PropValue::Str(kind.into())));
if let Some(h) = effective_height {
properties.push(("height".into(), PropValue::F64(h)));
}
if let Some(name) = feature.get_str("name") {
properties.push(("name".into(), PropValue::Str(name.to_string())));
}
Some(ProcessedFeature {
id: feature.id,
geometry: feature.geometry.clone(),
layer: Layer::Buildings,
min_zoom,
max_zoom: 15,
sort_rank: 400,
properties,
})
}
fn parse_osm_height(feature: &InputFeature) -> Option<f64> {
if let Some(height_str) = feature.get_str("height") {
let sanitized = height_str
.replace(',', ".")
.trim_end_matches(" m")
.trim()
.to_string();
if let Ok(h) = sanitized.parse::<f64>()
&& h > 0.0
{
return Some(h);
}
}
if let Some(levels_str) = feature.get_str("building:levels")
&& let Ok(levels) = levels_str.parse::<f64>()
{
let effective_levels = levels.max(1.0);
return Some(effective_levels * 3.0 + 2.0);
}
feature.get_f64("height").or_else(|| {
feature
.get_f64("building:levels")
.map(|l| l.max(1.0) * 3.0 + 2.0)
})
}
fn extract_address(feature: &InputFeature) -> Option<ProcessedFeature> {
let housenumber = feature.get_str("addr:housenumber")?;
let centroid = match feature.geometry.as_ref() {
geo::Geometry::Polygon(p) => {
use geo::Centroid;
p.centroid().map(|c| Arc::new(geo::Geometry::Point(c)))
}
geo::Geometry::MultiPolygon(mp) => {
use geo::Centroid;
mp.centroid().map(|c| Arc::new(geo::Geometry::Point(c)))
}
geo::Geometry::Point(_) => Some(feature.geometry.clone()),
_ => None,
}?;
let mut properties = Vec::with_capacity(4);
properties.push(("kind".into(), PropValue::Str("address".into())));
properties.push((
"addr_housenumber".into(),
PropValue::Str(housenumber.to_string()),
));
if let Some(street) = feature.get_str("addr:street") {
properties.push(("addr_street".into(), PropValue::Str(street.to_string())));
}
Some(ProcessedFeature {
id: feature.id,
geometry: centroid,
layer: Layer::Buildings,
min_zoom: 15,
max_zoom: 15,
sort_rank: 401,
properties,
})
}
#[must_use]
pub fn quantize_height(height: f64, zoom: u8) -> f64 {
match zoom {
0..=12 => (height / 20.0).round() * 20.0,
13 => (height / 10.0).round() * 10.0,
14 => (height / 5.0).round() * 5.0,
_ => height,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::source::input::{DataSource, OsmElementType};
use std::collections::HashMap;
fn make_feature(otype: &str, props: &[(&str, PropValue)]) -> InputFeature {
let mut properties = HashMap::new();
for (k, v) in props {
properties.insert(k.to_string(), v.clone());
}
InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(7.42, 43.73))),
properties,
bbox: None,
source: DataSource::Overture {
theme: "buildings".into(),
otype: otype.into(),
},
}
}
fn make_osm(props: &[(&str, PropValue)]) -> InputFeature {
let mut properties = HashMap::new();
for (k, v) in props {
properties.insert(k.to_string(), v.clone());
}
InputFeature {
id: 42,
geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
geo::LineString::from(vec![
(0.0, 0.0),
(0.0, 1.0),
(1.0, 1.0),
(1.0, 0.0),
(0.0, 0.0),
]),
vec![],
))),
properties,
bbox: None,
source: DataSource::Osm {
element_type: OsmElementType::Way,
relations: Vec::new(),
},
}
}
fn has_prop(p: &[(String, PropValue)], key: &str, val: &PropValue) -> bool {
p.iter().any(|(k, v)| k == key && v == val)
}
fn get_prop<'a>(p: &'a [(String, PropValue)], key: &str) -> Option<&'a PropValue> {
p.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
#[test]
fn building_has_correct_kind_and_zoom() {
for otype in ["building", "something_else"] {
let feat = make_feature(otype, &[]);
let result = process(&feat).expect(otype);
assert_eq!(result.layer, Layer::Buildings, "{otype}");
assert_eq!(result.min_zoom, 11, "{otype}");
assert_eq!(result.sort_rank, 400, "{otype}");
assert!(
has_prop(
&result.properties,
"kind",
&PropValue::Str("building".into())
),
"{otype}"
);
}
}
#[test]
fn building_part_starts_at_zoom_14() {
let feat = make_feature("building_part", &[]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 14);
assert!(has_prop(
&result.properties,
"kind",
&PropValue::Str("building_part".into())
));
}
#[test]
fn height_from_direct_attribute() {
let feat = make_feature("building", &[("height", PropValue::F64(25.0))]);
let result = process(&feat).unwrap();
assert_eq!(
get_prop(&result.properties, "height"),
Some(&PropValue::F64(25.0))
);
}
#[test]
fn height_estimated_from_floors() {
let feat = make_feature("building", &[("num_floors", PropValue::F64(5.0))]);
let result = process(&feat).unwrap();
assert_eq!(
get_prop(&result.properties, "height"),
Some(&PropValue::F64(15.0))
);
}
#[test]
fn direct_height_preferred_over_floors() {
let feat = make_feature(
"building",
&[
("height", PropValue::F64(30.0)),
("num_floors", PropValue::F64(5.0)),
],
);
let result = process(&feat).unwrap();
assert_eq!(
get_prop(&result.properties, "height"),
Some(&PropValue::F64(30.0))
);
}
#[test]
fn height_quantization() {
assert_eq!(quantize_height(17.0, 12), 20.0);
assert_eq!(quantize_height(17.0, 13), 20.0);
assert_eq!(quantize_height(17.0, 14), 15.0);
assert_eq!(quantize_height(17.0, 15), 17.0);
}
#[test]
fn quantize_low_zoom_levels() {
assert_eq!(quantize_height(50.0, 0), 60.0);
assert_eq!(quantize_height(10.0, 5), 20.0);
assert_eq!(quantize_height(9.0, 12), 0.0);
}
#[test]
fn unsupported_source_returns_none() {
let mut feat = make_feature("building", &[]);
feat.source = DataSource::LandPolygons;
assert!(process(&feat).is_none());
assert!(process_all(&feat).is_empty());
}
#[test]
fn overture_no_height_emits_no_height_prop() {
let feat = make_feature("building", &[]);
let result = process(&feat).unwrap();
assert!(get_prop(&result.properties, "height").is_none());
}
#[test]
fn osm_without_building_tag_returns_none() {
let feat = make_osm(&[("name", PropValue::Str("foo".into()))]);
assert!(process(&feat).is_none());
}
#[test]
fn osm_with_building_tag() {
let feat = make_osm(&[("building", PropValue::Str("yes".into()))]);
let r = process(&feat).unwrap();
assert_eq!(r.layer, Layer::Buildings);
assert_eq!(r.min_zoom, 11);
assert_eq!(r.max_zoom, 15);
assert_eq!(r.sort_rank, 400);
assert!(has_prop(
&r.properties,
"kind",
&PropValue::Str("building".into())
));
}
#[test]
fn osm_with_building_part_tag() {
let feat = make_osm(&[("building:part", PropValue::Str("yes".into()))]);
let r = process(&feat).unwrap();
assert_eq!(r.min_zoom, 14);
assert!(has_prop(
&r.properties,
"kind",
&PropValue::Str("building_part".into())
));
}
#[test]
fn osm_includes_name_when_present() {
let feat = make_osm(&[
("building", PropValue::Str("residential".into())),
("name", PropValue::Str("Empire State".into())),
]);
let r = process(&feat).unwrap();
assert!(has_prop(
&r.properties,
"name",
&PropValue::Str("Empire State".into())
));
}
#[test]
fn osm_omits_name_when_missing() {
let feat = make_osm(&[("building", PropValue::Str("yes".into()))]);
let r = process(&feat).unwrap();
assert!(get_prop(&r.properties, "name").is_none());
}
#[test]
fn osm_height_and_levels_resolve_to_metres() {
let s = |v: &str| PropValue::Str(v.into());
type Case = (&'static str, Vec<(&'static str, PropValue)>, Option<f64>);
let cases: [Case; 13] = [
("plain number", vec![("height", s("12.5"))], Some(12.5)),
("metre suffix", vec![("height", s("33 m"))], Some(33.0)),
("decimal comma", vec![("height", s("89,1"))], Some(89.1)),
(
"comma and suffix",
vec![("height", s("12,5 m"))],
Some(12.5),
),
(
"numeric height",
vec![("height", PropValue::F64(42.0))],
Some(42.0),
),
(
"unparseable height",
vec![("height", s("abc")), ("building:levels", s("4"))],
Some(14.0),
),
(
"empty height",
vec![("height", s("")), ("building:levels", s("2"))],
Some(8.0),
),
(
"zero height",
vec![("height", s("0")), ("building:levels", s("3"))],
Some(11.0),
),
("negative height", vec![("height", s("-5"))], None),
("zero levels", vec![("building:levels", s("0"))], Some(5.0)),
(
"numeric levels",
vec![("building:levels", PropValue::F64(5.0))],
Some(17.0),
),
(
"unparseable levels",
vec![("building:levels", s("many"))],
None,
),
("neither", vec![], None),
];
for (case, tags, expected) in cases {
let mut all = vec![("building", s("yes"))];
all.extend(tags);
let r = process(&make_osm(&all)).expect(case);
assert_eq!(
get_prop(&r.properties, "height"),
expected.map(PropValue::F64).as_ref(),
"{case}"
);
}
}
#[test]
fn osm_with_housenumber_emits_address_point() {
let feat = make_osm(&[
("building", PropValue::Str("yes".into())),
("addr:housenumber", PropValue::Str("221B".into())),
("addr:street", PropValue::Str("Baker St".into())),
]);
let results = process_all(&feat);
assert_eq!(results.len(), 2);
let addr = &results[1];
assert_eq!(addr.min_zoom, 15);
assert_eq!(addr.max_zoom, 15);
assert_eq!(addr.sort_rank, 401);
assert!(has_prop(
&addr.properties,
"kind",
&PropValue::Str("address".into())
));
assert!(has_prop(
&addr.properties,
"addr_housenumber",
&PropValue::Str("221B".into())
));
assert!(has_prop(
&addr.properties,
"addr_street",
&PropValue::Str("Baker St".into())
));
assert!(matches!(addr.geometry.as_ref(), geo::Geometry::Point(_)));
}
#[test]
fn osm_address_omits_street_when_missing() {
let feat = make_osm(&[
("building", PropValue::Str("yes".into())),
("addr:housenumber", PropValue::Str("10".into())),
]);
let results = process_all(&feat);
assert_eq!(results.len(), 2);
let address = results
.iter()
.find(|r| matches!(r.geometry.as_ref(), geo::Geometry::Point(_)))
.expect("the address point is emitted");
assert!(has_prop(
&address.properties,
"addr_housenumber",
&PropValue::Str("10".into())
));
assert!(get_prop(&address.properties, "addr_street").is_none());
}
#[test]
fn osm_address_from_multipolygon() {
let mut feat = make_osm(&[
("building", PropValue::Str("yes".into())),
("addr:housenumber", PropValue::Str("5".into())),
]);
let poly = geo::Polygon::new(
geo::LineString::from(vec![
(0.0, 0.0),
(0.0, 2.0),
(2.0, 2.0),
(2.0, 0.0),
(0.0, 0.0),
]),
vec![],
);
feat.geometry = Arc::new(geo::Geometry::MultiPolygon(geo::MultiPolygon(vec![poly])));
let results = process_all(&feat);
assert_eq!(results.len(), 2);
assert!(matches!(
results[1].geometry.as_ref(),
geo::Geometry::Point(_)
));
}
#[test]
fn osm_address_from_point_geometry() {
let mut feat = make_osm(&[
("building", PropValue::Str("yes".into())),
("addr:housenumber", PropValue::Str("7".into())),
]);
feat.geometry = Arc::new(geo::Geometry::Point(geo::Point::new(1.0, 2.0)));
let results = process_all(&feat);
assert_eq!(results.len(), 2);
assert!(matches!(
results[1].geometry.as_ref(),
geo::Geometry::Point(_)
));
}
#[test]
fn osm_address_unsupported_geometry_no_address() {
let mut feat = make_osm(&[
("building", PropValue::Str("yes".into())),
("addr:housenumber", PropValue::Str("9".into())),
]);
feat.geometry = Arc::new(geo::Geometry::LineString(geo::LineString::from(vec![
(0.0, 0.0),
(1.0, 1.0),
])));
assert_eq!(process_all(&feat).len(), 1, "a line gets no address point");
let untagged = make_osm(&[("building", PropValue::Str("yes".into()))]);
assert_eq!(
process_all(&untagged).len(),
1,
"no housenumber, no address point"
);
}
#[test]
fn overture_with_addr_housenumber_does_not_emit_address() {
let tagged = [("addr:housenumber", PropValue::Str("1".into()))];
for props in [&tagged[..], &[]] {
let results = process_all(&make_feature("building", props));
assert_eq!(results.len(), 1, "{props:?}");
}
}
}