Ive got this python code. It should project 8 cube corners. It doesn't tho:
import math
def setProjectionMatrix(angleOfView, near, far):
scale = 1 / math.tan(angleOfView * 0.5 * math.pi / 180)
M = [[scale, 0, 0, 0],
[0, scale, 0, 0],
[0, 0, -far / (far - near), -3],
[0, 0, 0, 0]]
return M
def multPointMatrix(vin, M):
x, y, z = vin
nx = x * M[0][0] + y * M[1][0] + z * M[2][0] + M[3][0]
ny = x * M[0][1] + y * M[1][1] + z * M[2][1] + M[3][1]
nz = x * M[0][2] + y * M[1][2] + z * M[2][2] + M[3][2]
w = x * M[0][3] + y * M[1][3] + z * M[2][3] + M[3][3]
if w != 1 and w != 0:
nx /= w
ny /= w
nz /= w
return nx, ny, nz
#Gets coordinates of cube points and add them to *vertices*
cubeSize = 20
x, y, z = (0, 0, 50)
sh = int(cubeSize / 2)
vertices = [(x + sh, y + sh, z - sh), (x + sh, y - sh, z - sh), (x - sh, y - sh, z - sh), (x - sh, y + sh, z - sh),
(x + sh, y + sh, z + sh), (x + sh, y - sh, z + sh), (x - sh, y - sh, z + sh), (x - sh, y + sh, z + sh)]
coords = [] #Coordinates
imageWidth = 512
imageHeight = 512
worldToCamera = [[0 for _ in range(4)] for _ in range(4)]
worldToCamera[3][1] = -10
worldToCamera[3][2] = -10
angleOfView = 90
near = 25
far = 75
projectionMatrix = setProjectionMatrix(angleOfView, near, far)
for v in vertices:
vertCam = multPointMatrix(v, worldToCamera)
projectedVert = multPointMatrix(vertCam, projectionMatrix)
x, y, z = projectedVert
if x < -1 or x > 1 or y < -1 or y > 1: continue
x = min(imageWidth - 1, int(((x + 1) * 0.5 * imageWidth)))
y = min(imageHeight - 1, int(((1 - (y + 1) * 0.5) * imageHeight)))
coords.append((x, y))
input(coords) #Input so the window doesn't close
Output:
[(256, 341), (256, 341), (256, 341), (256, 341), (256, 341), (256, 341), (256, 341), (256, 341)]
Why are all of the points the same and whats wrong? Changing the cubeSize, near and far variables does change the output, but its still all the same. This code is from scratch a pixel, but in python.