This repository has no description
1#[cfg(feature = "web")]
2use wasm_bindgen::prelude::*;
3
4use crate::Region;
5
6use super::Angle;
7
8#[cfg_attr(feature = "web", wasm_bindgen)]
9#[derive(Debug, Clone, Copy, Default, PartialEq)]
10pub struct Point(pub usize, pub usize);
11
12impl Point {
13 pub fn translated(&self, dx: i32, dy: i32) -> Self {
14 Self((self.0 as i32 + dx) as usize, (self.1 as i32 + dy) as usize)
15 }
16
17 pub fn translated_by(&self, point: Point) -> Self {
18 Self(self.0 + point.0, self.1 + point.1)
19 }
20
21 pub fn region(&self) -> Region {
22 Region {
23 start: *self,
24 end: *self,
25 }
26 }
27
28 pub fn translate(&mut self, dx: i32, dy: i32) {
29 self.0 = (self.0 as i32 + dx) as usize;
30 self.1 = (self.1 as i32 + dy) as usize;
31 }
32
33 pub fn coords(&self, cell_size: usize) -> (f32, f32) {
34 ((self.0 * cell_size) as f32, (self.1 * cell_size) as f32)
35 }
36
37 /// get SVG coordinates of the cell's center instead of its origin (top-left)
38 pub fn center_coords(&self, cell_size: usize) -> (f32, f32) {
39 let (x, y) = self.coords(cell_size);
40 (x + cell_size as f32 / 2.0, y + cell_size as f32 / 2.0)
41 }
42
43 pub fn distances(&self, other: &Point) -> (usize, usize) {
44 (self.0.abs_diff(other.0) + 1, self.1.abs_diff(other.1) + 1)
45 }
46
47 pub fn rotated(&self, around: &Point, angle: Angle) -> Point {
48 let (dx, dy) = (
49 self.0 as f32 - around.0 as f32,
50 self.1 as f32 - around.1 as f32,
51 );
52
53 let (cos, sin) = angle.cos_sin();
54 let new_x = dx * cos - dy * sin;
55 let new_y = dx * sin + dy * cos;
56
57 Point(
58 (new_x + around.0 as f32) as usize,
59 (new_y + around.1 as f32) as usize,
60 )
61 }
62}
63
64impl From<(usize, usize)> for Point {
65 fn from(value: (usize, usize)) -> Self {
66 Self(value.0, value.1)
67 }
68}
69
70impl From<(i32, i32)> for Point {
71 fn from(value: (i32, i32)) -> Self {
72 Self(value.0 as usize, value.1 as usize)
73 }
74}
75
76impl PartialEq<(usize, usize)> for Point {
77 fn eq(&self, other: &(usize, usize)) -> bool {
78 self.0 == other.0 && self.1 == other.1
79 }
80}
81
82impl Eq for Point {}
83
84impl std::fmt::Display for Point {
85 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
86 write!(f, "({}, {})", self.0, self.1)
87 }
88}