• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*!
2 # glam
3 
4 `glam` is a simple and fast linear algebra library for games and graphics.
5 
6 ## Features
7 
8 * [`f32`](mod@f32) types
9   * vectors: [`Vec2`], [`Vec3`], [`Vec3A`] and [`Vec4`]
10   * square matrices: [`Mat2`], [`Mat3`], [`Mat3A`] and [`Mat4`]
11   * a quaternion type: [`Quat`]
12   * affine transformation types: [`Affine2`] and [`Affine3A`]
13 * [`f64`](mod@f64) types
14   * vectors: [`DVec2`], [`DVec3`] and [`DVec4`]
15   * square matrices: [`DMat2`], [`DMat3`] and [`DMat4`]
16   * a quaternion type: [`DQuat`]
17   * affine transformation types: [`DAffine2`] and [`DAffine3`]
18 * [`i32`](mod@i32) types
19   * vectors: [`IVec2`], [`IVec3`] and [`IVec4`]
20 * [`u32`](mod@u32) types
21   * vectors: [`UVec2`], [`UVec3`] and [`UVec4`]
22 * [`bool`](mod@bool) types
23   * vectors: [`BVec2`], [`BVec3`] and [`BVec4`]
24 
25 ## SIMD
26 
27 `glam` is built with SIMD in mind. Many `f32` types use 128-bit SIMD vector types for storage
28 and/or implementation. The use of SIMD generally enables better performance than using primitive
29 numeric types such as `f32`.
30 
31 Some `glam` types use SIMD for storage meaning they are 16 byte aligned, these types include
32 `Mat2`, `Mat3A`, `Mat4`, `Quat`, `Vec3A`, `Vec4`, `Affine2` an `Affine3A`. Types
33 with an `A` suffix are a SIMD alternative to a scalar type, e.g. `Vec3` uses `f32` storage and
34 `Vec3A` uses SIMD storage.
35 
36 When SIMD is not available on the target the types will maintain 16 byte alignment and internal
37 padding so that object sizes and layouts will not change between architectures. There are scalar
38 math fallback implementations exist when SIMD is not available. It is intended to add support for
39 other SIMD architectures once they appear in stable Rust.
40 
41 Currently only SSE2 on x86/x86_64 is supported as this is what stable Rust supports.
42 
43 ## Vec3A and Mat3A
44 
45 `Vec3A` is a SIMD optimized version of the `Vec3` type, which due to 16 byte alignment results
46 in `Vec3A` containing 4 bytes of padding making it 16 bytes in size in total. `Mat3A` is composed
47 of three `Vec3A` columns.
48 
49 | Type       | `f32` bytes | Align bytes | Size bytes | Padding |
50 |:-----------|------------:|------------:|-----------:|--------:|
51 |[`Vec3`]    |           12|            4|          12|        0|
52 |[`Vec3A`]   |           12|           16|          16|        4|
53 |[`Mat3`]    |           36|            4|          36|        0|
54 |[`Mat3A`]   |           36|           16|          48|       12|
55 
56 Despite this wasted space the SIMD implementations tend to outperform `f32` implementations in
57 [**mathbench**](https://github.com/bitshifter/mathbench-rs) benchmarks.
58 
59 `glam` treats [`Vec3`] as the default 3D vector type and [`Vec3A`] a special case for optimization.
60 When methods need to return a 3D vector they will generally return [`Vec3`].
61 
62 There are [`From`] trait implementations for converting from [`Vec4`] to a [`Vec3A`] and between
63 [`Vec3`] and [`Vec3A`] (and vice versa).
64 
65 ```
66 use glam::{Vec3, Vec3A, Vec4};
67 
68 let v4 = Vec4::new(1.0, 2.0, 3.0, 4.0);
69 
70 // Convert from `Vec4` to `Vec3A`, this is a no-op if SIMD is supported.
71 let v3a = Vec3A::from(v4);
72 assert_eq!(Vec3A::new(1.0, 2.0, 3.0), v3a);
73 
74 // Convert from `Vec3A` to `Vec3`.
75 let v3 = Vec3::from(v3a);
76 assert_eq!(Vec3::new(1.0, 2.0, 3.0), v3);
77 
78 // Convert from `Vec3` to `Vec3A`.
79 let v3a = Vec3A::from(v3);
80 assert_eq!(Vec3A::new(1.0, 2.0, 3.0), v3a);
81 ```
82 
83 ## Affine2 and Affine3A
84 
85 `Affine2` and `Affine3A` are composed of a linear transform matrix and a vector translation. The
86 represent 2D and 3D affine transformations which are commonly used in games.
87 
88 The table below shows the performance advantage of `Affine2` over `Mat3A` and `Mat3A` over `Mat3`.
89 
90 | operation          | `Mat3`      | `Mat3A`    | `Affine2`  |
91 |--------------------|-------------|------------|------------|
92 | inverse            | 11.4±0.09ns | 7.1±0.09ns | 5.4±0.06ns |
93 | mul self           | 10.5±0.04ns | 5.2±0.05ns | 4.0±0.05ns |
94 | transform point2   |  2.7±0.02ns | 2.7±0.03ns | 2.8±0.04ns |
95 | transform vector2  |  2.6±0.01ns | 2.6±0.03ns | 2.3±0.02ns |
96 
97 Performance is much closer between `Mat4` and `Affine3A` with the affine type being faster to
98 invert.
99 
100 | operation          | `Mat4`      | `Affine3A`  |
101 |--------------------|-------------|-------------|
102 | inverse            | 15.9±0.11ns | 10.8±0.06ns |
103 | mul self           |  7.3±0.05ns |  7.0±0.06ns |
104 | transform point3   |  3.6±0.02ns |  4.3±0.04ns |
105 | transform point3a  |  3.0±0.02ns |  3.0±0.04ns |
106 | transform vector3  |  4.1±0.02ns |  3.9±0.04ns |
107 | transform vector3a |  2.8±0.02ns |  2.8±0.02ns |
108 
109 Benchmarks were taken on an Intel Core i7-4710HQ.
110 
111 ## Linear algebra conventions
112 
113 `glam` interprets vectors as column matrices (also known as column vectors) meaning when
114 transforming a vector with a matrix the matrix goes on the left.
115 
116 ```
117 use glam::{Mat3, Vec3};
118 let m = Mat3::IDENTITY;
119 let x = Vec3::X;
120 let v = m * x;
121 assert_eq!(v, x);
122 ```
123 
124 Matrices are stored in memory in column-major order.
125 
126 All angles are in radians. Rust provides the `f32::to_radians()` and `f64::to_radians()` methods to
127 convert from degrees.
128 
129 ## Direct element access
130 
131 Because some types may internally be implemented using SIMD types, direct access to vector elements
132 is supported by implementing the [`Deref`] and [`DerefMut`] traits.
133 
134 ```
135 use glam::Vec3A;
136 let mut v = Vec3A::new(1.0, 2.0, 3.0);
137 assert_eq!(3.0, v.z);
138 v.z += 1.0;
139 assert_eq!(4.0, v.z);
140 ```
141 
142 [`Deref`]: https://doc.rust-lang.org/std/ops/trait.Deref.html
143 [`DerefMut`]: https://doc.rust-lang.org/std/ops/trait.DerefMut.html
144 
145 ## glam assertions
146 
147 `glam` does not enforce validity checks on method parameters at runtime. For example methods that
148 require normalized vectors as input such as `Quat::from_axis_angle(axis, angle)` will not check
149 that axis is a valid normalized vector. To help catch unintended misuse of `glam` the
150 `debug-glam-assert` or `glam-assert` features can be enabled to add checks ensure that inputs to
151 are valid.
152 
153 ## Vector swizzles
154 
155 `glam` vector types have functions allowing elements of vectors to be reordered, this includes
156 creating a vector of a different size from the vectors elements.
157 
158 The swizzle functions are implemented using traits to add them to each vector type. This is
159 primarily because there are a lot of swizzle functions which can obfuscate the other vector
160 functions in documentation and so on. The traits are [`Vec2Swizzles`], [`Vec3Swizzles`] and
161 [`Vec4Swizzles`].
162 
163 Note that the [`Vec3Swizzles`] implementation for [`Vec3A`] will return a [`Vec3A`] for 3 element
164 swizzles, all other implementations will return [`Vec3`].
165 
166 ```
167 use glam::{swizzles::*, Vec2, Vec3, Vec3A, Vec4};
168 
169 let v = Vec4::new(1.0, 2.0, 3.0, 4.0);
170 
171 // Reverse elements of `v`, if SIMD is supported this will use a vector shuffle.
172 let wzyx = v.wzyx();
173 assert_eq!(Vec4::new(4.0, 3.0, 2.0, 1.0), wzyx);
174 
175 // Swizzle the yzw elements of `v` into a `Vec3`
176 let yzw = v.yzw();
177 assert_eq!(Vec3::new(2.0, 3.0, 4.0), yzw);
178 
179 // To swizzle a `Vec4` into a `Vec3A` swizzle the `Vec4` first then convert to
180 // `Vec3A`. If SIMD is supported this will use a vector shuffle. The last
181 // element of the shuffled `Vec4` is ignored by the `Vec3A`.
182 let yzw = Vec3A::from(v.yzwx());
183 assert_eq!(Vec3A::new(2.0, 3.0, 4.0), yzw);
184 
185 // You can swizzle from a `Vec4` to a `Vec2`
186 let xy = v.xy();
187 assert_eq!(Vec2::new(1.0, 2.0), xy);
188 
189 // And back again
190 let yyxx = xy.yyxx();
191 assert_eq!(Vec4::new(2.0, 2.0, 1.0, 1.0), yyxx);
192 ```
193 
194 ## SIMD and scalar consistency
195 
196 `glam` types implement `serde` `Serialize` and `Deserialize` traits to ensure
197 that they will serialize and deserialize exactly the same whether or not
198 SIMD support is being used.
199 
200 The SIMD versions implement the `core::fmt::Debug` and `core::fmt::Display`
201 traits so they print the same as the scalar version.
202 
203 ```
204 use glam::Vec4;
205 let a = Vec4::new(1.0, 2.0, 3.0, 4.0);
206 assert_eq!(format!("{}", a), "[1, 2, 3, 4]");
207 ```
208 
209 ## Feature gates
210 
211 All `glam` dependencies are optional, however some are required for tests
212 and benchmarks.
213 
214 * `std` - the default feature, has no dependencies.
215 * `approx` - traits and macros for approximate float comparisons
216 * `bytemuck` - for casting into slices of bytes
217 * `libm` - required to compile with `no_std`
218 * `mint` - for interoperating with other 3D math libraries
219 * `num-traits` - required to compile `no_std`, will be included when enabling
220   the `libm` feature
221 * `rand` - implementations of `Distribution` trait for all `glam` types.
222 * `rkyv` - implementations of `Archive`, `Serialize` and `Deserialize` for all
223   `glam` types. Note that serialization is not interoperable with and without the
224   `scalar-math` feature. It should work between all other builds of `glam`.
225   Endian conversion is currently not supported
226 * `bytecheck` - to perform archive validation when using the `rkyv` feature
227 * `serde` - implementations of `Serialize` and `Deserialize` for all `glam`
228   types. Note that serialization should work between builds of `glam` with and without SIMD enabled
229 * `scalar-math` - disables SIMD support and uses native alignment for all types.
230 * `debug-glam-assert` - adds assertions in debug builds which check the validity of parameters
231   passed to `glam` to help catch runtime errors.
232 * `glam-assert` - adds assertions to all builds which check the validity of parameters passed to
233   `glam` to help catch runtime errors.
234 * `cuda` - forces `glam` types to match expected cuda alignment
235 * `fast-math` - By default, glam attempts to provide bit-for-bit identical
236   results on all platforms. Using this feature will enable platform specific
237   optimizations that may not be identical to other platforms. **Intermediate
238   libraries should not use this feature and defer the decision to the final
239   binary build**.
240 * `core-simd` - enables SIMD support via the portable simd module. This is an
241   unstable feature which requires a nightly Rust toolchain and `std` support.
242 
243 ## Minimum Supported Rust Version (MSRV)
244 
245 The minimum supported Rust version is `1.58.1`.
246 
247 */
248 #![doc(html_root_url = "https://docs.rs/glam/0.23.0")]
249 #![cfg_attr(not(feature = "std"), no_std)]
250 #![cfg_attr(target_arch = "spirv", feature(repr_simd))]
251 #![deny(
252     rust_2018_compatibility,
253     rust_2018_idioms,
254     future_incompatible,
255     nonstandard_style
256 )]
257 // clippy doesn't like `to_array(&self)`
258 #![allow(clippy::wrong_self_convention)]
259 #![cfg_attr(
260     all(feature = "core-simd", not(feature = "scalar-math")),
261     feature(portable_simd)
262 )]
263 
264 #[macro_use]
265 mod macros;
266 
267 mod align16;
268 mod deref;
269 mod euler;
270 mod features;
271 mod float_ex;
272 
273 #[cfg(target_arch = "spirv")]
274 mod spirv;
275 
276 #[cfg(all(
277     target_feature = "sse2",
278     not(any(feature = "core-simd", feature = "scalar-math"))
279 ))]
280 mod sse2;
281 
282 #[cfg(all(
283     target_feature = "simd128",
284     not(any(feature = "core-simd", feature = "scalar-math"))
285 ))]
286 mod wasm32;
287 
288 #[cfg(all(feature = "core-simd", not(feature = "scalar-math")))]
289 mod coresimd;
290 
291 #[cfg(all(
292     target_feature = "sse2",
293     not(any(feature = "core-simd", feature = "scalar-math"))
294 ))]
295 use align16::Align16;
296 
297 use float_ex::FloatEx;
298 
299 /** `bool` vector mask types. */
300 pub mod bool;
301 pub use self::bool::*;
302 
303 /** `f32` vector, quaternion and matrix types. */
304 pub mod f32;
305 pub use self::f32::*;
306 
307 /** `f64` vector, quaternion and matrix types. */
308 pub mod f64;
309 pub use self::f64::*;
310 
311 /** `i32` vector types. */
312 pub mod i32;
313 pub use self::i32::*;
314 
315 /** `u32` vector types. */
316 pub mod u32;
317 pub use self::u32::*;
318 
319 /** Traits adding swizzle methods to all vector types. */
320 pub mod swizzles;
321 pub use self::swizzles::{Vec2Swizzles, Vec3Swizzles, Vec4Swizzles};
322 
323 /** Rotation Helper */
324 pub use euler::EulerRot;
325