bestagon 0.9.0

An engine for discrete stuff in hexagonal grids
Documentation
use crate::{HexAx, HexCb, math::Vec2};

pub trait Distance<T> {
  /// Return the grid distance from `self` to `other`.
  fn dist(&self, other: &Self) -> T;
}

// Implementations can be simplified once this lands in stable:
// https://github.com/rust-lang/rust/issues/74913

impl Distance<isize> for HexCb {
  /// ```
  /// use bestagon::{HexCb, distance::Distance};
  /// assert_eq!(HexCb::new(0, 4, -4).dist(&HexCb::new(1, 2, -3)), 2);
  /// assert_eq!(HexCb::new(-3, 2, 1).dist(&HexCb::new(3, -1, -2)), 6);
  /// assert_eq!(HexCb::new(-4, 4, 0).dist(&HexCb::new(4, -4, 0)), 8);
  /// ```
  fn dist(&self, other: &HexCb) -> isize {
    // https://www.redblobgames.com/grids/hexagons/#distances-cube
    ((other.q - self.q).abs() + (other.r - self.r).abs() + (other.s - self.s).abs()) / 2
  }
}

impl Distance<isize> for HexAx {
  /// ```
  /// use bestagon::{HexAx, distance::Distance};
  /// assert_eq!(HexAx::new(0, 4).dist(&HexAx::new(1, 2)), 2);
  /// assert_eq!(HexAx::new(-3, 2).dist(&HexAx::new(3, -1)), 6);
  /// ```
  fn dist(&self, other: &HexAx) -> isize {
    // Simply convert to HexCb and use that implementation.
    // Could be improved by manually calculating but this is easier.
    let self_c: HexCb = (*self).into();
    let other_c: HexCb = (*other).into();
    self_c.dist(&other_c)
  }
}

impl Distance<f32> for Vec2<f32> {
  fn dist(&self, other: &Self) -> f32 {
    f32::sqrt((self.x - other.x).powi(2) + (self.y - other.y).powi(2))
  }
}