use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, mln_wire::Wire)]
pub struct CanonicalTileID {
pub z: u8,
pub x: u32,
pub y: u32,
}
impl CanonicalTileID {
#[must_use]
pub fn new(z: u8, x: u32, y: u32) -> Self {
debug_assert!(z <= 32);
debug_assert!(u64::from(x) < (1u64 << z));
debug_assert!(u64::from(y) < (1u64 << z));
CanonicalTileID { z, x, y }
}
#[must_use]
pub fn is_child_of(&self, parent: &CanonicalTileID) -> bool {
parent.z == 0
|| (parent.z < self.z
&& parent.x == self.x.wrapping_shr(u32::from(self.z - parent.z))
&& parent.y == self.y.wrapping_shr(u32::from(self.z - parent.z)))
}
#[must_use]
pub fn scaled_to(&self, target_z: u8) -> CanonicalTileID {
if target_z <= self.z {
let shift = (i32::from(self.z) - i32::from(target_z)) as u32;
CanonicalTileID::new(target_z, self.x.wrapping_shr(shift), self.y.wrapping_shr(shift))
} else {
let shift = (i32::from(target_z) - i32::from(self.z)) as u32;
CanonicalTileID::new(target_z, self.x.wrapping_shl(shift), self.y.wrapping_shl(shift))
}
}
#[must_use]
pub fn children(&self) -> [CanonicalTileID; 4] {
let child_z = self.z.wrapping_add(1);
let child_x = self.x.wrapping_mul(2);
let child_y = self.y.wrapping_mul(2);
[
CanonicalTileID::new(child_z, child_x, child_y),
CanonicalTileID::new(child_z, child_x, child_y.wrapping_add(1)),
CanonicalTileID::new(child_z, child_x.wrapping_add(1), child_y),
CanonicalTileID::new(child_z, child_x.wrapping_add(1), child_y.wrapping_add(1)),
]
}
}
impl fmt::Display for CanonicalTileID {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}/{}", self.z, self.x, self.y)
}
}
#[cfg(test)]
#[path = "tile_id_test.rs"]
mod tile_id_test;