Bounce bolls off of walls in a proper angle
[kaka/rust-sdl-test.git] / src / common / geometry.rs
CommitLineData
2836f506 1use std::ops::{Add, AddAssign, Sub, SubAssign, Mul, MulAssign, Div, DivAssign, Neg};
296187ca 2
60058b91
TW
3////////// POINT ///////////////////////////////////////////////////////////////
4
787dbfb4 5#[macro_export]
296187ca 6macro_rules! point {
6ba7aef1 7 ( $x:expr, $y:expr ) => {
e570927a 8 Point { x: $x, y: $y }
6ba7aef1 9 };
296187ca
TW
10}
11
b0566120 12#[derive(Debug, Default, Copy, Clone, PartialEq)]
e570927a 13pub struct Point<T> {
296187ca
TW
14 pub x: T,
15 pub y: T,
16}
17
e570927a 18impl Point<f64> {
eca25591 19 pub fn length(&self) -> f64 {
296187ca
TW
20 ((self.x * self.x) + (self.y * self.y)).sqrt()
21 }
bf7b5671 22
93fc5734 23 pub fn normalized(&self) -> Self {
eca25591
TW
24 let l = self.length();
25 Self {
26 x: self.x / l,
27 y: self.y / l,
28 }
29 }
30
ee533e13 31 pub fn to_radians(&self) -> Radians {
eca25591
TW
32 Radians(self.y.atan2(self.x))
33 }
34
ee533e13
TW
35 pub fn to_degrees(&self) -> Degrees {
36 self.to_radians().to_degrees()
eca25591
TW
37 }
38
e570927a
TW
39 pub fn to_i32(self) -> Point<i32> {
40 Point {
bf7b5671
TW
41 x: self.x as i32,
42 y: self.y as i32,
43 }
44 }
296187ca
TW
45}
46
6cd86b94
TW
47macro_rules! point_op {
48 ($op:tt, $trait:ident($fn:ident), $trait_assign:ident($fn_assign:ident), $rhs:ident = $Rhs:ty => $x:expr, $y:expr) => {
e570927a 49 impl<T: $trait<Output = T>> $trait<$Rhs> for Point<T> {
6cd86b94
TW
50 type Output = Self;
51
52 fn $fn(self, $rhs: $Rhs) -> Self {
53 Self {
54 x: self.x $op $x,
55 y: self.y $op $y,
56 }
57 }
2836f506 58 }
2836f506 59
e570927a 60 impl<T: $trait<Output = T> + Copy> $trait_assign<$Rhs> for Point<T> {
6cd86b94
TW
61 fn $fn_assign(&mut self, $rhs: $Rhs) {
62 *self = Self {
63 x: self.x $op $x,
64 y: self.y $op $y,
65 }
66 }
2836f506
TW
67 }
68 }
69}
70
e570927a
TW
71point_op!(+, Add(add), AddAssign(add_assign), rhs = Point<T> => rhs.x, rhs.y);
72point_op!(-, Sub(sub), SubAssign(sub_assign), rhs = Point<T> => rhs.x, rhs.y);
73point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = Point<T> => rhs.x, rhs.y);
74point_op!(/, Div(div), DivAssign(div_assign), rhs = Point<T> => rhs.x, rhs.y);
6cd86b94
TW
75point_op!(+, Add(add), AddAssign(add_assign), rhs = (T, T) => rhs.0, rhs.1);
76point_op!(-, Sub(sub), SubAssign(sub_assign), rhs = (T, T) => rhs.0, rhs.1);
77point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = (T, T) => rhs.0, rhs.1);
78point_op!(/, Div(div), DivAssign(div_assign), rhs = (T, T) => rhs.0, rhs.1);
d59c7f04
TW
79point_op!(*, Mul(mul), MulAssign(mul_assign), rhs = Dimension<T> => rhs.width, rhs.height);
80point_op!(/, Div(div), DivAssign(div_assign), rhs = Dimension<T> => rhs.width, rhs.height);
2836f506
TW
81
82////////// multiply point with scalar //////////////////////////////////////////
e570927a 83impl<T: Mul<Output = T> + Copy> Mul<T> for Point<T> {
2836f506
TW
84 type Output = Self;
85
86 fn mul(self, rhs: T) -> Self {
87 Self {
88 x: self.x * rhs,
89 y: self.y * rhs,
90 }
91 }
92}
93
e570927a 94impl<T: Mul<Output = T> + Copy> MulAssign<T> for Point<T> {
2836f506
TW
95 fn mul_assign(&mut self, rhs: T) {
96 *self = Self {
97 x: self.x * rhs,
98 y: self.y * rhs,
99 }
100 }
101}
102
2836f506 103////////// divide point with scalar ////////////////////////////////////////////
e570927a 104impl<T: Div<Output = T> + Copy> Div<T> for Point<T> {
2836f506
TW
105 type Output = Self;
106
107 fn div(self, rhs: T) -> Self {
108 Self {
109 x: self.x / rhs,
110 y: self.y / rhs,
111 }
112 }
113}
114
e570927a 115impl<T: Div<Output = T> + Copy> DivAssign<T> for Point<T> {
2836f506
TW
116 fn div_assign(&mut self, rhs: T) {
117 *self = Self {
118 x: self.x / rhs,
119 y: self.y / rhs,
120 }
121 }
122}
123
e570927a 124impl<T: Neg<Output = T>> Neg for Point<T> {
2836f506
TW
125 type Output = Self;
126
127 fn neg(self) -> Self {
128 Self {
129 x: -self.x,
130 y: -self.y,
131 }
296187ca
TW
132 }
133}
134
e570927a 135impl<T> From<(T, T)> for Point<T> {
b0566120 136 fn from(item: (T, T)) -> Self {
e570927a 137 Point {
b0566120
TW
138 x: item.0,
139 y: item.1,
140 }
141 }
142}
143
e570927a
TW
144impl<T> From<Point<T>> for (T, T) {
145 fn from(item: Point<T>) -> Self {
bf7b5671
TW
146 (item.x, item.y)
147 }
148}
149
e570927a 150impl From<Degrees> for Point<f64> {
e58a1769 151 fn from(item: Degrees) -> Self {
ee533e13 152 let r = item.0.to_radians();
e570927a 153 Point {
ee533e13
TW
154 x: r.cos(),
155 y: r.sin(),
e58a1769
TW
156 }
157 }
158}
159
e570927a 160impl From<Radians> for Point<f64> {
e58a1769 161 fn from(item: Radians) -> Self {
e570927a 162 Point {
e58a1769
TW
163 x: item.0.cos(),
164 y: item.0.sin(),
165 }
166 }
167}
168
bf7b5671
TW
169#[derive(Debug, Default, PartialEq, Clone, Copy)]
170pub struct Degrees(pub f64);
171#[derive(Debug, Default, PartialEq, Clone, Copy)]
172pub struct Radians(pub f64);
e58a1769
TW
173
174impl Degrees {
bf7b5671 175 #[allow(dead_code)]
8065e264 176 pub fn to_radians(&self) -> Radians {
ee533e13 177 Radians(self.0.to_radians())
e58a1769
TW
178 }
179}
180
181impl Radians {
bf7b5671 182 #[allow(dead_code)]
8065e264 183 pub fn to_degrees(&self) -> Degrees {
ee533e13 184 Degrees(self.0.to_degrees())
e58a1769 185 }
8065e264
TW
186
187 /// Returns the reflection of the incident when mirrored along this angle.
188 pub fn mirror(&self, incidence: Radians) -> Radians {
189 Radians((std::f64::consts::PI + self.0 * 2.0 - incidence.0) % std::f64::consts::TAU)
190 }
e58a1769
TW
191}
192
60058b91
TW
193////////// INTERSECTION ////////////////////////////////////////////////////////
194
195#[derive(Debug)]
196pub enum Intersection {
197 Point(Point<f64>),
198 //Line(Point<f64>, Point<f64>), // TODO: overlapping collinear
199 None,
200}
201
202impl Intersection {
203 pub fn lines(p1: Point<f64>, p2: Point<f64>, p3: Point<f64>, p4: Point<f64>) -> Intersection {
204 let s1 = p2 - p1;
205 let s2 = p4 - p3;
206
207 let denomimator = -s2.x * s1.y + s1.x * s2.y;
208 if denomimator != 0.0 {
209 let s = (-s1.y * (p1.x - p3.x) + s1.x * (p1.y - p3.y)) / denomimator;
210 let t = ( s2.x * (p1.y - p3.y) - s2.y * (p1.x - p3.x)) / denomimator;
211
212 if s >= 0.0 && s <= 1.0 && t >= 0.0 && t <= 1.0 {
213 return Intersection::Point(p1 + (s1 * t))
214 }
215 }
216
217 Intersection::None
218 }
219}
220
221////////// DIMENSION ///////////////////////////////////////////////////////////
222
0b5024d1 223#[macro_export]
1f42d724
TW
224macro_rules! dimen {
225 ( $w:expr, $h:expr ) => {
226 Dimension { width: $w, height: $h }
0b5024d1
TW
227 };
228}
229
8012f86b 230#[derive(Debug, Default, Copy, Clone, PartialEq)]
1f42d724 231pub struct Dimension<T> {
6edafdc0
TW
232 pub width: T,
233 pub height: T,
234}
235
1f42d724 236impl<T: Mul<Output = T> + Copy> Dimension<T> {
6edafdc0
TW
237 #[allow(dead_code)]
238 pub fn area(&self) -> T {
6ba7aef1 239 self.width * self.height
6edafdc0
TW
240 }
241}
242
1f42d724 243impl<T> From<(T, T)> for Dimension<T> {
6edafdc0 244 fn from(item: (T, T)) -> Self {
1f42d724 245 Dimension {
6ba7aef1
TW
246 width: item.0,
247 height: item.1,
248 }
6edafdc0
TW
249 }
250}
251
8012f86b
TW
252impl<T> From<Dimension<T>> for (T, T) {
253 fn from(item: Dimension<T>) -> Self {
254 (item.width, item.height)
255 }
256}
257
258////////////////////////////////////////////////////////////////////////////////
259
260#[allow(dead_code)]
261pub fn supercover_line_int(p1: Point<isize>, p2: Point<isize>) -> Vec<Point<isize>> {
262 let d = p2 - p1;
263 let n = point!(d.x.abs(), d.y.abs());
264 let step = point!(
265 if d.x > 0 { 1 } else { -1 },
266 if d.y > 0 { 1 } else { -1 }
267 );
268
269 let mut p = p1.clone();
270 let mut points = vec!(point!(p.x as isize, p.y as isize));
271 let mut i = point!(0, 0);
272 while i.x < n.x || i.y < n.y {
273 let decision = (1 + 2 * i.x) * n.y - (1 + 2 * i.y) * n.x;
274 if decision == 0 { // next step is diagonal
275 p.x += step.x;
276 p.y += step.y;
277 i.x += 1;
278 i.y += 1;
279 } else if decision < 0 { // next step is horizontal
280 p.x += step.x;
281 i.x += 1;
282 } else { // next step is vertical
283 p.y += step.y;
284 i.y += 1;
285 }
286 points.push(point!(p.x as isize, p.y as isize));
287 }
288
289 points
290}
291
292/// Calculates all points a line crosses, unlike Bresenham's line algorithm.
293/// There might be room for a lot of improvement here.
294pub fn supercover_line(mut p1: Point<f64>, mut p2: Point<f64>) -> Vec<Point<isize>> {
295 let mut delta = p2 - p1;
296 if (delta.x.abs() > delta.y.abs() && delta.x.is_sign_negative()) || (delta.x.abs() <= delta.y.abs() && delta.y.is_sign_negative()) {
297 std::mem::swap(&mut p1, &mut p2);
298 delta = -delta;
299 }
300
301 let mut last = point!(p1.x as isize, p1.y as isize);
302 let mut coords: Vec<Point<isize>> = vec!();
303 coords.push(last);
304
305 if delta.x.abs() > delta.y.abs() {
306 let k = delta.y / delta.x;
307 let m = p1.y as f64 - p1.x as f64 * k;
308 for x in (p1.x as isize + 1)..=(p2.x as isize) {
309 let y = (k * x as f64 + m).floor();
310 let next = point!(x as isize - 1, y as isize);
311 if next != last {
312 coords.push(next);
313 }
314 let next = point!(x as isize, y as isize);
315 coords.push(next);
316 last = next;
317 }
318 } else {
319 let k = delta.x / delta.y;
320 let m = p1.x as f64 - p1.y as f64 * k;
321 for y in (p1.y as isize + 1)..=(p2.y as isize) {
322 let x = (k * y as f64 + m).floor();
323 let next = point!(x as isize, y as isize - 1);
324 if next != last {
325 coords.push(next);
326 }
327 let next = point!(x as isize, y as isize);
328 coords.push(next);
329 last = next;
330 }
331 }
332
333 let next = point!(p2.x as isize, p2.y as isize);
334 if next != last {
335 coords.push(next);
336 }
337
338 coords
339}
340
60058b91 341////////// TESTS ///////////////////////////////////////////////////////////////
249d43ea 342
296187ca
TW
343#[cfg(test)]
344mod tests {
345 use super::*;
346
347 #[test]
348 fn immutable_copy_of_point() {
349 let a = point!(0, 0);
350 let mut b = a; // Copy
351 assert_eq!(a, b); // PartialEq
352 b.x = 1;
353 assert_ne!(a, b); // PartialEq
354 }
355
356 #[test]
357 fn add_points() {
358 let mut a = point!(1, 0);
359 assert_eq!(a + point!(2, 2), point!(3, 2)); // Add
360 a += point!(2, 2); // AddAssign
361 assert_eq!(a, point!(3, 2));
2836f506
TW
362 assert_eq!(point!(1, 0) + (2, 3), point!(3, 3));
363 }
364
365 #[test]
366 fn sub_points() {
367 let mut a = point!(1, 0);
368 assert_eq!(a - point!(2, 2), point!(-1, -2));
369 a -= point!(2, 2);
370 assert_eq!(a, point!(-1, -2));
6cd86b94 371 assert_eq!(point!(1, 0) - (2, 3), point!(-1, -3));
2836f506
TW
372 }
373
374 #[test]
375 fn mul_points() {
376 let mut a = point!(1, 2);
377 assert_eq!(a * 2, point!(2, 4));
378 assert_eq!(a * point!(2, 3), point!(2, 6));
379 a *= 2;
380 assert_eq!(a, point!(2, 4));
381 a *= point!(3, 1);
382 assert_eq!(a, point!(6, 4));
6cd86b94 383 assert_eq!(point!(1, 0) * (2, 3), point!(2, 0));
2836f506
TW
384 }
385
386 #[test]
387 fn div_points() {
388 let mut a = point!(4, 8);
389 assert_eq!(a / 2, point!(2, 4));
390 assert_eq!(a / point!(2, 4), point!(2, 2));
391 a /= 2;
392 assert_eq!(a, point!(2, 4));
393 a /= point!(2, 4);
394 assert_eq!(a, point!(1, 1));
6cd86b94 395 assert_eq!(point!(6, 3) / (2, 3), point!(3, 1));
2836f506
TW
396 }
397
398 #[test]
399 fn neg_point() {
400 assert_eq!(point!(1, 1), -point!(-1, -1));
296187ca 401 }
6edafdc0
TW
402
403 #[test]
e58a1769
TW
404 fn angles() {
405 assert_eq!(Radians(0.0).to_degrees(), Degrees(0.0));
406 assert_eq!(Radians(std::f64::consts::PI).to_degrees(), Degrees(180.0));
407 assert_eq!(Degrees(180.0).to_radians(), Radians(std::f64::consts::PI));
e570927a
TW
408 assert!((Point::from(Degrees(90.0)) - point!(0.0, 1.0)).length() < 0.001);
409 assert!((Point::from(Radians(std::f64::consts::FRAC_PI_2)) - point!(0.0, 1.0)).length() < 0.001);
e58a1769
TW
410 }
411
412 #[test]
1f42d724
TW
413 fn area_for_dimension_of_multipliable_type() {
414 let r: Dimension<_> = (30, 20).into(); // the Into trait uses the From trait
6ba7aef1 415 assert_eq!(r.area(), 30 * 20);
1f42d724 416 // let a = Dimension::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String
6edafdc0 417 }
60058b91
TW
418
419 #[test]
420 fn intersection_of_lines() {
421 let p1 = point!(0.0, 0.0);
422 let p2 = point!(2.0, 2.0);
423 let p3 = point!(0.0, 2.0);
424 let p4 = point!(2.0, 0.0);
425 let r = Intersection::lines(p1, p2, p3, p4);
426 if let Intersection::Point(p) = r {
427 assert_eq!(p, point!(1.0, 1.0));
428 } else {
429 panic!();
430 }
431 }
8012f86b
TW
432
433 #[test]
434 fn some_coordinates_on_line() {
435 // horizontally up
436 let coords = supercover_line(point!(0.0, 0.0), point!(3.3, 2.2));
437 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(1, 0), point!(1, 1), point!(2, 1), point!(2, 2), point!(3, 2)]);
438
439 // horizontally down
440 let coords = supercover_line(point!(0.0, 5.0), point!(3.3, 2.2));
441 assert_eq!(coords.as_slice(), &[point!(0, 5), point!(0, 4), point!(1, 4), point!(1, 3), point!(2, 3), point!(2, 2), point!(3, 2)]);
442
443 // vertically right
444 let coords = supercover_line(point!(0.0, 0.0), point!(2.2, 3.3));
445 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(0, 1), point!(1, 1), point!(1, 2), point!(2, 2), point!(2, 3)]);
446
447 // vertically left
448 let coords = supercover_line(point!(5.0, 0.0), point!(3.0, 3.0));
449 assert_eq!(coords.as_slice(), &[point!(5, 0), point!(4, 0), point!(4, 1), point!(3, 1), point!(3, 2), point!(3, 3)]);
450
451 // negative
452 let coords = supercover_line(point!(0.0, 0.0), point!(-3.0, -2.0));
453 assert_eq!(coords.as_slice(), &[point!(-3, -2), point!(-2, -2), point!(-2, -1), point!(-1, -1), point!(-1, 0), point!(0, 0)]);
454
455 //
456 let coords = supercover_line(point!(0.0, 0.0), point!(2.3, 1.1));
457 assert_eq!(coords.as_slice(), &[point!(0, 0), point!(1, 0), point!(2, 0), point!(2, 1)]);
458 }
296187ca 459}