v_math.py

Created by valmontechno

Created on June 12, 2024

2.61 KB


from math import *

QUARTER_CIRCLE = pi / 2
HALF_CIRCLE = pi
CIRCLE = pi * 2

class Vector2:
    screenWidth, screenHeight = None, None
    @classmethod
    def setScreenSize(cls, width:int, height:int):
        cls.screenWidth, cls.screenHeight = width, height
        cls.screenRatio = cls.screenHeight / cls.screenWidth

    def __init__(self, x:float, y:float):
        self.x, self.y = x, y
    
    def toScreen(self):
        return Vector2(int((self.screenRatio*self.x+1)*self.screenWidth//2), int((-self.y+1)*self.screenHeight//2))

    def __str__(self):
        return '(' + str(self.x) + ', ' + str(self.y) + ')'
    
class Edge2:
    def __init__(self, v1:Vector2, v2:Vector2):
        self.v1, self.v2 = v1, v2

    def toScreen(self):
        return Edge2(self.v1.toScreen(), self.v2.toScreen())

    def __str__(self):
        return 'Edge2(' + str(self.v1) + ', ' + str(self.v2) + ')'

class Vector3:
    def __init__(self, x:float, y:float, z:float):
        self.x, self.y, self.z = x, y, z

    def add(self, v:'Vector3'):
        return Vector3(self.x+v.x, self.y+v.y, self.z+v.z)
    
    def sub(self, v:'Vector3'):
        return Vector3(self.x-v.x, self.y-v.y, self.z-v.z)
    
    def mulK(self, k:float):
        return Vector3(self.x*k, self.y*k, self.z*k)
    
    def opposite(self):
        return Vector3(-self.x, -self.y, -self.z)
    
    def rotationX(self, pitch:float):
        y = cos(pitch)*self.y-sin(pitch)*self.z
        z = sin(pitch)*self.y+cos(pitch)*self.z
        return Vector3(self.x, y, z)
    
    def rotationY(self, yaw:float):
        x = cos(yaw)*self.x+sin(yaw)*self.z
        z = -sin(yaw)*self.x+cos(yaw)*self.z
        return Vector3(x, self.y, z)

    def projection(self, focalLenth:float):
        return Vector2(focalLenth * self.x / self.z, focalLenth * self.y / self.z)

    def __str__(self):
        return '(' + str(self.x) + ', ' + str(self.y) + ', ' + str(self.z) + ')'

class Edge3:
    def __init__(self, v1:Vector3, v2:Vector3):
        self.v1, self.v2 = v1, v2

    def translate(self, v:Vector3):
        return Edge3(self.v1.add(v), self.v2.add(v))
    
    def rotationX(self, pitch:float):
        return Edge3(self.v1.rotationX(pitch), self.v2.rotationX(pitch))
    
    def rotationY(self, yaw:float):
        return Edge3(self.v1.rotationY(yaw), self.v2.rotationY(yaw))

    def projection(self, focalLenth:float):
        return Edge2(self.v1.projection(focalLenth), self.v2.projection(focalLenth))
    
    def __str__(self):
        return 'Edge3(' + str(self.v1) + ', ' + str(self.v2) + ')'
    
def dot3(v1:Vector3, v2:Vector3):
    return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z