diff --git a/src/matrixmania/__init__.py b/src/matrixmania/__init__.py index 2201c3b..8c09bb0 100644 --- a/src/matrixmania/__init__.py +++ b/src/matrixmania/__init__.py @@ -1 +1 @@ -from .compute import matmul, project_ortho, rot_2D, rot_3D, transpose \ No newline at end of file +from .compute import matmul, project_ortho, project_perspective, rot_2D, rot_3D, transpose \ No newline at end of file diff --git a/src/matrixmania/compute.py b/src/matrixmania/compute.py index 81359fa..6c2c354 100644 --- a/src/matrixmania/compute.py +++ b/src/matrixmania/compute.py @@ -151,6 +151,39 @@ def project_ortho( +def project_perspective( + point: tuple[float, float, float], + focal_length: float = 1.0, + scale: float = 1.0, + camera_distance: float = 4.0, +) -> tuple[float, float]: + """ + Projiziert einen 3D-Punkt perspektivisch auf die Bildschirmebene. + + Weiter entfernte Punkte erscheinen kleiner, da x und y durch die Tiefe + des Punktes geteilt werden: + x' = x * focal_length / (z + camera_distance) * scale + y' = y * focal_length / (z + camera_distance) * scale + + :param point: 3D-Punkt als Tupel (x, y, z) + :param focal_length: Brennweite, steuert die Stärke der Perspektive + :param scale: Skalierungsfaktor für den projizierten Punkt + :param camera_distance: Abstand der Kamera zum Ursprung entlang der z-Achse + :return: Projizierter 2D-Punkt als Tupel (x, y) + :raises ValueError: Wenn z + camera_distance kleiner oder gleich 0 ist, + der Punkt also auf Höhe der Kamera oder hinter ihr liegt + """ + x, y, z = point + depth = z + camera_distance + if depth <= 0: + raise ValueError( + f"Der Punkt liegt nicht vor der Kamera (z + camera_distance = {depth})" + ) + factor = focal_length / depth * scale + return x * factor, y * factor + + + if __name__ == "__main__": matrix_a = [ [3, 4, -1, 4], diff --git a/test/test_matrixmania/test_projection.py b/test/test_matrixmania/test_projection.py index 47b1bce..7733dc7 100644 --- a/test/test_matrixmania/test_projection.py +++ b/test/test_matrixmania/test_projection.py @@ -1,4 +1,6 @@ -from matrixmania import project_ortho +import pytest + +from matrixmania import project_ortho, project_perspective def test_project_ortho_without_scale(): @@ -23,4 +25,28 @@ def test_project_ortho_with_scale_100(): result = project_ortho(point, scale=scale) # Assert - assert result == expected \ No newline at end of file + assert result == expected + + +def test_project_perspective_without_scale(): + # Arrange + point = (1.0, 2.0, 3.0) + expected = (1 / 7, 2 / 7) + + # Act + result = project_perspective(point, focal_length=1, scale=1) + + # Assert + assert result == pytest.approx(expected) + + +def test_project_perspective_with_scale_100_and_focal_length_2(): + # Arrange + point = (1.0, 2.0, 3.0) + expected = (200 / 7, 400 / 7) + + # Act + result = project_perspective(point, focal_length=2, scale=100) + + # Assert + assert result == pytest.approx(expected) \ No newline at end of file