Skip to main content

mlua/
vector.rs

1use std::fmt;
2
3#[cfg(feature = "serde")]
4use serde::ser::{Serialize, SerializeTupleStruct, Serializer};
5
6/// A Luau vector type.
7///
8/// By default vectors are 3-dimensional, but can be 4-dimensional
9/// if the `luau-vector4` feature is enabled.
10#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
11#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd)]
12pub struct Vector(pub(crate) [f32; Self::SIZE]);
13
14impl fmt::Display for Vector {
15    #[rustfmt::skip]
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        #[cfg(not(feature = "luau-vector4"))]
18        return write!(f, "vector({}, {}, {})", self.x(), self.y(), self.z());
19        #[cfg(feature = "luau-vector4")]
20        return write!(f, "vector({}, {}, {}, {})", self.x(), self.y(), self.z(), self.w());
21    }
22}
23
24#[cfg_attr(not(feature = "luau"), allow(unused))]
25impl Vector {
26    pub(crate) const SIZE: usize = if cfg!(feature = "luau-vector4") { 4 } else { 3 };
27
28    /// Creates a new vector.
29    #[cfg(not(feature = "luau-vector4"))]
30    pub const fn new(x: f32, y: f32, z: f32) -> Self {
31        Self([x, y, z])
32    }
33
34    /// Creates a new vector.
35    #[cfg(feature = "luau-vector4")]
36    pub const fn new(x: f32, y: f32, z: f32, w: f32) -> Self {
37        Self([x, y, z, w])
38    }
39
40    /// Creates a new vector with all components set to `0.0`.
41    pub const fn zero() -> Self {
42        Self([0.0; Self::SIZE])
43    }
44
45    /// Returns 1st component of the vector.
46    pub const fn x(&self) -> f32 {
47        self.0[0]
48    }
49
50    /// Returns 2nd component of the vector.
51    pub const fn y(&self) -> f32 {
52        self.0[1]
53    }
54
55    /// Returns 3rd component of the vector.
56    pub const fn z(&self) -> f32 {
57        self.0[2]
58    }
59
60    /// Returns 4th component of the vector.
61    #[cfg(any(feature = "luau-vector4", doc))]
62    #[cfg_attr(docsrs, doc(cfg(feature = "luau-vector4")))]
63    pub const fn w(&self) -> f32 {
64        self.0[3]
65    }
66}
67
68#[cfg(feature = "serde")]
69impl Serialize for Vector {
70    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
71        let mut ts = serializer.serialize_tuple_struct("Vector", Self::SIZE)?;
72        ts.serialize_field(&self.x())?;
73        ts.serialize_field(&self.y())?;
74        ts.serialize_field(&self.z())?;
75        #[cfg(feature = "luau-vector4")]
76        ts.serialize_field(&self.w())?;
77        ts.end()
78    }
79}
80
81impl PartialEq<[f32; Self::SIZE]> for Vector {
82    #[inline]
83    fn eq(&self, other: &[f32; Self::SIZE]) -> bool {
84        self.0 == *other
85    }
86}
87
88#[cfg(feature = "luau")]
89impl crate::types::LuaType for Vector {
90    const TYPE_ID: std::os::raw::c_int = ffi::LUA_TVECTOR;
91}