gemath 0.1.0

Type-safe game math with type-level units/spaces, typed angles, and explicit fallible ops (plus optional geometry/collision).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
use crate::vec3::Vec3;
use core::marker::PhantomData;
use crate::math;
#[cfg(feature = "unit_vec")]
use crate::unit_vec::UnitVec3;

// Re-export shared marker types for backwards-compatible paths like `gemath::vec4::Meters`.
pub use crate::markers::{Local, Meters, Pixels, Screen, World};

#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Radians;
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Degrees;

/// 4D vector with type-level unit and coordinate space
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct Vec4<Unit: Copy = (), Space: Copy = ()> {
    pub x: f32,
    pub y: f32,
    pub z: f32,
    pub w: f32,
    #[cfg_attr(feature = "serde", serde(skip))]
    _unit: PhantomData<Unit>,
    #[cfg_attr(feature = "serde", serde(skip))]
    _space: PhantomData<Space>,
}

/// Type aliases for common units and spaces
pub type Vec4f32 = Vec4<(),()>;
pub type Vec4Meters = Vec4<Meters,()>;
pub type Vec4Pixels = Vec4<Pixels,()>;
pub type Vec4World = Vec4<(),World>;
pub type Vec4Local = Vec4<(),Local>;
pub type Vec4Screen = Vec4<(),Screen>;
pub type Vec4MetersWorld = Vec4<Meters,World>;
pub type Vec4PixelsScreen = Vec4<Pixels,Screen>;

impl<Unit: Copy, Space: Copy> Vec4<Unit, Space> {
    pub const ZERO: Self = Self {
        x: 0.0,
        y: 0.0,
        z: 0.0,
        w: 0.0,
        _unit: PhantomData,
        _space: PhantomData,
    };

    pub const fn new(x: f32, y: f32, z: f32, w: f32) -> Self {
        Self { x, y, z, w, _unit: PhantomData, _space: PhantomData }
    }

    /// Returns the xyz components of this Vec4 as a Vec3.
    pub fn xyz(self) -> Vec3<Unit, Space> {
        Vec3::new(self.x, self.y, self.z)
    }

    /// Calculates the dot product of two vectors.
    #[inline]
    pub const fn dot(self, other: Self) -> f32 {
        self.x * other.x + self.y * other.y + self.z * other.z + self.w * other.w
    }

