[−][src]Module gramit::vec
Two, three, and four-dimensional real vectors with f32
components.
This module defines a trait Vector
for generic mathematical vectors, as well as three
default vector types useful for graphics programming: Vec2
, Vec3
, and Vec4
, vectors
in the 2, 3, and 4 dimensional real spaces respectively. To facilitate interfaces with common
graphics APIs, all three are represented as contiguous tuples of 32-bit floating point numbers.
The vector types defined here implement a full set of arithmetic operators on both scalars and other vectors:
let v1 = vec2!(1.0, 2.0); let v2 = vec2!(3.0, 4.0); // Between a vector and an `f32` scalar, we may: // Multiply (on either side) to scale the vector: assert_approx_eq!(2.0 * v1, vec2!(2.0, 4.0)); assert_approx_eq!(v1 * 2.0, vec2!(2.0, 4.0)); // ... or divide by the scalar: assert_approx_eq!(v1 / 2.0, vec2!(0.5, 1.0)); // Between two vectors, we can perform component-wise arithmetic: assert_approx_eq!(v1 + v2, vec2!(4.0, 6.0)); assert_approx_eq!(v1 - v2, vec2!(-2.0, -2.0)); assert_approx_eq!(v1 * v2, vec2!(3.0, 8.0)); assert_approx_eq!(v2 / v1, vec2!(3.0, 2.0)); // Arithmetic assignment operations are also defined for mutable vectors: let mut v1 = vec2!(4.0, 5.0); let mut v2 = vec2!(6.0, 7.0); v1 *= 2.0; assert_approx_eq!(v1, vec2!(8.0, 10.0)); v2 /= 2.0; assert_approx_eq!(v2, vec2!(3.0, 3.5)); v1 += v2; assert_approx_eq!(v1, vec2!(11.0, 13.5)); v2 -= v1; assert_approx_eq!(v2, vec2!(-8.0, -10.0)); v1 *= vec2!(0.5, 10.0); assert_approx_eq!(v1, vec2!(5.5, 135.0)); v2 /= vec2!(-4.0, 2.0); assert_approx_eq!(v2, vec2!(2.0, -5.0)); // Similar for `Vec3` and `Vec4`.
Variants of the arithmetic operators are defined for all (sane) combinations of references and
moves for their arguments, and all three vector types are Copy
. In most cases, it should be
uneccessary to explicitly reference or dereference vectors in order to perform arithmetic.
For convenience, gramit
defines the macros vec2
,
vec3
, and vec4
for creating new vectors.
Structs
Vec2 | |
Vec3 | |
Vec4 |
Traits
Vector | Generic vector operations. |
Functions
cross | A free function version of |
dot | A free function version of |
length | A free function version of |
normalize | A free function version of |
project | Project one vector onto another. |