Skip to content

Commit

Permalink
add some operators and utility funcs to BaseVector
Browse files Browse the repository at this point in the history
  • Loading branch information
duncathan committed Dec 13, 2023
1 parent 9dee21c commit f9f5738
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/retro_data_structures/properties/base_vector.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
from __future__ import annotations

import copy
import dataclasses
import functools
import math
from typing import Any

# ruff: noqa: TCH002
from typing_extensions import Self

from retro_data_structures.properties.base_property import BaseProperty

Expand All @@ -24,3 +31,65 @@ def to_json(self) -> dict:

def dependencies_for(self, asset_manager):
yield from []

def __add__(self, other: BaseVector) -> Self:
return self.__class__(self.x + other.x, self.y + other.y, self.z + other.z)

def __sub__(self, other: BaseVector) -> Self:
return self.__class__(self.x - other.x, self.y - other.y, self.z - other.z)

@functools.singledispatchmethod
def __mul__(self, other: Any) -> Self:
raise TypeError

@__mul__.register
def _(self, scalar: int | float) -> Self:
return self.__class__(self.x * scalar, self.y * scalar, self.z * scalar)

@__mul__.register
def _(self, vector: BaseVector) -> Self:
return self.__class__(self.x * vector.x, self.y * vector.y, self.z * vector.z)

@functools.singledispatchmethod
def __truediv__(self, other: Any) -> Self:
raise TypeError

@__truediv__.register
def _(self, scalar: int | float) -> Self:
return self.__class__(self.x / scalar, self.y / scalar, self.z / scalar)

@__truediv__.register
def _(self, vector: BaseVector) -> Self:
return self.__class__(self.x / vector.x, self.y / vector.y, self.z / vector.z)

@functools.singledispatchmethod
def __floordiv__(self, other: Any) -> Self:
raise TypeError

@__floordiv__.register
def _(self, scalar: int | float) -> Self:
return self.__class__(self.x // scalar, self.y // scalar, self.z // scalar)

@__floordiv__.register
def _(self, vector: BaseVector) -> Self:
return self.__class__(self.x // vector.x, self.y // vector.y, self.z // vector.z)

def rotate(self, rotation: BaseVector, center: BaseVector | None = None) -> Self:
if center is None:
center = BaseVector()

pos = [self.x - center.x, self.y - center.y, self.z - center.z]

for i in range(3):
theta = rotation[i] * math.pi / 180.0
sin = math.sin(theta)
cos = math.cos(theta)

old_pos = copy.copy(pos)

comp1 = (i + 1) % 3
comp2 = (i + 2) % 3
pos[comp1] = old_pos[comp1] * cos - old_pos[comp2] * sin
pos[comp2] = old_pos[comp1] * sin + old_pos[comp2] * cos

return self.__class__(pos[0], pos[1], pos[2]) + center

0 comments on commit f9f5738

Please sign in to comment.