    pub const fn wzyx(self) -> Self {
        Self {
            x: self.w,
            y: self.z,
            z: self.y,
            w: self.x,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Calculates the squared length (magnitude squared) of the vector.
    /// This is equivalent to `self.dot(self)`.
    #[inline]
    pub const fn length_squared(self) -> f32 {
        self.dot(self)
    }

    /// Calculates the length (magnitude) of the vector.
    #[inline]
    pub fn length(self) -> f32 {
        math::sqrt(self.length_squared())
    }

    /// Normalizes the vector to unit length.
    /// Returns `Vec4::ZERO` if the vector has zero length.
    #[inline]
    pub fn normalize(self) -> Self {
        let len_sq = self.length_squared();
        if len_sq == 0.0 {
            // Or use a small epsilon comparison
            Self::ZERO
        } else {
            self / math::sqrt(len_sq)
        }
    }

    /// Tries to normalize the vector to unit length.
    /// Returns `None` if the vector has zero length.
    #[inline]
    pub fn try_normalize(self) -> Option<Self> {
        let len_sq = self.length_squared();
        if len_sq > 0.0 {
            Some(self * (1.0 / math::sqrt(len_sq)))
        } else {
            None
        }
    }

    /// Divides this vector by a scalar, returning `None` for invalid divisors.
    ///
    /// Returns `None` if `rhs` is zero (including `-0.0`) or non-finite (`NaN`, `±inf`).
    #[inline]
    pub fn checked_div_scalar(self, rhs: f32) -> Option<Self> {
        if rhs == 0.0 || !rhs.is_finite() {
            None
        } else {
            Some(self / rhs)
        }
    }

    /// Reflects this vector (incident vector `i`) about a normal `n`.
    /// Operates on xyz, preserves w.
    pub fn reflect(self, normal: Self) -> Self {
        let reflected_xyz = self.xyz().reflect(normal.xyz());
        Self::new(reflected_xyz.x, reflected_xyz.y, reflected_xyz.z, self.w)
    }

    /// Reflects this vector about a **unit** normal (xyz), preserving w.
    #[inline]
    #[cfg(feature = "unit_vec")]
    pub fn reflect_unit(self, normal: UnitVec3<Unit, Space>) -> Self {
        let reflected_xyz = self.xyz().reflect(normal.as_vec());
        Self::new(reflected_xyz.x, reflected_xyz.y, reflected_xyz.z, self.w)
    }

    /// Computes the refraction of this vector (`i`) given a surface normal `n` and an index of refraction `eta` (n1/n2).
    /// Operates on xyz, preserves w. Returns a zero vector (for xyz) if total internal reflection occurs.
    pub fn refract(self, normal: Self, eta: f32) -> Self {
        let refracted_xyz = self.xyz().refract(normal.xyz(), eta);
        Self::new(refracted_xyz.x, refracted_xyz.y, refracted_xyz.z, self.w)
    }

    /// Attempts to compute the refraction of this vector (`i`) given a surface normal `n` and an index of refraction `eta` (n1/n2).
    /// Operates on xyz, preserves w. Returns `None` if total internal reflection occurs for the xyz part.
    pub fn try_refract(self, normal: Self, eta: f32) -> Option<Self> {
        match self.xyz().try_refract(normal.xyz(), eta) {
            Some(refracted_xyz) => Some(Self::new(
                refracted_xyz.x,
                refracted_xyz.y,
                refracted_xyz.z,
                self.w,
            )),
            None => None,
        }
    }

    /// Computes refraction using a **unit** normal (xyz), preserving w.
    #[inline]
    #[cfg(feature = "unit_vec")]
    pub fn refract_unit(self, normal: UnitVec3<Unit, Space>, eta: f32) -> Self {
        let refracted_xyz = self.xyz().refract(normal.as_vec(), eta);
        Self::new(refracted_xyz.x, refracted_xyz.y, refracted_xyz.z, self.w)
    }

    /// Attempts refraction using a **unit** normal (xyz), preserving w.
    #[inline]
    #[cfg(feature = "unit_vec")]
    pub fn try_refract_unit(self, normal: UnitVec3<Unit, Space>, eta: f32) -> Option<Self> {
        match self.xyz().try_refract(normal.as_vec(), eta) {
            Some(refracted_xyz) => Some(Self::new(
                refracted_xyz.x,
                refracted_xyz.y,
                refracted_xyz.z,
                self.w,
            )),
            None => None,
        }
    }

    /// Reflects the vector `i` about the normal `n` (static version).
    pub fn reflect_incident(i: Self, n: Self) -> Self {
        i - n * (2.0 * i.dot(n))
    }

    /// Refracts the incident vector `i` through a surface with normal `n` (static version).
    pub fn refract_gl(i: Self, n: Self, eta: f32) -> Self {
        let dot_ni = i.dot(n);
        let k = 1.0 - eta * eta * (1.0 - dot_ni * dot_ni);
        if k < 0.0 {
            Self::ZERO
        } else {
            i * eta - n * (eta * dot_ni + math::sqrt(k))
        }
    }

    /// Attempts to refract the incident vector `i` through a surface with normal `n` (static version).
    pub fn try_refract_gl(i: Self, n: Self, eta: f32) -> Option<Self> {
        let dot_ni = i.dot(n);
        let k = 1.0 - eta * eta * (1.0 - dot_ni * dot_ni);
        if k < 0.0 {
            None
        } else {
            Some(i * eta - n * (eta * dot_ni + math::sqrt(k)))
        }
    }

    /// Refracts the incident vector `i` through a surface with normal `n` (static version).
    ///
    /// This is the naming-consistent alias for `refract_gl`.
    #[inline]
    pub fn refract_incident(i: Self, n: Self, eta: f32) -> Self {
        Self::refract_gl(i, n, eta)
    }

    /// Attempts to refract the incident vector `i` through a surface with normal `n` (static version).
    ///
    /// This is the naming-consistent alias for `try_refract_gl`.
    #[inline]
    pub fn try_refract_incident(i: Self, n: Self, eta: f32) -> Option<Self> {
        Self::try_refract_gl(i, n, eta)
    }

    /// Linearly interpolates between two vectors.
    #[inline]
    pub fn lerp(self, b: Self, t: f32) -> Self {
        Self {
            x: self.x + (b.x - self.x) * t,
            y: self.y + (b.y - self.y) * t,
            z: self.z + (b.z - self.z) * t,
            w: self.w + (b.w - self.w) * t,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Returns the angle (in radians) between self and other.
    pub fn angle_between(self, other: Self) -> f32 {
        let dot = self.dot(other);
        let len_product = self.length() * other.length();
        if len_product == 0.0 {
            0.0
        } else {
            math::acos((dot / len_product).clamp(-1.0, 1.0))
        }
    }

    /// Projects self onto other.
    pub fn project_onto(self, other: Self) -> Self {
        let other_len_sq = other.length_squared();
        if other_len_sq == 0.0 {
            Self::ZERO
        } else {
            other * (self.dot(other) / other_len_sq)
        }
    }

    /// Normalizes the vector or returns Vec4::ZERO if length is zero.
    pub fn normalize_or_zero(self) -> Self {
        let len = self.length();
        if len == 0.0 { Self::ZERO } else { self / len }
    }

    /// Returns the distance between self and other.
    pub fn distance(self, other: Self) -> f32 {
        (self - other).length()
    }

    /// Clamps each component of self between min and max.
    pub const fn clamp(self, min: Self, max: Self) -> Self {
        Self {
            x: if self.x < min.x { min.x } else if self.x > max.x { max.x } else { self.x },
            y: if self.y < min.y { min.y } else if self.y > max.y { max.y } else { self.y },
            z: if self.z < min.z { min.z } else if self.z > max.z { max.z } else { self.z },
            w: if self.w < min.w { min.w } else if self.w > max.w { max.w } else { self.w },
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Returns the component-wise minimum of self and other.
    pub const fn min(self, other: Self) -> Self {
        Self {
            x: if self.x < other.x { self.x } else { other.x },
            y: if self.y < other.y { self.y } else { other.y },
            z: if self.z < other.z { self.z } else { other.z },
            w: if self.w < other.w { self.w } else { other.w },
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Returns the component-wise maximum of self and other.
    pub const fn max(self, other: Self) -> Self {
        Self {
            x: if self.x > other.x { self.x } else { other.x },
            y: if self.y > other.y { self.y } else { other.y },
            z: if self.z > other.z { self.z } else { other.z },
            w: if self.w > other.w { self.w } else { other.w },
            _unit: PhantomData,
            _space: PhantomData,
        }
    }

    /// Returns true if any component is NaN.
    pub fn is_nan(self) -> bool {
        self.x.is_nan() || self.y.is_nan() || self.z.is_nan() || self.w.is_nan()
    }

    /// Returns true if all components are finite.
    pub fn is_finite(self) -> bool {
        self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite()
    }
}

impl Vec4<Meters,()> {
    pub fn to_pixels(self, scale: f32) -> Vec4<Pixels,()> {
        Vec4 {
            x: self.x * scale,
            y: self.y * scale,
            z: self.z * scale,
            w: self.w * scale,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

impl<Unit: Copy, Space: Copy> Add for Vec4<Unit, Space> {
    type Output = Self;
    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
            z: self.z + rhs.z,
            w: self.w + rhs.w,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> AddAssign for Vec4<Unit, Space> {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        self.x += rhs.x;
        self.y += rhs.y;
        self.z += rhs.z;
        self.w += rhs.w;
    }
}

impl<Unit: Copy, Space: Copy> Sub for Vec4<Unit, Space> {
    type Output = Self;
    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
            z: self.z - rhs.z,
            w: self.w - rhs.w,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> SubAssign for Vec4<Unit, Space> {
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        self.x -= rhs.x;
        self.y -= rhs.y;
        self.z -= rhs.z;
        self.w -= rhs.w;
    }
}

impl<Unit: Copy, Space: Copy> Mul<f32> for Vec4<Unit, Space> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: f32) -> Self::Output {
        Self {
            x: self.x * rhs,
            y: self.y * rhs,
            z: self.z * rhs,
            w: self.w * rhs,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> Mul<Vec4<Unit, Space>> for f32 {
    type Output = Vec4<Unit, Space>;
    #[inline]
    fn mul(self, rhs: Vec4<Unit, Space>) -> Self::Output {
        Vec4 {
            x: self * rhs.x,
            y: self * rhs.y,
            z: self * rhs.z,
            w: self * rhs.w,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> MulAssign<f32> for Vec4<Unit, Space> {
    #[inline]
    fn mul_assign(&mut self, rhs: f32) {
        self.x *= rhs;
        self.y *= rhs;
        self.z *= rhs;
        self.w *= rhs;
    }
}

// Hadamard product Vec4 * Vec4
impl<Unit: Copy, Space: Copy> Mul<Vec4<Unit, Space>> for Vec4<Unit, Space> {
    type Output = Self;
    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x * rhs.x,
            y: self.y * rhs.y,
            z: self.z * rhs.z,
            w: self.w * rhs.w,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> MulAssign<Vec4<Unit, Space>> for Vec4<Unit, Space> {
    #[inline]
    fn mul_assign(&mut self, rhs: Self) {
        self.x *= rhs.x;
        self.y *= rhs.y;
        self.z *= rhs.z;
        self.w *= rhs.w;
    }
}

impl<Unit: Copy, Space: Copy> Div<f32> for Vec4<Unit, Space> {
    type Output = Self;
    #[inline]
    fn div(self, rhs: f32) -> Self::Output {
        let inv_rhs = 1.0 / rhs;
        Self {
            x: self.x * inv_rhs,
            y: self.y * inv_rhs,
            z: self.z * inv_rhs,
            w: self.w * inv_rhs,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> DivAssign<f32> for Vec4<Unit, Space> {
    #[inline]
    fn div_assign(&mut self, rhs: f32) {
        let inv_rhs = 1.0 / rhs;
        self.x *= inv_rhs;
        self.y *= inv_rhs;
        self.z *= inv_rhs;
        self.w *= inv_rhs;
    }
}

// Hadamard division Vec4 / Vec4
impl<Unit: Copy, Space: Copy> Div<Vec4<Unit, Space>> for Vec4<Unit, Space> {
    type Output = Self;
    #[inline]
    fn div(self, rhs: Self) -> Self::Output {
        Self {
            x: self.x / rhs.x,
            y: self.y / rhs.y,
            z: self.z / rhs.z,
            w: self.w / rhs.w,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}

impl<Unit: Copy, Space: Copy> DivAssign<Vec4<Unit, Space>> for Vec4<Unit, Space> {
    #[inline]
    fn div_assign(&mut self, rhs: Self) {
        self.x /= rhs.x;
        self.y /= rhs.y;
        self.z /= rhs.z;
        self.w /= rhs.w;
    }
}

impl<Unit: Copy, Space: Copy> Neg for Vec4<Unit, Space> {
    type Output = Self;
    #[inline]
    fn neg(self) -> Self::Output {
        Self {
            x: -self.x,
            y: -self.y,
            z: -self.z,
            w: -self.w,
            _unit: PhantomData,
            _space: PhantomData,
        }
    }
}