Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from geometry import Point
- from matrix import Matrix, MatrixFromList, MatrixFromPoint
- import math
- from polygon import Polygon
- class Scene:
- def __init__(self):
- self.modelMatrices = [identity()]
- self.vertices = []
- self.lines = []
- self.polys = []
- def pushMatrix(self):
- self.modelMatrices.append(self.modelMatrices[-1].copy())
- def popMatrix(self):
- self.modelMatrices.pop()
- def translate(self, x,y,z):
- self.modelMatrices[-1] *= getTranslateMatrix(x,y,z)
- def scale(self, x,y,z):
- self.modelMatrices[-1]*= getScaleMatrix(x,y,z)
- def rotate(self, angle, x, y, z):
- self.modelMatrices[-1] *= getRotationMatrix(angle, x, y, z)
- def vertex(self, p):
- v = MatrixFromPoint(p)
- v = self.modelMatrices[-1] * v
- self.vertices.append(v)
- def line(self, p1, p2):
- p1 = self.modelMatrices[-1] * MatrixFromPoint(p1)
- p2 = self.modelMatrices[-1] * MatrixFromPoint(p2)
- self.lines.append((p1, p2))
- def polygon(self, *points, **kargs):
- points = [self.modelMatrices[-1] * MatrixFromPoint(p) for p in points]
- self.polys.append(Polygon(points, **kargs))
- def projected(self):
- """
- outputs a dict containing the projected elements of the scene.
- keys are: "vertices", "lines", "triangles"
- """
- projection = getProjectionMatrix(-1, 1, -1, 1, 2, 10)
- ret = {}
- ret["vertices"] = [projection * v for v in self.vertices]
- ret["lines"] = [[projection * p for p in l] for l in self.lines]
- ret["polygons"] = [poly.mult(projection) for poly in self.polys]
- return ret
- def identity():
- return MatrixFromList([
- [1,0,0,0],
- [0,1,0,0],
- [0,0,1,0],
- [0,0,0,1]
- ])
- def getTranslateMatrix(x,y,z):
- return MatrixFromList([
- [1,0,0,x],
- [0,1,0,y],
- [0,0,1,z],
- [0,0,0,1]
- ])
- def getScaleMatrix(x,y,z):
- return MatrixFromList([
- [x,0,0,0],
- [0,y,0,0],
- [0,0,z,0],
- [0,0,0,1]
- ])
- def getRotationMatrix(angle, x, y, z):
- c = math.cos(angle)
- s = math.sin(angle)
- m = Matrix(4,4)
- #magic values courtesy of:
- #http://www.opengl.org/sdk/docs/man2/xhtml/glRotate.xml
- return MatrixFromList([
- [x*x*(1-c)+c , x*y*(1-c)-z*s, x*z*(1-c)+y*s, 0],
- [y*x*(1-c)+z*s, y*y*(1-c)+c , y*z*(1-c)-x*s, 0],
- [x*z*(1-c)-y*s, y*z*(1-c)+x*s, z*z*(1-c)+c , 0],
- [0 , 0 , 0 , 1]
- ])
- def getProjectionMatrix(left, right, bottom, top, near, far):
- left, right, bottom, top, near, far = map(float, [left, right, bottom, top, near, far])
- a = (right + left) / (right - left)
- b = (top + bottom) / (top - bottom)
- c = -(far + near) / (far - near)
- d = -(2*far*near)/(far-near)
- p = 2 * near / (right - left)
- q = 2 * near / (top - bottom)
- return MatrixFromList([
- [p,0, a,0],
- [0,q, b,0],
- [0,0, c,d],
- [0,0,-1,0]
- ])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement