1use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
13pub struct Point3 {
14 pub x: f64,
16 pub y: f64,
18 pub z: f64,
20}
21
22impl Point3 {
23 pub fn new(x: f64, y: f64, z: f64) -> Self {
25 Point3 { x, y, z }
26 }
27
28 pub fn distance(self, other: Point3) -> f64 {
30 self.distance_squared(other).sqrt()
31 }
32
33 pub fn distance_squared(self, other: Point3) -> f64 {
35 (self.x - other.x).powi(2) + (self.y - other.y).powi(2) + (self.z - other.z).powi(2)
36 }
37
38 pub fn vector_from(self, origin: Point3) -> Vector3 {
40 Vector3::new(self.x - origin.x, self.y - origin.y, self.z - origin.z)
41 }
42
43 #[must_use]
45 pub fn translated(self, vector: Vector3, scale: f64) -> Point3 {
46 Point3::new(
47 self.x + scale * vector.x,
48 self.y + scale * vector.y,
49 self.z + scale * vector.z,
50 )
51 }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
57pub struct Vector3 {
58 pub x: f64,
60 pub y: f64,
62 pub z: f64,
64}
65
66impl Vector3 {
67 pub fn new(x: f64, y: f64, z: f64) -> Self {
69 Vector3 { x, y, z }
70 }
71
72 pub fn norm(&self) -> f64 {
74 (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
75 }
76
77 pub fn dot(self, other: Vector3) -> f64 {
79 self.x * other.x + self.y * other.y + self.z * other.z
80 }
81
82 #[must_use]
84 pub fn cross(self, other: Vector3) -> Vector3 {
85 Vector3::new(
86 self.y * other.z - self.z * other.y,
87 self.z * other.x - self.x * other.z,
88 self.x * other.y - self.y * other.x,
89 )
90 }
91
92 #[must_use]
94 pub fn scale(self, factor: f64) -> Vector3 {
95 Vector3::new(self.x * factor, self.y * factor, self.z * factor)
96 }
97
98 #[must_use]
101 pub fn unit(self) -> Option<Vector3> {
102 let length = self.norm();
103 (length > f64::EPSILON)
104 .then(|| Vector3::new(self.x / length, self.y / length, self.z / length))
105 }
106}
107
108impl std::ops::Add for Vector3 {
109 type Output = Vector3;
110
111 fn add(self, other: Vector3) -> Vector3 {
112 Vector3::new(self.x + other.x, self.y + other.y, self.z + other.z)
113 }
114}
115
116impl std::ops::Sub for Vector3 {
117 type Output = Vector3;
118
119 fn sub(self, other: Vector3) -> Vector3 {
120 Vector3::new(self.x - other.x, self.y - other.y, self.z - other.z)
121 }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
126pub struct Point2 {
127 pub u: f64,
129 pub v: f64,
131}
132
133impl Point2 {
134 pub fn new(u: f64, v: f64) -> Self {
136 Point2 { u, v }
137 }
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
142pub struct Aabb {
143 pub min: Point3,
145 pub max: Point3,
147}