Skip to content

Instantly share code, notes, and snippets.

@rubber-duck
Last active December 18, 2015 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubber-duck/5725536 to your computer and use it in GitHub Desktop.
Save rubber-duck/5725536 to your computer and use it in GitHub Desktop.
pub use self::_vec2::vec2;
pub use self::_vec3::vec3;
pub use self::_vec4::vec4;
macro_rules! impl_vec_dot(
($x: ident, $y: ident, $z: ident, $w: ident) => ( x.$x * y.$x + x.$y * y.$y + x.$z * y.$z + x.$w * y.$w );
($x: ident, $y: ident, $z: ident) => ( x.$x * y.$x + x.$y * y.$y + x.$z * y.$z );
($x: ident, $y: ident) => ( x.$x * y.$x + x.$y * y.$y );
)
macro_rules! impl_vv_op(
($optr: ident, $op: ident, $vt: ident, $($comp: ident)+) => (
impl $optr<$vt, $vt> for $vt {
fn $op(&self, other: &$vt) -> $vt {
$vt { $( $comp: self.$comp.$op(&other.$comp) ),+ }
}
}
);
)
macro_rules! define_vec (
($vt: ident, $vmod: ident, $ct: ident, $($comp: ident),+) => (
mod $vmod {
struct $vt { $($comp : $ct),+ }
impl $vt {
#[inline(always)]
pub fn new($($comp: $ct),+) -> $vt {
$vt { $($comp: $comp),+ }
}
#[inline(always)]
pub fn from_value(v: $ct) -> $vt {
$vt { $($comp: v),+ }
}
#[inline(always)]
pub fn zero() -> $vt {
$vt { $($comp: 0 as $ct),+ }
}
#[inline(always)]
pub fn dot(x: &$vt, y: &$vt) -> $ct {
impl_vec_dot!($($comp),+)
}
#[inline(always)]
pub fn length(x: &$vt) -> $ct {
$vt::dot(x, x).sqrt()
}
#[inline(always)]
pub fn normalize(x: &$vt) -> $vt {
let invl = (1 as $ct) / $vt::length(x);
$vt { $($comp: x.$comp * invl),+ }
}
}
impl_vv_op!(Add, add, $vt, $( $comp )+)
impl_vv_op!(Sub, sub, $vt, $( $comp )+)
impl_vv_op!(Mul, mul, $vt, $( $comp )+)
impl_vv_op!(Div, div, $vt, $( $comp )+)
// Implement because #[deriving()] is broken inside macro (issue #6976)
impl ToStr for $vt {
fn to_str(&self) -> ~str {
[$(self.$comp),+].to_str()
}
}
}
);
)
define_vec!(vec2, _vec2, f32, x, y)
define_vec!(vec3, _vec3, f32, x, y, z)
define_vec!(vec4, _vec4, f32, x, y, z, w)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment