mlua/
vector.rs

1use std::fmt;
2
3#[cfg(feature = "serialize")]
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    #[doc(hidden)]
42    pub const fn zero() -> Self {
43        Self([0.0; Self::SIZE])
44    }
45
46    /// Returns 1st component of the vector.
47    pub const fn x(&self) -> f32 {
48        self.0[0]
49    }
50
51    /// Returns 2nd component of the vector.
52    pub const fn y(&self) -> f32 {
53        self.0[1]
54    }
55
56    /// Returns 3rd component of the vector.
57    pub const fn z(&self) -> f32 {
58        self.0[2]
59    }
60
61    /// Returns 4th component of the vector.
62    #[cfg(any(feature = "luau-vector4", doc))]
63    #[cfg_attr(docsrs, doc(cfg(feature = "luau-vector4")))]
64    pub const fn w(&self) -> f32 {
65        self.0[3]
66    }
67}
68
69#[cfg(feature = "serialize")]
70impl Serialize for Vector {
71    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
72        let mut ts = serializer.serialize_tuple_struct("Vector", Self::SIZE)?;
73        ts.serialize_field(&self.x())?;
74        ts.serialize_field(&self.y())?;
75        ts.serialize_field(&self.z())?;
76        #[cfg(feature = "luau-vector4")]
77        ts.serialize_field(&self.w())?;
78        ts.end()
79    }
80}
81
82impl PartialEq<[f32; Self::SIZE]> for Vector {
83    #[inline]
84    fn eq(&self, other: &[f32; Self::SIZE]) -> bool {
85        self.0 == *other
86    }
87}
88
89#[cfg(feature = "luau")]
90impl crate::types::LuaType for Vector {
91    const TYPE_ID: std::os::raw::c_int = ffi::LUA_TVECTOR;
92}