euv_engine/math/impl.rs
1use crate::*;
2
3/// Implements static math utility methods on the `Numeric` namespace struct.
4impl Numeric {
5 /// Clamps a value between a minimum and maximum bound.
6 ///
7 /// # Arguments
8 ///
9 /// - `f64` - The value to clamp.
10 /// - `f64` - The minimum allowed value.
11 /// - `f64` - The maximum allowed value.
12 ///
13 /// # Returns
14 ///
15 /// - `f64` - The clamped value.
16 pub fn clamp(value: f64, min: f64, max: f64) -> f64 {
17 value.max(min).min(max)
18 }
19
20 /// Performs linear interpolation between two values.
21 ///
22 /// # Arguments
23 ///
24 /// - `f64` - The start value.
25 /// - `f64` - The end value.
26 /// - `f64` - The interpolation factor, typically in the range 0.0 to 1.0.
27 ///
28 /// # Returns
29 ///
30 /// - `f64` - The interpolated value.
31 pub fn lerp(start: f64, end: f64, t: f64) -> f64 {
32 start + (end - start) * t
33 }
34
35 /// Converts an angle from degrees to radians.
36 ///
37 /// # Arguments
38 ///
39 /// - `f64` - The angle in degrees.
40 ///
41 /// # Returns
42 ///
43 /// - `f64` - The angle in radians.
44 pub fn deg_to_rad(degrees: f64) -> f64 {
45 degrees * DEG_TO_RAD
46 }
47
48 /// Converts an angle from radians to degrees.
49 ///
50 /// # Arguments
51 ///
52 /// - `f64` - The angle in radians.
53 ///
54 /// # Returns
55 ///
56 /// - `f64` - The angle in degrees.
57 pub fn rad_to_deg(radians: f64) -> f64 {
58 radians * RAD_TO_DEG
59 }
60
61 /// Normalizes an angle to the range -PI to PI.
62 ///
63 /// # Arguments
64 ///
65 /// - `f64` - The angle in radians.
66 ///
67 /// # Returns
68 ///
69 /// - `f64` - The normalized angle in the range -PI to PI.
70 pub fn normalize_angle(radians: f64) -> f64 {
71 let mut angle: f64 = radians % TWO_PI;
72 if angle < -PI {
73 angle += TWO_PI;
74 }
75 if angle > PI {
76 angle -= TWO_PI;
77 }
78 angle
79 }
80
81 /// Computes the shortest angular difference between two angles.
82 ///
83 /// # Arguments
84 ///
85 /// - `f64` - The source angle in radians.
86 /// - `f64` - The target angle in radians.
87 ///
88 /// # Returns
89 ///
90 /// - `f64` - The signed angular delta in the range -PI to PI.
91 pub fn angle_delta(from: f64, to: f64) -> f64 {
92 Self::normalize_angle(to - from)
93 }
94
95 /// Performs angular interpolation taking the shortest path around the circle.
96 ///
97 /// # Arguments
98 ///
99 /// - `f64` - The source angle in radians.
100 /// - `f64` - The target angle in radians.
101 /// - `f64` - The interpolation factor, typically in the range 0.0 to 1.0.
102 ///
103 /// # Returns
104 ///
105 /// - `f64` - The interpolated angle in radians.
106 pub fn lerp_angle(from: f64, to: f64, t: f64) -> f64 {
107 from + Self::angle_delta(from, to) * t
108 }
109
110 /// Computes the Euclidean distance between two 2D points.
111 ///
112 /// # Arguments
113 ///
114 /// - `Vector2D` - The first point.
115 /// - `Vector2D` - The second point.
116 ///
117 /// # Returns
118 ///
119 /// - `f64` - The distance between the two points.
120 pub fn distance(a: Vector2D, b: Vector2D) -> f64 {
121 (b - a).magnitude()
122 }
123
124 /// Computes the squared Euclidean distance between two 2D points.
125 ///
126 /// Avoids a square root, making it faster for comparison-only use cases.
127 ///
128 /// # Arguments
129 ///
130 /// - `Vector2D` - The first point.
131 /// - `Vector2D` - The second point.
132 ///
133 /// # Returns
134 ///
135 /// - `f64` - The squared distance between the two points.
136 pub fn distance_squared(a: Vector2D, b: Vector2D) -> f64 {
137 (b - a).magnitude_squared()
138 }
139
140 /// Computes a smoothstep interpolation factor using a cubic Hermite polynomial.
141 ///
142 /// # Arguments
143 ///
144 /// - `f64` - The edge minimum.
145 /// - `f64` - The edge maximum.
146 /// - `f64` - The input value.
147 ///
148 /// # Returns
149 ///
150 /// - `f64` - The smoothstep result in the range 0.0 to 1.0.
151 pub fn smoothstep(edge_min: f64, edge_max: f64, value: f64) -> f64 {
152 let clamped: f64 = Self::clamp((value - edge_min) / (edge_max - edge_min), 0.0, 1.0);
153 clamped * clamped * (3.0 - 2.0 * clamped)
154 }
155
156 /// Moves `current` towards `target` by at most `max_delta`.
157 ///
158 /// # Arguments
159 ///
160 /// - `f64` - The current value.
161 /// - `f64` - The target value.
162 /// - `f64` - The maximum allowed change.
163 ///
164 /// # Returns
165 ///
166 /// - `f64` - The new value moved towards target.
167 pub fn approach(current: f64, target: f64, max_delta: f64) -> f64 {
168 if (target - current).abs() <= max_delta {
169 return target;
170 }
171 current + max_delta.signum() * max_delta
172 }
173
174 /// Returns the sign of a value as -1.0, 0.0, or 1.0.
175 ///
176 /// # Arguments
177 ///
178 /// - `f64` - The input value.
179 ///
180 /// # Returns
181 ///
182 /// - `f64` - -1.0 if negative, 0.0 if zero, 1.0 if positive.
183 pub fn sign(value: f64) -> f64 {
184 if value > 0.0 {
185 1.0
186 } else if value < 0.0 {
187 -1.0
188 } else {
189 0.0
190 }
191 }
192
193 /// Wraps a value into the range 0.0 to `max`.
194 ///
195 /// # Arguments
196 ///
197 /// - `f64` - The value to wrap.
198 /// - `f64` - The upper bound of the range.
199 ///
200 /// # Returns
201 ///
202 /// - `f64` - The wrapped value in the range 0.0 to `max`.
203 pub fn wrap(value: f64, max: f64) -> f64 {
204 let result: f64 = value % max;
205 if result < 0.0 { result + max } else { result }
206 }
207
208 /// Returns 1.0 if the value is positive, -1.0 otherwise.
209 ///
210 /// # Arguments
211 ///
212 /// - `f64` - The input value.
213 ///
214 /// # Returns
215 ///
216 /// - `f64` - 1.0 if the value is non-negative, -1.0 otherwise.
217 pub fn sign_or_positive(value: f64) -> f64 {
218 if value < 0.0 { -1.0 } else { 1.0 }
219 }
220
221 /// Computes the Euclidean distance between two 3D points.
222 ///
223 /// # Arguments
224 ///
225 /// - `Vector3D` - The first point.
226 /// - `Vector3D` - The second point.
227 ///
228 /// # Returns
229 ///
230 /// - `f64` - The distance between the two points.
231 pub fn distance_3d(a: Vector3D, b: Vector3D) -> f64 {
232 (b - a).magnitude()
233 }
234
235 /// Computes the squared Euclidean distance between two 3D points.
236 ///
237 /// Avoids a square root, making it faster for comparison-only use cases.
238 ///
239 /// # Arguments
240 ///
241 /// - `Vector3D` - The first point.
242 /// - `Vector3D` - The second point.
243 ///
244 /// # Returns
245 ///
246 /// - `f64` - The squared distance between the two points.
247 pub fn distance_squared_3d(a: Vector3D, b: Vector3D) -> f64 {
248 (b - a).magnitude_squared()
249 }
250}
251
252/// Implements the `Interpolable` trait for `f64`.
253impl Interpolable for f64 {
254 fn lerp(&self, other: f64, t: f64) -> f64 {
255 *self + (other - *self) * t
256 }
257}
258
259/// Implements methods and operator overloading for `Vector2D`.
260impl Vector2D {
261 /// Returns the zero vector (0.0, 0.0).
262 ///
263 /// # Returns
264 ///
265 /// - `Vector2D` - The zero vector.
266 pub fn zero() -> Vector2D {
267 Vector2D::new(0.0, 0.0)
268 }
269
270 /// Returns the unit vector pointing right (1.0, 0.0).
271 ///
272 /// # Returns
273 ///
274 /// - `Vector2D` - The right unit vector.
275 pub fn right() -> Vector2D {
276 Vector2D::new(1.0, 0.0)
277 }
278
279 /// Returns the unit vector pointing up (0.0, -1.0).
280 ///
281 /// In screen coordinates where y increases downward.
282 ///
283 /// # Returns
284 ///
285 /// - `Vector2D` - The up unit vector.
286 pub fn up() -> Vector2D {
287 Vector2D::new(0.0, -1.0)
288 }
289
290 /// Creates a unit vector from an angle in radians.
291 ///
292 /// # Arguments
293 ///
294 /// - `f64` - The angle in radians.
295 ///
296 /// # Returns
297 ///
298 /// - `Vector2D` - The unit vector pointing in the given direction.
299 pub fn from_angle(radians: f64) -> Vector2D {
300 Vector2D::new(radians.cos(), radians.sin())
301 }
302
303 /// Returns the magnitude (length) of the vector.
304 ///
305 /// # Returns
306 ///
307 /// - `f64` - The magnitude of the vector.
308 pub fn magnitude(&self) -> f64 {
309 (self.get_x() * self.get_x() + self.get_y() * self.get_y()).sqrt()
310 }
311
312 /// Returns the squared magnitude of the vector.
313 ///
314 /// Avoids a square root, making it faster for comparison-only use cases.
315 ///
316 /// # Returns
317 ///
318 /// - `f64` - The squared magnitude of the vector.
319 pub fn magnitude_squared(&self) -> f64 {
320 self.get_x() * self.get_x() + self.get_y() * self.get_y()
321 }
322
323 /// Returns a normalized (unit length) copy of this vector.
324 ///
325 /// Returns the zero vector if the magnitude is zero.
326 ///
327 /// # Returns
328 ///
329 /// - `Vector2D` - The normalized vector.
330 pub fn normalized(&self) -> Vector2D {
331 let mag: f64 = self.magnitude();
332 if mag < EPSILON {
333 return Vector2D::zero();
334 }
335 Vector2D::new(self.get_x() / mag, self.get_y() / mag)
336 }
337
338 /// Normalizes this vector in place.
339 pub fn normalize(&mut self) {
340 let mag: f64 = self.magnitude();
341 if mag < EPSILON {
342 self.set_x(0.0);
343 self.set_y(0.0);
344 return;
345 }
346 self.set_x(self.get_x() / mag);
347 self.set_y(self.get_y() / mag);
348 }
349
350 /// Computes the dot product with another vector.
351 ///
352 /// # Arguments
353 ///
354 /// - `Vector2D` - The other vector.
355 ///
356 /// # Returns
357 ///
358 /// - `f64` - The dot product.
359 pub fn dot(&self, other: Vector2D) -> f64 {
360 self.get_x() * other.get_x() + self.get_y() * other.get_y()
361 }
362
363 /// Computes the 2D cross product (scalar) with another vector.
364 ///
365 /// # Arguments
366 ///
367 /// - `Vector2D` - The other vector.
368 ///
369 /// # Returns
370 ///
371 /// - `f64` - The cross product scalar.
372 pub fn cross(&self, other: Vector2D) -> f64 {
373 self.get_x() * other.get_y() - self.get_y() * other.get_x()
374 }
375
376 /// Returns the perpendicular vector (rotated 90 degrees counter-clockwise).
377 ///
378 /// # Returns
379 ///
380 /// - `Vector2D` - The perpendicular vector.
381 pub fn perp(&self) -> Vector2D {
382 Vector2D::new(-self.get_y(), self.get_x())
383 }
384
385 /// Returns the angle of this vector in radians.
386 ///
387 /// # Returns
388 ///
389 /// - `f64` - The angle in radians.
390 pub fn angle(&self) -> f64 {
391 self.get_y().atan2(self.get_x())
392 }
393
394 /// Returns the angle from this vector to another.
395 ///
396 /// # Arguments
397 ///
398 /// - `Vector2D` - The target vector.
399 ///
400 /// # Returns
401 ///
402 /// - `f64` - The signed angle in radians.
403 pub fn angle_to(&self, other: Vector2D) -> f64 {
404 (other - *self).angle()
405 }
406
407 /// Returns a rotated copy of this vector.
408 ///
409 /// # Arguments
410 ///
411 /// - `f64` - The rotation angle in radians.
412 ///
413 /// # Returns
414 ///
415 /// - `Vector2D` - The rotated vector.
416 pub fn rotated(&self, radians: f64) -> Vector2D {
417 let cos: f64 = radians.cos();
418 let sin: f64 = radians.sin();
419 Vector2D::new(
420 self.get_x() * cos - self.get_y() * sin,
421 self.get_x() * sin + self.get_y() * cos,
422 )
423 }
424
425 /// Rotates this vector in place.
426 ///
427 /// # Arguments
428 ///
429 /// - `f64` - The rotation angle in radians.
430 pub fn rotate(&mut self, radians: f64) {
431 let cos: f64 = radians.cos();
432 let sin: f64 = radians.sin();
433 let new_x: f64 = self.get_x() * cos - self.get_y() * sin;
434 let new_y: f64 = self.get_x() * sin + self.get_y() * cos;
435 self.set_x(new_x);
436 self.set_y(new_y);
437 }
438
439 /// Returns the distance from this point to another.
440 ///
441 /// # Arguments
442 ///
443 /// - `Vector2D` - The target point.
444 ///
445 /// # Returns
446 ///
447 /// - `f64` - The Euclidean distance.
448 pub fn distance_to(&self, other: Vector2D) -> f64 {
449 (other - *self).magnitude()
450 }
451
452 /// Returns the squared distance from this point to another.
453 ///
454 /// # Arguments
455 ///
456 /// - `Vector2D` - The target point.
457 ///
458 /// # Returns
459 ///
460 /// - `f64` - The squared Euclidean distance.
461 pub fn distance_squared_to(&self, other: Vector2D) -> f64 {
462 (other - *self).magnitude_squared()
463 }
464
465 /// Returns a unit vector pointing from this point to another.
466 ///
467 /// # Arguments
468 ///
469 /// - `Vector2D` - The target point.
470 ///
471 /// # Returns
472 ///
473 /// - `Vector2D` - The direction unit vector.
474 pub fn direction_to(&self, other: Vector2D) -> Vector2D {
475 (other - *self).normalized()
476 }
477
478 /// Returns a linearly interpolated vector between this and another.
479 ///
480 /// # Arguments
481 ///
482 /// - `Vector2D` - The target vector.
483 /// - `f64` - The interpolation factor.
484 ///
485 /// # Returns
486 ///
487 /// - `Vector2D` - The interpolated vector.
488 pub fn lerp(&self, other: Vector2D, t: f64) -> Vector2D {
489 Vector2D::new(
490 self.get_x() + (other.get_x() - self.get_x()) * t,
491 self.get_y() + (other.get_y() - self.get_y()) * t,
492 )
493 }
494
495 /// Scales this vector by a scalar factor.
496 ///
497 /// # Arguments
498 ///
499 /// - `f64` - The scalar factor.
500 pub fn scale(&mut self, scalar: f64) {
501 self.set_x(self.get_x() * scalar);
502 self.set_y(self.get_y() * scalar);
503 }
504
505 /// Returns a scaled copy of this vector.
506 ///
507 /// # Arguments
508 ///
509 /// - `f64` - The scalar factor.
510 ///
511 /// # Returns
512 ///
513 /// - `Vector2D` - The scaled vector.
514 pub fn scaled(&self, scalar: f64) -> Vector2D {
515 Vector2D::new(self.get_x() * scalar, self.get_y() * scalar)
516 }
517}
518
519/// Implements `Interpolable` for `Vector2D`.
520impl Interpolable for Vector2D {
521 fn lerp(&self, other: Vector2D, t: f64) -> Vector2D {
522 Vector2D::lerp(self, other, t)
523 }
524}
525
526/// Implements vector addition.
527impl Add for Vector2D {
528 type Output = Vector2D;
529 fn add(self, other: Vector2D) -> Vector2D {
530 Vector2D::new(self.get_x() + other.get_x(), self.get_y() + other.get_y())
531 }
532}
533
534/// Implements vector subtraction.
535impl Sub for Vector2D {
536 type Output = Vector2D;
537 fn sub(self, other: Vector2D) -> Vector2D {
538 Vector2D::new(self.get_x() - other.get_x(), self.get_y() - other.get_y())
539 }
540}
541
542/// Implements scalar multiplication.
543impl Mul<f64> for Vector2D {
544 type Output = Vector2D;
545 fn mul(self, scalar: f64) -> Vector2D {
546 Vector2D::new(self.get_x() * scalar, self.get_y() * scalar)
547 }
548}
549
550/// Implements vector negation.
551impl Neg for Vector2D {
552 type Output = Vector2D;
553 fn neg(self) -> Vector2D {
554 Vector2D::new(-self.get_x(), -self.get_y())
555 }
556}
557
558/// Implements in-place vector addition.
559impl AddAssign for Vector2D {
560 fn add_assign(&mut self, other: Vector2D) {
561 self.set_x(self.get_x() + other.get_x());
562 self.set_y(self.get_y() + other.get_y());
563 }
564}
565
566/// Implements in-place vector subtraction.
567impl SubAssign for Vector2D {
568 fn sub_assign(&mut self, other: Vector2D) {
569 self.set_x(self.get_x() - other.get_x());
570 self.set_y(self.get_y() - other.get_y());
571 }
572}
573
574/// Implements in-place scalar multiplication.
575impl MulAssign<f64> for Vector2D {
576 fn mul_assign(&mut self, scalar: f64) {
577 self.set_x(self.get_x() * scalar);
578 self.set_y(self.get_y() * scalar);
579 }
580}
581
582/// Implements methods for `Rect`.
583impl Rect {
584 /// Creates a rectangle from a center point and dimensions.
585 ///
586 /// # Arguments
587 ///
588 /// - `Vector2D` - The center point.
589 /// - `f64` - The width.
590 /// - `f64` - The height.
591 ///
592 /// # Returns
593 ///
594 /// - `Rect` - The new rectangle.
595 pub fn from_center(center: Vector2D, width: f64, height: f64) -> Rect {
596 Rect::new(
597 center.get_x() - width * 0.5,
598 center.get_y() - height * 0.5,
599 width,
600 height,
601 )
602 }
603
604 /// Returns the center point of the rectangle.
605 ///
606 /// # Returns
607 ///
608 /// - `Vector2D` - The center point.
609 pub fn center(&self) -> Vector2D {
610 Vector2D::new(
611 self.get_x() + self.get_width() * 0.5,
612 self.get_y() + self.get_height() * 0.5,
613 )
614 }
615
616 /// Returns the minimum corner (top-left).
617 ///
618 /// # Returns
619 ///
620 /// - `Vector2D` - The minimum corner.
621 pub fn min(&self) -> Vector2D {
622 Vector2D::new(self.get_x(), self.get_y())
623 }
624
625 /// Returns the maximum corner (bottom-right).
626 ///
627 /// # Returns
628 ///
629 /// - `Vector2D` - The maximum corner.
630 pub fn max(&self) -> Vector2D {
631 Vector2D::new(
632 self.get_x() + self.get_width(),
633 self.get_y() + self.get_height(),
634 )
635 }
636
637 /// Returns the size as a vector.
638 ///
639 /// # Returns
640 ///
641 /// - `Vector2D` - The size vector.
642 pub fn size(&self) -> Vector2D {
643 Vector2D::new(self.get_width(), self.get_height())
644 }
645
646 /// Tests whether a point is inside this rectangle.
647 ///
648 /// # Arguments
649 ///
650 /// - `Vector2D` - The point to test.
651 ///
652 /// # Returns
653 ///
654 /// - `bool` - True if the point is inside.
655 pub fn contains(&self, point: Vector2D) -> bool {
656 point.get_x() >= self.get_x()
657 && point.get_x() <= self.get_x() + self.get_width()
658 && point.get_y() >= self.get_y()
659 && point.get_y() <= self.get_y() + self.get_height()
660 }
661
662 /// Tests whether this rectangle intersects another.
663 ///
664 /// # Arguments
665 ///
666 /// - `Rect` - The other rectangle.
667 ///
668 /// # Returns
669 ///
670 /// - `bool` - True if they intersect.
671 pub fn intersects(&self, other: Rect) -> bool {
672 self.x < other.x + other.width
673 && self.x + self.width > other.x
674 && self.y < other.y + other.height
675 && self.y + self.height > other.y
676 }
677
678 /// Alias for `intersects` — used by the physics module's broad-phase
679 /// collision check. (`Rect::broad_phase(a, b)` was being referenced by
680 /// upstream code; we expose it here so the engine compiles cleanly.)
681 pub fn broad_phase_alias(a: Rect, b: Rect) -> bool {
682 a.intersects(b)
683 }
684
685 /// Returns the intersection of two rectangles, or `None` if they do not overlap.
686 ///
687 /// # Arguments
688 ///
689 /// - `Rect` - The other rectangle.
690 ///
691 /// # Returns
692 ///
693 /// - `Option<Rect>` - The intersection rectangle, or `None`.
694 pub fn intersection(&self, other: Rect) -> Option<Rect> {
695 if !self.intersects(other) {
696 return None;
697 }
698 let max_x: f64 = self.get_x().max(other.get_x());
699 let max_y: f64 = self.get_y().max(other.get_y());
700 let min_right: f64 =
701 (self.get_x() + self.get_width()).min(other.get_x() + other.get_width());
702 let min_bottom: f64 =
703 (self.get_y() + self.get_height()).min(other.get_y() + other.get_height());
704 Some(Rect::new(
705 max_x,
706 max_y,
707 min_right - max_x,
708 min_bottom - max_y,
709 ))
710 }
711}
712
713/// Implements methods for `Circle`.
714impl Circle {
715 /// Tests whether a point is inside this circle.
716 ///
717 /// # Arguments
718 ///
719 /// - `Vector2D` - The point to test.
720 ///
721 /// # Returns
722 ///
723 /// - `bool` - True if the point is inside.
724 pub fn contains(&self, point: Vector2D) -> bool {
725 self.get_center().distance_squared_to(point) <= self.get_radius() * self.get_radius()
726 }
727
728 /// Tests whether this circle intersects another.
729 ///
730 /// # Arguments
731 ///
732 /// - `Circle` - The other circle.
733 ///
734 /// # Returns
735 ///
736 /// - `bool` - True if they intersect.
737 pub fn intersects(&self, other: Circle) -> bool {
738 let distance_sq: f64 = self.get_center().distance_squared_to(other.get_center());
739 let radius_sum: f64 = self.get_radius() + other.get_radius();
740 distance_sq <= radius_sum * radius_sum
741 }
742
743 /// Returns the circumference of the circle.
744 ///
745 /// # Returns
746 ///
747 /// - `f64` - The circumference.
748 pub fn circumference(&self) -> f64 {
749 TWO_PI * self.get_radius()
750 }
751
752 /// Returns the area of the circle.
753 ///
754 /// # Returns
755 ///
756 /// - `f64` - The area.
757 pub fn area(&self) -> f64 {
758 PI * self.get_radius() * self.get_radius()
759 }
760}
761
762/// Implements methods for `Transform2D`.
763impl Transform2D {
764 /// Creates a new transform at the origin with no rotation and unit scale.
765 ///
766 /// # Returns
767 ///
768 /// - `Transform2D` - The identity transform.
769 pub fn identity() -> Transform2D {
770 Transform2D::new(Vector2D::zero(), 0.0, Vector2D::new(1.0, 1.0))
771 }
772
773 /// Translates the position by the given offset.
774 ///
775 /// # Arguments
776 ///
777 /// - `Vector2D` - The translation offset.
778 pub fn translate(&mut self, offset: Vector2D) {
779 self.set_position(self.get_position() + offset);
780 }
781
782 /// Rotates by the given angle in radians.
783 ///
784 /// # Arguments
785 ///
786 /// - `f64` - The rotation delta in radians.
787 pub fn rotate(&mut self, radians: f64) {
788 self.set_rotation(self.get_rotation() + radians);
789 }
790
791 /// Scales by the given factors.
792 ///
793 /// # Arguments
794 ///
795 /// - `Vector2D` - The scale factors.
796 pub fn scale_by(&mut self, factors: Vector2D) {
797 let mut scale: Vector2D = self.get_scale();
798 scale.set_x(scale.get_x() * factors.get_x());
799 scale.set_y(scale.get_y() * factors.get_y());
800 self.set_scale(scale);
801 }
802
803 /// Applies this transform to a local-space point, returning world-space coordinates.
804 ///
805 /// # Arguments
806 ///
807 /// - `Vector2D` - The local-space point.
808 ///
809 /// # Returns
810 ///
811 /// - `Vector2D` - The transformed world-space point.
812 pub fn apply_to_point(&self, point: Vector2D) -> Vector2D {
813 let scaled: Vector2D = Vector2D::new(
814 point.get_x() * self.get_scale().get_x(),
815 point.get_y() * self.get_scale().get_y(),
816 );
817 scaled.rotated(self.get_rotation()) + self.get_position()
818 }
819}
820
821/// Implements `Default` for `Transform2D` as the identity transform.
822impl Default for Transform2D {
823 fn default() -> Transform2D {
824 Transform2D::identity()
825 }
826}
827
828/// Implements methods for `Color`.
829impl Color {
830 /// Creates a color from RGB hex values (0-255), with full opacity.
831 ///
832 /// # Arguments
833 ///
834 /// - `u8` - The red channel (0-255).
835 /// - `u8` - The green channel (0-255).
836 /// - `u8` - The blue channel (0-255).
837 ///
838 /// # Returns
839 ///
840 /// - `Color` - The new color.
841 pub fn from_rgb(red: u8, green: u8, blue: u8) -> Color {
842 Color::new(
843 red as f64 / 255.0,
844 green as f64 / 255.0,
845 blue as f64 / 255.0,
846 1.0,
847 )
848 }
849
850 /// Converts the color to a CSS `rgba()` string.
851 ///
852 /// # Returns
853 ///
854 /// - `String` - The CSS color string.
855 pub fn to_css_rgba(&self) -> String {
856 let red: i32 = (self.get_red() * 255.0).round() as i32;
857 let green: i32 = (self.get_green() * 255.0).round() as i32;
858 let blue: i32 = (self.get_blue() * 255.0).round() as i32;
859 let alpha: f64 = self.get_alpha();
860 format!("rgba({red}, {green}, {blue}, {alpha})")
861 }
862
863 /// Returns black (0, 0, 0, 1).
864 ///
865 /// # Returns
866 ///
867 /// - `Color` - The black color.
868 pub fn black() -> Color {
869 Color::new(0.0, 0.0, 0.0, 1.0)
870 }
871
872 /// Returns white (1, 1, 1, 1).
873 ///
874 /// # Returns
875 ///
876 /// - `Color` - The white color.
877 pub fn white() -> Color {
878 Color::new(1.0, 1.0, 1.0, 1.0)
879 }
880
881 /// Returns transparent (0, 0, 0, 0).
882 ///
883 /// # Returns
884 ///
885 /// - `Color` - The transparent color.
886 pub fn transparent() -> Color {
887 Color::new(0.0, 0.0, 0.0, 0.0)
888 }
889}
890
891/// Implements `Default` for `Color` as opaque black.
892impl Default for Color {
893 fn default() -> Color {
894 Color::black()
895 }
896}
897
898/// Implements methods and operator overloading for `Vector3D`.
899impl Vector3D {
900 /// Returns the zero vector (0.0, 0.0, 0.0).
901 ///
902 /// # Returns
903 ///
904 /// - `Vector3D` - The zero vector.
905 pub fn zero() -> Vector3D {
906 Vector3D::new(0.0, 0.0, 0.0)
907 }
908
909 /// Returns the unit vector pointing right (1.0, 0.0, 0.0).
910 ///
911 /// # Returns
912 ///
913 /// - `Vector3D` - The right unit vector.
914 pub fn right() -> Vector3D {
915 Vector3D::new(1.0, 0.0, 0.0)
916 }
917
918 /// Returns the unit vector pointing up (0.0, 1.0, 0.0).
919 ///
920 /// # Returns
921 ///
922 /// - `Vector3D` - The up unit vector.
923 pub fn up() -> Vector3D {
924 Vector3D::new(0.0, 1.0, 0.0)
925 }
926
927 /// Returns the unit vector pointing forward (0.0, 0.0, -1.0).
928 ///
929 /// In a right-handed coordinate system where -z is forward.
930 ///
931 /// # Returns
932 ///
933 /// - `Vector3D` - The forward unit vector.
934 pub fn forward() -> Vector3D {
935 Vector3D::new(0.0, 0.0, -1.0)
936 }
937
938 /// Returns the magnitude (length) of the vector.
939 ///
940 /// # Returns
941 ///
942 /// - `f64` - The magnitude of the vector.
943 pub fn magnitude(&self) -> f64 {
944 (self.get_x() * self.get_x() + self.get_y() * self.get_y() + self.get_z() * self.get_z())
945 .sqrt()
946 }
947
948 /// Returns the squared magnitude of the vector.
949 ///
950 /// Avoids a square root, making it faster for comparison-only use cases.
951 ///
952 /// # Returns
953 ///
954 /// - `f64` - The squared magnitude of the vector.
955 pub fn magnitude_squared(&self) -> f64 {
956 self.get_x() * self.get_x() + self.get_y() * self.get_y() + self.get_z() * self.get_z()
957 }
958
959 /// Returns a normalized (unit length) copy of this vector.
960 ///
961 /// Returns the zero vector if the magnitude is zero.
962 ///
963 /// # Returns
964 ///
965 /// - `Vector3D` - The normalized vector.
966 pub fn normalized(&self) -> Vector3D {
967 let mag: f64 = self.magnitude();
968 if mag < EPSILON {
969 return Vector3D::zero();
970 }
971 Vector3D::new(self.get_x() / mag, self.get_y() / mag, self.get_z() / mag)
972 }
973
974 /// Normalizes this vector in place.
975 pub fn normalize(&mut self) {
976 let mag: f64 = self.magnitude();
977 if mag < EPSILON {
978 self.set_x(0.0);
979 self.set_y(0.0);
980 self.set_z(0.0);
981 return;
982 }
983 self.set_x(self.get_x() / mag);
984 self.set_y(self.get_y() / mag);
985 self.set_z(self.get_z() / mag);
986 }
987
988 /// Computes the dot product with another vector.
989 ///
990 /// # Arguments
991 ///
992 /// - `Vector3D` - The other vector.
993 ///
994 /// # Returns
995 ///
996 /// - `f64` - The dot product.
997 pub fn dot(&self, other: Vector3D) -> f64 {
998 self.get_x() * other.get_x() + self.get_y() * other.get_y() + self.get_z() * other.get_z()
999 }
1000
1001 /// Computes the 3D cross product with another vector.
1002 ///
1003 /// # Arguments
1004 ///
1005 /// - `Vector3D` - The other vector.
1006 ///
1007 /// # Returns
1008 ///
1009 /// - `Vector3D` - The cross product vector.
1010 pub fn cross(&self, other: Vector3D) -> Vector3D {
1011 Vector3D::new(
1012 self.get_y() * other.get_z() - self.get_z() * other.get_y(),
1013 self.get_z() * other.get_x() - self.get_x() * other.get_z(),
1014 self.get_x() * other.get_y() - self.get_y() * other.get_x(),
1015 )
1016 }
1017
1018 /// Returns the distance from this point to another.
1019 ///
1020 /// # Arguments
1021 ///
1022 /// - `Vector3D` - The target point.
1023 ///
1024 /// # Returns
1025 ///
1026 /// - `f64` - The Euclidean distance.
1027 pub fn distance_to(&self, other: Vector3D) -> f64 {
1028 (other - *self).magnitude()
1029 }
1030
1031 /// Returns the squared distance from this point to another.
1032 ///
1033 /// # Arguments
1034 ///
1035 /// - `Vector3D` - The target point.
1036 ///
1037 /// # Returns
1038 ///
1039 /// - `f64` - The squared Euclidean distance.
1040 pub fn distance_squared_to(&self, other: Vector3D) -> f64 {
1041 (other - *self).magnitude_squared()
1042 }
1043
1044 /// Returns a unit vector pointing from this point to another.
1045 ///
1046 /// # Arguments
1047 ///
1048 /// - `Vector3D` - The target point.
1049 ///
1050 /// # Returns
1051 ///
1052 /// - `Vector3D` - The direction unit vector.
1053 pub fn direction_to(&self, other: Vector3D) -> Vector3D {
1054 (other - *self).normalized()
1055 }
1056
1057 /// Returns a linearly interpolated vector between this and another.
1058 ///
1059 /// # Arguments
1060 ///
1061 /// - `Vector3D` - The target vector.
1062 /// - `f64` - The interpolation factor.
1063 ///
1064 /// # Returns
1065 ///
1066 /// - `Vector3D` - The interpolated vector.
1067 pub fn lerp(&self, other: Vector3D, t: f64) -> Vector3D {
1068 Vector3D::new(
1069 self.get_x() + (other.get_x() - self.get_x()) * t,
1070 self.get_y() + (other.get_y() - self.get_y()) * t,
1071 self.get_z() + (other.get_z() - self.get_z()) * t,
1072 )
1073 }
1074
1075 /// Scales this vector by a scalar factor.
1076 ///
1077 /// # Arguments
1078 ///
1079 /// - `f64` - The scalar factor.
1080 pub fn scale(&mut self, scalar: f64) {
1081 self.set_x(self.get_x() * scalar);
1082 self.set_y(self.get_y() * scalar);
1083 self.set_z(self.get_z() * scalar);
1084 }
1085
1086 /// Returns a scaled copy of this vector.
1087 ///
1088 /// # Arguments
1089 ///
1090 /// - `f64` - The scalar factor.
1091 ///
1092 /// # Returns
1093 ///
1094 /// - `Vector3D` - The scaled vector.
1095 pub fn scaled(&self, scalar: f64) -> Vector3D {
1096 Vector3D::new(
1097 self.get_x() * scalar,
1098 self.get_y() * scalar,
1099 self.get_z() * scalar,
1100 )
1101 }
1102
1103 /// Rotates this vector by a quaternion.
1104 ///
1105 /// # Arguments
1106 ///
1107 /// - `Quaternion` - The rotation quaternion.
1108 ///
1109 /// # Returns
1110 ///
1111 /// - `Vector3D` - The rotated vector.
1112 pub fn rotated_by(&self, quaternion: Quaternion) -> Vector3D {
1113 let pure: Quaternion = Quaternion::new(self.get_x(), self.get_y(), self.get_z(), 0.0);
1114 let result: Quaternion = quaternion * pure * quaternion.conjugate();
1115 Vector3D::new(result.get_x(), result.get_y(), result.get_z())
1116 }
1117}
1118
1119/// Implements `Interpolable` for `Vector3D`.
1120impl Interpolable for Vector3D {
1121 fn lerp(&self, other: Vector3D, t: f64) -> Vector3D {
1122 Vector3D::lerp(self, other, t)
1123 }
1124}
1125
1126/// Implements vector addition.
1127impl Add for Vector3D {
1128 type Output = Vector3D;
1129 fn add(self, other: Vector3D) -> Vector3D {
1130 Vector3D::new(
1131 self.get_x() + other.get_x(),
1132 self.get_y() + other.get_y(),
1133 self.get_z() + other.get_z(),
1134 )
1135 }
1136}
1137
1138/// Implements vector subtraction.
1139impl Sub for Vector3D {
1140 type Output = Vector3D;
1141 fn sub(self, other: Vector3D) -> Vector3D {
1142 Vector3D::new(
1143 self.get_x() - other.get_x(),
1144 self.get_y() - other.get_y(),
1145 self.get_z() - other.get_z(),
1146 )
1147 }
1148}
1149
1150/// Implements scalar multiplication.
1151impl Mul<f64> for Vector3D {
1152 type Output = Vector3D;
1153 fn mul(self, scalar: f64) -> Vector3D {
1154 Vector3D::new(
1155 self.get_x() * scalar,
1156 self.get_y() * scalar,
1157 self.get_z() * scalar,
1158 )
1159 }
1160}
1161
1162/// Implements vector negation.
1163impl Neg for Vector3D {
1164 type Output = Vector3D;
1165 fn neg(self) -> Vector3D {
1166 Vector3D::new(-self.get_x(), -self.get_y(), -self.get_z())
1167 }
1168}
1169
1170/// Implements in-place vector addition.
1171impl AddAssign for Vector3D {
1172 fn add_assign(&mut self, other: Vector3D) {
1173 self.set_x(self.get_x() + other.get_x());
1174 self.set_y(self.get_y() + other.get_y());
1175 self.set_z(self.get_z() + other.get_z());
1176 }
1177}
1178
1179/// Implements in-place vector subtraction.
1180impl SubAssign for Vector3D {
1181 fn sub_assign(&mut self, other: Vector3D) {
1182 self.set_x(self.get_x() - other.get_x());
1183 self.set_y(self.get_y() - other.get_y());
1184 self.set_z(self.get_z() - other.get_z());
1185 }
1186}
1187
1188/// Implements in-place scalar multiplication.
1189impl MulAssign<f64> for Vector3D {
1190 fn mul_assign(&mut self, scalar: f64) {
1191 self.set_x(self.get_x() * scalar);
1192 self.set_y(self.get_y() * scalar);
1193 self.set_z(self.get_z() * scalar);
1194 }
1195}
1196
1197/// Implements quaternion operations for `Quaternion`.
1198impl Quaternion {
1199 /// Returns the identity quaternion (0, 0, 0, 1) representing no rotation.
1200 ///
1201 /// # Returns
1202 ///
1203 /// - `Quaternion` - The identity quaternion.
1204 pub fn identity() -> Quaternion {
1205 Quaternion::new(0.0, 0.0, 0.0, 1.0)
1206 }
1207
1208 /// Creates a quaternion from a rotation around an axis.
1209 ///
1210 /// # Arguments
1211 ///
1212 /// - `Vector3D` - The rotation axis (should be normalized).
1213 /// - `f64` - The rotation angle in radians.
1214 ///
1215 /// # Returns
1216 ///
1217 /// - `Quaternion` - The rotation quaternion.
1218 pub fn from_axis_angle(axis: Vector3D, angle: f64) -> Quaternion {
1219 let half: f64 = angle * 0.5;
1220 let sin_half: f64 = half.sin();
1221 let cos_half: f64 = half.cos();
1222 let normalized_axis: Vector3D = axis.normalized();
1223 Quaternion::new(
1224 normalized_axis.get_x() * sin_half,
1225 normalized_axis.get_y() * sin_half,
1226 normalized_axis.get_z() * sin_half,
1227 cos_half,
1228 )
1229 }
1230
1231 /// Creates a quaternion from Euler angles (yaw, pitch, roll) in radians.
1232 ///
1233 /// # Arguments
1234 ///
1235 /// - `f64` - The yaw (rotation around y axis) in radians.
1236 /// - `f64` - The pitch (rotation around x axis) in radians.
1237 /// - `f64` - The roll (rotation around z axis) in radians.
1238 ///
1239 /// # Returns
1240 ///
1241 /// - `Quaternion` - The rotation quaternion.
1242 pub fn from_euler(yaw: f64, pitch: f64, roll: f64) -> Quaternion {
1243 let half_yaw: f64 = yaw * 0.5;
1244 let half_pitch: f64 = pitch * 0.5;
1245 let half_roll: f64 = roll * 0.5;
1246 let cy: f64 = half_yaw.cos();
1247 let sy: f64 = half_yaw.sin();
1248 let cp: f64 = half_pitch.cos();
1249 let sp: f64 = half_pitch.sin();
1250 let cr: f64 = half_roll.cos();
1251 let sr: f64 = half_roll.sin();
1252 Quaternion::new(
1253 sp * cy * cr + cp * sy * sr,
1254 cp * sy * cr - sp * cy * sr,
1255 cp * cy * sr - sp * sy * cr,
1256 sp * sy * sr + cp * cy * cr,
1257 )
1258 }
1259
1260 /// Returns the magnitude of the quaternion.
1261 ///
1262 /// # Returns
1263 ///
1264 /// - `f64` - The magnitude.
1265 pub fn magnitude(&self) -> f64 {
1266 (self.get_x() * self.get_x()
1267 + self.get_y() * self.get_y()
1268 + self.get_z() * self.get_z()
1269 + self.get_w() * self.get_w())
1270 .sqrt()
1271 }
1272
1273 /// Returns a normalized copy of this quaternion.
1274 ///
1275 /// # Returns
1276 ///
1277 /// - `Quaternion` - The normalized quaternion.
1278 pub fn normalized(&self) -> Quaternion {
1279 let mag: f64 = self.magnitude();
1280 if mag < EPSILON {
1281 return Quaternion::identity();
1282 }
1283 let inv: f64 = 1.0 / mag;
1284 Quaternion::new(
1285 self.get_x() * inv,
1286 self.get_y() * inv,
1287 self.get_z() * inv,
1288 self.get_w() * inv,
1289 )
1290 }
1291
1292 /// Returns the conjugate of this quaternion.
1293 ///
1294 /// # Returns
1295 ///
1296 /// - `Quaternion` - The conjugate quaternion.
1297 pub fn conjugate(&self) -> Quaternion {
1298 Quaternion::new(-self.get_x(), -self.get_y(), -self.get_z(), self.get_w())
1299 }
1300
1301 /// Computes the dot product with another quaternion.
1302 ///
1303 /// # Arguments
1304 ///
1305 /// - `Quaternion` - The other quaternion.
1306 ///
1307 /// # Returns
1308 ///
1309 /// - `f64` - The dot product.
1310 pub fn dot(&self, other: Quaternion) -> f64 {
1311 self.get_x() * other.get_x()
1312 + self.get_y() * other.get_y()
1313 + self.get_z() * other.get_z()
1314 + self.get_w() * other.get_w()
1315 }
1316
1317 /// Performs spherical linear interpolation between this and another quaternion.
1318 ///
1319 /// # Arguments
1320 ///
1321 /// - `Quaternion` - The target quaternion.
1322 /// - `f64` - The interpolation factor in the range 0.0 to 1.0.
1323 ///
1324 /// # Returns
1325 ///
1326 /// - `Quaternion` - The interpolated quaternion.
1327 pub fn slerp(&self, other: Quaternion, t: f64) -> Quaternion {
1328 let mut cos_theta: f64 = self.dot(other);
1329 let target: Quaternion = if cos_theta < 0.0 {
1330 cos_theta = -cos_theta;
1331 Quaternion::new(
1332 -other.get_x(),
1333 -other.get_y(),
1334 -other.get_z(),
1335 -other.get_w(),
1336 )
1337 } else {
1338 other
1339 };
1340 if cos_theta > 1.0 - EPSILON {
1341 return Quaternion::new(
1342 self.get_x() + (target.get_x() - self.get_x()) * t,
1343 self.get_y() + (target.get_y() - self.get_y()) * t,
1344 self.get_z() + (target.get_z() - self.get_z()) * t,
1345 self.get_w() + (target.get_w() - self.get_w()) * t,
1346 )
1347 .normalized();
1348 }
1349 let theta: f64 = cos_theta.acos();
1350 let sin_theta: f64 = theta.sin();
1351 let factor_a: f64 = ((1.0 - t) * theta).sin() / sin_theta;
1352 let factor_b: f64 = (t * theta).sin() / sin_theta;
1353 Quaternion::new(
1354 self.get_x() * factor_a + target.get_x() * factor_b,
1355 self.get_y() * factor_a + target.get_y() * factor_b,
1356 self.get_z() * factor_a + target.get_z() * factor_b,
1357 self.get_w() * factor_a + target.get_w() * factor_b,
1358 )
1359 }
1360}
1361
1362/// Implements quaternion multiplication.
1363impl Mul for Quaternion {
1364 type Output = Quaternion;
1365 fn mul(self, other: Quaternion) -> Quaternion {
1366 Quaternion::new(
1367 self.get_w() * other.get_x()
1368 + self.get_x() * other.get_w()
1369 + self.get_y() * other.get_z()
1370 - self.get_z() * other.get_y(),
1371 self.get_w() * other.get_y() - self.get_x() * other.get_z()
1372 + self.get_y() * other.get_w()
1373 + self.get_z() * other.get_x(),
1374 self.get_w() * other.get_z() + self.get_x() * other.get_y()
1375 - self.get_y() * other.get_x()
1376 + self.get_z() * other.get_w(),
1377 self.get_w() * other.get_w()
1378 - self.get_x() * other.get_x()
1379 - self.get_y() * other.get_y()
1380 - self.get_z() * other.get_z(),
1381 )
1382 }
1383}
1384
1385/// Implements matrix operations for `Matrix4x4`.
1386impl Matrix4x4 {
1387 /// Returns the identity matrix.
1388 ///
1389 /// # Returns
1390 ///
1391 /// - `Matrix4x4` - The identity matrix.
1392 pub fn identity() -> Matrix4x4 {
1393 Matrix4x4::new([
1394 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
1395 ])
1396 }
1397
1398 /// Creates a translation matrix.
1399 ///
1400 /// # Arguments
1401 ///
1402 /// - `Vector3D` - The translation vector.
1403 ///
1404 /// # Returns
1405 ///
1406 /// - `Matrix4x4` - The translation matrix.
1407 pub fn translation(translation: Vector3D) -> Matrix4x4 {
1408 let mut elements: [f64; 16] = Self::identity().get_elements();
1409 elements[12] = translation.get_x();
1410 elements[13] = translation.get_y();
1411 elements[14] = translation.get_z();
1412 Matrix4x4::new(elements)
1413 }
1414
1415 /// Creates a scaling matrix.
1416 ///
1417 /// # Arguments
1418 ///
1419 /// - `Vector3D` - The scale factors.
1420 ///
1421 /// # Returns
1422 ///
1423 /// - `Matrix4x4` - The scaling matrix.
1424 pub fn scaling(scale: Vector3D) -> Matrix4x4 {
1425 Matrix4x4::new([
1426 scale.get_x(),
1427 0.0,
1428 0.0,
1429 0.0,
1430 0.0,
1431 scale.get_y(),
1432 0.0,
1433 0.0,
1434 0.0,
1435 0.0,
1436 scale.get_z(),
1437 0.0,
1438 0.0,
1439 0.0,
1440 0.0,
1441 1.0,
1442 ])
1443 }
1444
1445 /// Creates a rotation matrix from a quaternion.
1446 ///
1447 /// # Arguments
1448 ///
1449 /// - `Quaternion` - The rotation quaternion.
1450 ///
1451 /// # Returns
1452 ///
1453 /// - `Matrix4x4` - The rotation matrix.
1454 pub fn rotation(quaternion: Quaternion) -> Matrix4x4 {
1455 let xx: f64 = quaternion.get_x() * quaternion.get_x();
1456 let yy: f64 = quaternion.get_y() * quaternion.get_y();
1457 let zz: f64 = quaternion.get_z() * quaternion.get_z();
1458 let xy: f64 = quaternion.get_x() * quaternion.get_y();
1459 let xz: f64 = quaternion.get_x() * quaternion.get_z();
1460 let yz: f64 = quaternion.get_y() * quaternion.get_z();
1461 let wx: f64 = quaternion.get_w() * quaternion.get_x();
1462 let wy: f64 = quaternion.get_w() * quaternion.get_y();
1463 let wz: f64 = quaternion.get_w() * quaternion.get_z();
1464 Matrix4x4::new([
1465 1.0 - 2.0 * (yy + zz),
1466 2.0 * (xy + wz),
1467 2.0 * (xz - wy),
1468 0.0,
1469 2.0 * (xy - wz),
1470 1.0 - 2.0 * (xx + zz),
1471 2.0 * (yz + wx),
1472 0.0,
1473 2.0 * (xz + wy),
1474 2.0 * (yz - wx),
1475 1.0 - 2.0 * (xx + yy),
1476 0.0,
1477 0.0,
1478 0.0,
1479 0.0,
1480 1.0,
1481 ])
1482 }
1483
1484 /// Creates a perspective projection matrix.
1485 ///
1486 /// # Arguments
1487 ///
1488 /// - `f64` - The vertical field of view in radians.
1489 /// - `f64` - The aspect ratio (width / height).
1490 /// - `f64` - The near clipping plane distance.
1491 /// - `f64` - The far clipping plane distance.
1492 ///
1493 /// # Returns
1494 ///
1495 /// - `Matrix4x4` - The perspective projection matrix.
1496 pub fn perspective(fov: f64, aspect: f64, near: f64, far: f64) -> Matrix4x4 {
1497 let f: f64 = 1.0 / (fov * 0.5).tan();
1498 let range: f64 = far - near;
1499 Matrix4x4::new([
1500 f / aspect,
1501 0.0,
1502 0.0,
1503 0.0,
1504 0.0,
1505 f,
1506 0.0,
1507 0.0,
1508 0.0,
1509 0.0,
1510 -(far + near) / range,
1511 -1.0,
1512 0.0,
1513 0.0,
1514 -(2.0 * far * near) / range,
1515 0.0,
1516 ])
1517 }
1518
1519 /// Creates an orthographic projection matrix.
1520 ///
1521 /// # Arguments
1522 ///
1523 /// - `f64` - The left boundary.
1524 /// - `f64` - The right boundary.
1525 /// - `f64` - The bottom boundary.
1526 /// - `f64` - The top boundary.
1527 /// - `f64` - The near clipping plane distance.
1528 /// - `f64` - The far clipping plane distance.
1529 ///
1530 /// # Returns
1531 ///
1532 /// - `Matrix4x4` - The orthographic projection matrix.
1533 pub fn orthographic(
1534 left: f64,
1535 right: f64,
1536 bottom: f64,
1537 top: f64,
1538 near: f64,
1539 far: f64,
1540 ) -> Matrix4x4 {
1541 let rml: f64 = right - left;
1542 let tmb: f64 = top - bottom;
1543 let fmn: f64 = far - near;
1544 Matrix4x4::new([
1545 2.0 / rml,
1546 0.0,
1547 0.0,
1548 0.0,
1549 0.0,
1550 2.0 / tmb,
1551 0.0,
1552 0.0,
1553 0.0,
1554 0.0,
1555 -2.0 / fmn,
1556 0.0,
1557 -(right + left) / rml,
1558 -(top + bottom) / tmb,
1559 -(far + near) / fmn,
1560 1.0,
1561 ])
1562 }
1563
1564 /// Creates a view matrix using the "look at" convention.
1565 ///
1566 /// # Arguments
1567 ///
1568 /// - `Vector3D` - The eye position.
1569 /// - `Vector3D` - The target position to look at.
1570 /// - `Vector3D` - The up direction.
1571 ///
1572 /// # Returns
1573 ///
1574 /// - `Matrix4x4` - The view matrix.
1575 pub fn look_at(eye: Vector3D, target: Vector3D, up: Vector3D) -> Matrix4x4 {
1576 let forward: Vector3D = (target - eye).normalized();
1577 let right: Vector3D = forward.cross(up).normalized();
1578 let up_orthogonal: Vector3D = right.cross(forward);
1579 Matrix4x4::new([
1580 right.get_x(),
1581 up_orthogonal.get_x(),
1582 -forward.get_x(),
1583 0.0,
1584 right.get_y(),
1585 up_orthogonal.get_y(),
1586 -forward.get_y(),
1587 0.0,
1588 right.get_z(),
1589 up_orthogonal.get_z(),
1590 -forward.get_z(),
1591 0.0,
1592 -right.dot(eye),
1593 -up_orthogonal.dot(eye),
1594 forward.dot(eye),
1595 1.0,
1596 ])
1597 }
1598
1599 /// Multiplies this matrix by another using fully unrolled arithmetic.
1600 ///
1601 /// Eliminates all loop overhead and allows the compiler to maximize
1602 /// register allocation and instruction-level parallelism.
1603 ///
1604 /// # Arguments
1605 ///
1606 /// - `Matrix4x4` - The other matrix.
1607 ///
1608 /// # Returns
1609 ///
1610 /// - `Matrix4x4` - The product matrix.
1611 pub fn multiply(&self, other: Matrix4x4) -> Matrix4x4 {
1612 let a: [f64; 16] = self.get_elements();
1613 let b: [f64; 16] = other.get_elements();
1614 Matrix4x4::new([
1615 a[0] * b[0] + a[4] * b[1] + a[8] * b[2] + a[12] * b[3],
1616 a[1] * b[0] + a[5] * b[1] + a[9] * b[2] + a[13] * b[3],
1617 a[2] * b[0] + a[6] * b[1] + a[10] * b[2] + a[14] * b[3],
1618 a[3] * b[0] + a[7] * b[1] + a[11] * b[2] + a[15] * b[3],
1619 a[0] * b[4] + a[4] * b[5] + a[8] * b[6] + a[12] * b[7],
1620 a[1] * b[4] + a[5] * b[5] + a[9] * b[6] + a[13] * b[7],
1621 a[2] * b[4] + a[6] * b[5] + a[10] * b[6] + a[14] * b[7],
1622 a[3] * b[4] + a[7] * b[5] + a[11] * b[6] + a[15] * b[7],
1623 a[0] * b[8] + a[4] * b[9] + a[8] * b[10] + a[12] * b[11],
1624 a[1] * b[8] + a[5] * b[9] + a[9] * b[10] + a[13] * b[11],
1625 a[2] * b[8] + a[6] * b[9] + a[10] * b[10] + a[14] * b[11],
1626 a[3] * b[8] + a[7] * b[9] + a[11] * b[10] + a[15] * b[11],
1627 a[0] * b[12] + a[4] * b[13] + a[8] * b[14] + a[12] * b[15],
1628 a[1] * b[12] + a[5] * b[13] + a[9] * b[14] + a[13] * b[15],
1629 a[2] * b[12] + a[6] * b[13] + a[10] * b[14] + a[14] * b[15],
1630 a[3] * b[12] + a[7] * b[13] + a[11] * b[14] + a[15] * b[15],
1631 ])
1632 }
1633
1634 /// Transforms a 3D point by this matrix, applying the perspective divide.
1635 ///
1636 /// # Arguments
1637 ///
1638 /// - `Vector3D` - The point to transform.
1639 ///
1640 /// # Returns
1641 ///
1642 /// - `Vector3D` - The transformed point.
1643 pub fn transform_point(&self, point: Vector3D) -> Vector3D {
1644 let elements: [f64; 16] = self.get_elements();
1645 let x: f64 = elements[0] * point.get_x()
1646 + elements[4] * point.get_y()
1647 + elements[8] * point.get_z()
1648 + elements[12];
1649 let y: f64 = elements[1] * point.get_x()
1650 + elements[5] * point.get_y()
1651 + elements[9] * point.get_z()
1652 + elements[13];
1653 let z: f64 = elements[2] * point.get_x()
1654 + elements[6] * point.get_y()
1655 + elements[10] * point.get_z()
1656 + elements[14];
1657 let w: f64 = elements[3] * point.get_x()
1658 + elements[7] * point.get_y()
1659 + elements[11] * point.get_z()
1660 + elements[15];
1661 if w.abs() < EPSILON {
1662 return Vector3D::new(x, y, z);
1663 }
1664 Vector3D::new(x / w, y / w, z / w)
1665 }
1666}
1667
1668/// Implements `Default` for `Quaternion` as the identity quaternion.
1669impl Default for Quaternion {
1670 fn default() -> Quaternion {
1671 Quaternion::identity()
1672 }
1673}
1674
1675/// Implements `Default` for `Matrix4x4` as the identity matrix.
1676impl Default for Matrix4x4 {
1677 fn default() -> Matrix4x4 {
1678 Matrix4x4::identity()
1679 }
1680}
1681
1682/// Implements methods for `Transform3D`.
1683impl Transform3D {
1684 /// Creates a new transform at the origin with no rotation and unit scale.
1685 ///
1686 /// # Returns
1687 ///
1688 /// - `Transform3D` - The identity transform.
1689 pub fn identity() -> Transform3D {
1690 Transform3D::new(
1691 Vector3D::zero(),
1692 Quaternion::identity(),
1693 Vector3D::new(1.0, 1.0, 1.0),
1694 )
1695 }
1696
1697 /// Translates the position by the given offset.
1698 ///
1699 /// # Arguments
1700 ///
1701 /// - `Vector3D` - The translation offset.
1702 pub fn translate(&mut self, offset: Vector3D) {
1703 self.set_position(self.get_position() + offset);
1704 }
1705
1706 /// Rotates by the given quaternion (post-multiplies).
1707 ///
1708 /// # Arguments
1709 ///
1710 /// - `Quaternion` - The rotation to apply.
1711 pub fn rotate(&mut self, rotation: Quaternion) {
1712 self.set_rotation(rotation * self.get_rotation());
1713 }
1714
1715 /// Scales by the given factors.
1716 ///
1717 /// # Arguments
1718 ///
1719 /// - `Vector3D` - The scale factors.
1720 pub fn scale_by(&mut self, factors: Vector3D) {
1721 let mut scale: Vector3D = self.get_scale();
1722 scale.set_x(scale.get_x() * factors.get_x());
1723 scale.set_y(scale.get_y() * factors.get_y());
1724 scale.set_z(scale.get_z() * factors.get_z());
1725 self.set_scale(scale);
1726 }
1727
1728 /// Applies this transform to a local-space point, returning world-space coordinates.
1729 ///
1730 /// # Arguments
1731 ///
1732 /// - `Vector3D` - The local-space point.
1733 ///
1734 /// # Returns
1735 ///
1736 /// - `Vector3D` - The transformed world-space point.
1737 pub fn apply_to_point(&self, point: Vector3D) -> Vector3D {
1738 let scale: Vector3D = self.get_scale();
1739 let scaled: Vector3D = Vector3D::new(
1740 point.get_x() * scale.get_x(),
1741 point.get_y() * scale.get_y(),
1742 point.get_z() * scale.get_z(),
1743 );
1744 scaled.rotated_by(self.get_rotation()) + self.get_position()
1745 }
1746
1747 /// Converts this transform to a `Matrix4x4`.
1748 ///
1749 /// # Returns
1750 ///
1751 /// - `Matrix4x4` - The composed transformation matrix.
1752 pub fn to_matrix(&self) -> Matrix4x4 {
1753 let translation: Matrix4x4 = Matrix4x4::translation(self.get_position());
1754 let rotation: Matrix4x4 = Matrix4x4::rotation(self.get_rotation());
1755 let scaling: Matrix4x4 = Matrix4x4::scaling(self.get_scale());
1756 translation.multiply(rotation).multiply(scaling)
1757 }
1758}
1759
1760/// Implements `Default` for `Transform3D` as the identity transform.
1761impl Default for Transform3D {
1762 fn default() -> Transform3D {
1763 Transform3D::identity()
1764 }
1765}
1766
1767/// Implements methods for `AABB3D`.
1768impl AABB3D {
1769 /// Creates an AABB from a center point and dimensions.
1770 ///
1771 /// # Arguments
1772 ///
1773 /// - `Vector3D` - The center point.
1774 /// - `f64` - The width.
1775 /// - `f64` - The height.
1776 /// - `f64` - The depth.
1777 ///
1778 /// # Returns
1779 ///
1780 /// - `AABB3D` - The new bounding box.
1781 pub fn from_center(center: Vector3D, width: f64, height: f64, depth: f64) -> AABB3D {
1782 AABB3D::new(
1783 Vector3D::new(
1784 center.get_x() - width * 0.5,
1785 center.get_y() - height * 0.5,
1786 center.get_z() - depth * 0.5,
1787 ),
1788 Vector3D::new(
1789 center.get_x() + width * 0.5,
1790 center.get_y() + height * 0.5,
1791 center.get_z() + depth * 0.5,
1792 ),
1793 )
1794 }
1795
1796 /// Returns the center point of the bounding box.
1797 ///
1798 /// # Returns
1799 ///
1800 /// - `Vector3D` - The center point.
1801 pub fn center(&self) -> Vector3D {
1802 Vector3D::new(
1803 (self.get_min().get_x() + self.get_max().get_x()) * 0.5,
1804 (self.get_min().get_y() + self.get_max().get_y()) * 0.5,
1805 (self.get_min().get_z() + self.get_max().get_z()) * 0.5,
1806 )
1807 }
1808
1809 /// Returns the dimensions of the bounding box as a vector.
1810 ///
1811 /// # Returns
1812 ///
1813 /// - `Vector3D` - The size vector (width, height, depth).
1814 pub fn size(&self) -> Vector3D {
1815 Vector3D::new(
1816 self.get_max().get_x() - self.get_min().get_x(),
1817 self.get_max().get_y() - self.get_min().get_y(),
1818 self.get_max().get_z() - self.get_min().get_z(),
1819 )
1820 }
1821
1822 /// Tests whether a point is inside this bounding box.
1823 ///
1824 /// # Arguments
1825 ///
1826 /// - `Vector3D` - The point to test.
1827 ///
1828 /// # Returns
1829 ///
1830 /// - `bool` - True if the point is inside.
1831 pub fn contains(&self, point: Vector3D) -> bool {
1832 point.get_x() >= self.get_min().get_x()
1833 && point.get_x() <= self.get_max().get_x()
1834 && point.get_y() >= self.get_min().get_y()
1835 && point.get_y() <= self.get_max().get_y()
1836 && point.get_z() >= self.get_min().get_z()
1837 && point.get_z() <= self.get_max().get_z()
1838 }
1839
1840 /// Tests whether this bounding box intersects another.
1841 ///
1842 /// # Arguments
1843 ///
1844 /// - `AABB3D` - The other bounding box.
1845 ///
1846 /// # Returns
1847 ///
1848 /// - `bool` - True if they intersect.
1849 pub fn intersects(&self, other: AABB3D) -> bool {
1850 self.get_min().get_x() <= other.get_max().get_x()
1851 && self.get_max().get_x() >= other.get_min().get_x()
1852 && self.get_min().get_y() <= other.get_max().get_y()
1853 && self.get_max().get_y() >= other.get_min().get_y()
1854 && self.get_min().get_z() <= other.get_max().get_z()
1855 && self.get_max().get_z() >= other.get_min().get_z()
1856 }
1857}
1858
1859/// Implements methods for `Sphere`.
1860impl Sphere {
1861 /// Tests whether a point is inside this sphere.
1862 ///
1863 /// # Arguments
1864 ///
1865 /// - `Vector3D` - The point to test.
1866 ///
1867 /// # Returns
1868 ///
1869 /// - `bool` - True if the point is inside.
1870 pub fn contains(&self, point: Vector3D) -> bool {
1871 self.get_center().distance_squared_to(point) <= self.get_radius() * self.get_radius()
1872 }
1873
1874 /// Tests whether this sphere intersects another.
1875 ///
1876 /// # Arguments
1877 ///
1878 /// - `Sphere` - The other sphere.
1879 ///
1880 /// # Returns
1881 ///
1882 /// - `bool` - True if they intersect.
1883 pub fn intersects(&self, other: Sphere) -> bool {
1884 let distance_sq: f64 = self.get_center().distance_squared_to(other.get_center());
1885 let radius_sum: f64 = self.get_radius() + other.get_radius();
1886 distance_sq <= radius_sum * radius_sum
1887 }
1888
1889 /// Returns the volume of the sphere.
1890 ///
1891 /// # Returns
1892 ///
1893 /// - `f64` - The volume.
1894 pub fn volume(&self) -> f64 {
1895 (4.0 / 3.0) * PI * self.get_radius() * self.get_radius() * self.get_radius()
1896 }
1897
1898 /// Returns the surface area of the sphere.
1899 ///
1900 /// # Returns
1901 ///
1902 /// - `f64` - The surface area.
1903 pub fn surface_area(&self) -> f64 {
1904 4.0 * PI * self.get_radius() * self.get_radius()
1905 }
1906}
1907
1908/// Implements methods for `Plane`.
1909impl Plane {
1910 /// Creates a plane from a normal and a point on the plane.
1911 ///
1912 /// # Arguments
1913 ///
1914 /// - `Vector3D` - The normal vector.
1915 /// - `Vector3D` - A point on the plane.
1916 ///
1917 /// # Returns
1918 ///
1919 /// - `Plane` - The new plane.
1920 pub fn from_normal_and_point(normal: Vector3D, point: Vector3D) -> Plane {
1921 let normalized_normal: Vector3D = normal.normalized();
1922 Plane::new(normalized_normal, -normalized_normal.dot(point))
1923 }
1924
1925 /// Returns the signed distance from a point to this plane.
1926 ///
1927 /// # Arguments
1928 ///
1929 /// - `Vector3D` - The point to test.
1930 ///
1931 /// # Returns
1932 ///
1933 /// - `f64` - The signed distance (positive on the normal side).
1934 pub fn distance_to_point(&self, point: Vector3D) -> f64 {
1935 self.get_normal().dot(point) + self.get_distance()
1936 }
1937
1938 /// Normalizes the plane normal and adjusts the distance accordingly.
1939 pub fn normalize(&mut self) {
1940 let mut normal: Vector3D = self.get_normal();
1941 let mag: f64 = normal.magnitude();
1942 if mag < EPSILON {
1943 return;
1944 }
1945 normal.set_x(normal.get_x() / mag);
1946 normal.set_y(normal.get_y() / mag);
1947 normal.set_z(normal.get_z() / mag);
1948 self.set_normal(normal);
1949 self.set_distance(self.get_distance() / mag);
1950 }
1951}
1952
1953/// Implements methods for `Ray3D`.
1954impl Ray3D {
1955 /// Returns the point on the ray at the given parameter value.
1956 ///
1957 /// # Arguments
1958 ///
1959 /// - `f64` - The parameter value (distance along the ray).
1960 ///
1961 /// # Returns
1962 ///
1963 /// - `Vector3D` - The point at the given distance.
1964 pub fn point_at(&self, t: f64) -> Vector3D {
1965 self.get_origin() + self.get_direction().scaled(t)
1966 }
1967
1968 /// Tests for intersection with a sphere, returning the nearest distance if hit.
1969 ///
1970 /// # Arguments
1971 ///
1972 /// - `Sphere` - The sphere to test.
1973 ///
1974 /// # Returns
1975 ///
1976 /// - `Option<f64>` - The distance to the intersection, or `None`.
1977 pub fn intersect_sphere(&self, sphere: Sphere) -> Option<f64> {
1978 let oc: Vector3D = self.get_origin() - sphere.get_center();
1979 let direction: Vector3D = self.get_direction();
1980 let a: f64 = direction.dot(direction);
1981 let b: f64 = 2.0 * oc.dot(direction);
1982 let c: f64 = oc.dot(oc) - sphere.get_radius() * sphere.get_radius();
1983 let discriminant: f64 = b * b - 4.0 * a * c;
1984 if discriminant < 0.0 {
1985 return None;
1986 }
1987 let sqrt_d: f64 = discriminant.sqrt();
1988 let t1: f64 = (-b - sqrt_d) / (2.0 * a);
1989 if t1 >= 0.0 {
1990 return Some(t1);
1991 }
1992 let t2: f64 = (-b + sqrt_d) / (2.0 * a);
1993 if t2 >= 0.0 {
1994 return Some(t2);
1995 }
1996 None
1997 }
1998
1999 /// Tests for intersection with a plane, returning the distance if hit.
2000 ///
2001 /// # Arguments
2002 ///
2003 /// - `Plane` - The plane to test.
2004 ///
2005 /// # Returns
2006 ///
2007 /// - `Option<f64>` - The distance to the intersection, or `None`.
2008 pub fn intersect_plane(&self, plane: Plane) -> Option<f64> {
2009 let direction: Vector3D = self.get_direction();
2010 let normal: Vector3D = plane.get_normal();
2011 let denom: f64 = direction.dot(normal);
2012 if denom.abs() < EPSILON {
2013 return None;
2014 }
2015 let t: f64 = -(normal.dot(self.get_origin()) + plane.get_distance()) / denom;
2016 if t >= 0.0 { Some(t) } else { None }
2017 }
2018
2019 /// Tests for intersection with an AABB, returning the nearest distance if hit.
2020 ///
2021 /// # Arguments
2022 ///
2023 /// - `AABB3D` - The bounding box to test.
2024 ///
2025 /// # Returns
2026 ///
2027 /// - `Option<f64>` - The distance to the intersection, or `None`.
2028 pub fn intersect_aabb(&self, aabb: AABB3D) -> Option<f64> {
2029 let mut t_min: f64 = f64::MIN;
2030 let mut t_max: f64 = f64::MAX;
2031 let direction: Vector3D = self.get_direction();
2032 let origin: Vector3D = self.get_origin();
2033 let aabb_min: Vector3D = aabb.get_min();
2034 let aabb_max: Vector3D = aabb.get_max();
2035 for axis in 0..3usize {
2036 let (dir_component, origin_component, min_component, max_component) = match axis {
2037 0 => (
2038 direction.get_x(),
2039 origin.get_x(),
2040 aabb_min.get_x(),
2041 aabb_max.get_x(),
2042 ),
2043 1 => (
2044 direction.get_y(),
2045 origin.get_y(),
2046 aabb_min.get_y(),
2047 aabb_max.get_y(),
2048 ),
2049 _ => (
2050 direction.get_z(),
2051 origin.get_z(),
2052 aabb_min.get_z(),
2053 aabb_max.get_z(),
2054 ),
2055 };
2056 if dir_component.abs() < EPSILON {
2057 if origin_component < min_component || origin_component > max_component {
2058 return None;
2059 }
2060 } else {
2061 let inv_dir: f64 = 1.0 / dir_component;
2062 let t1: f64 = (min_component - origin_component) * inv_dir;
2063 let t2: f64 = (max_component - origin_component) * inv_dir;
2064 let t_near: f64 = t1.min(t2);
2065 let t_far: f64 = t1.max(t2);
2066 t_min = t_min.max(t_near);
2067 t_max = t_max.min(t_far);
2068 if t_min > t_max {
2069 return None;
2070 }
2071 }
2072 }
2073 if t_min >= 0.0 {
2074 Some(t_min)
2075 } else if t_max >= 0.0 {
2076 Some(t_max)
2077 } else {
2078 None
2079 }
2080 }
2081}