156 lines
3.0 KiB
Rust

use std::ops::{Add, Sub, Mul, Div, Neg, Index, IndexMut};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct Vec2(pub [f32; 2]);
impl Vec2 {
pub const fn new(x: f32, y: f32) -> Self {
Self([x, y])
}
pub const fn zero() -> Self {
Self([0.0, 0.0])
}
pub const fn one() -> Self {
Self([1.0, 1.0])
}
pub fn x(&self) -> f32 {
self.0[0]
}
pub fn y(&self) -> f32 {
self.0[1]
}
pub fn x_mut(&mut self) -> &mut f32 {
&mut self.0[0]
}
pub fn y_mut(&mut self) -> &mut f32 {
&mut self.0[1]
}
pub fn length_squared(&self) -> f32 {
self.0[0] * self.0[0] + self.0[1] * self.0[1]
}
pub fn length(&self) -> f32 {
self.length_squared().sqrt()
}
pub fn normalize(&self) -> Self {
let len = self.length();
if len == 0.0 {
return *self;
}
Self([self.0[0] / len, self.0[1] / len])
}
pub fn dot(&self, other: &Self) -> f32 {
self.0[0] * other.0[0] + self.0[1] * other.0[1]
}
pub fn as_ptr(&self) -> *const f32 {
self.0.as_ptr()
}
pub fn as_mut_ptr(&mut self) -> *mut f32 {
self.0.as_mut_ptr()
}
}
// Add operations
impl Add for Vec2 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self([self.0[0] + rhs.0[0], self.0[1] + rhs.0[1]])
}
}
impl Add<f32> for Vec2 {
type Output = Self;
fn add(self, rhs: f32) -> Self::Output {
Self([self.0[0] + rhs, self.0[1] + rhs])
}
}
// Subtraction operations
impl Sub for Vec2 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self([self.0[0] - rhs.0[0], self.0[1] - rhs.0[1]])
}
}
impl Sub<f32> for Vec2 {
type Output = Self;
fn sub(self, rhs: f32) -> Self::Output {
Self([self.0[0] - rhs, self.0[1] - rhs])
}
}
// Multiplication operations
impl Mul for Vec2 {
type Output = Self;
fn mul(self, rhs: Self) -> Self::Output {
Self([self.0[0] * rhs.0[0], self.0[1] * rhs.0[1]])
}
}
impl Mul<f32> for Vec2 {
type Output = Self;
fn mul(self, rhs: f32) -> Self::Output {
Self([self.0[0] * rhs, self.0[1] * rhs])
}
}
// Division operations
impl Div for Vec2 {
type Output = Self;
fn div(self, rhs: Self) -> Self::Output {
Self([self.0[0] / rhs.0[0], self.0[1] / rhs.0[1]])
}
}
impl Div<f32> for Vec2 {
type Output = Self;
fn div(self, rhs: f32) -> Self::Output {
Self([self.0[0] / rhs, self.0[1] / rhs])
}
}
// Negation
impl Neg for Vec2 {
type Output = Self;
fn neg(self) -> Self::Output {
Self([-self.0[0], -self.0[1]])
}
}
// Index operations
impl Index<usize> for Vec2 {
type Output = f32;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl IndexMut<usize> for Vec2 {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}