def level4_render(level): left = glfwGetKey(level.window, GLFW_KEY_LEFT) == GLFW_PRESS or \ glfwGetKey(level.window, GLFW_KEY_A) == GLFW_PRESS right = glfwGetKey(level.window, GLFW_KEY_RIGHT) == GLFW_PRESS or \ glfwGetKey(level.window, GLFW_KEY_D) == GLFW_PRESS backward = glfwGetKey(level.window, GLFW_KEY_DOWN) == GLFW_PRESS or \ glfwGetKey(level.window, GLFW_KEY_S) == GLFW_PRESS forward = glfwGetKey(level.window, GLFW_KEY_UP) == GLFW_PRESS or \ glfwGetKey(level.window, GLFW_KEY_W) == GLFW_PRESS up = glfwGetKey(level.window, GLFW_KEY_PAGE_UP) == GLFW_PRESS down = glfwGetKey(level.window, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS current_time = time() speed = (current_time - level.time_checkpoint)*3 if glfwGetKey(level.window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS: speed *= 2 if glfwGetKey(level.window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS: speed /= 2 if (left or right) and (backward or forward) and (up or down): speed /= sqrt(3.0) elif ((left or right) and (backward or forward)) or \ ((left or right) and (up or down)) or \ ((backward or forward) and (up or down)): speed /= sqrt(2.0) if left: v = vector_norm(array([level.orientation[0], level.orientation[1], 0, 0], dtype='float32')) v = rotate(pi/2).dot(v) try_to_move(lvl, level, -v[0]*speed, -v[1]*speed, start_x, start_y) if right: v = vector_norm(array([level.orientation[0], level.orientation[1], 0, 0], dtype='float32')) v = rotate(-pi/2).dot(v) try_to_move(lvl, level, -v[0]*speed, -v[1]*speed, start_x, start_y) if backward: v = vector_norm(array([level.orientation[0], level.orientation[1], 0, 0], dtype='float32')) v = rotate(pi).dot(v) try_to_move(lvl, level, v[0]*speed, v[1]*speed, start_x, start_y) if forward: v = vector_norm(array([level.orientation[0], level.orientation[1], 0, 0], dtype='float32')) try_to_move(lvl, level, v[0]*speed, v[1]*speed, start_x, start_y) if up: level.position[2] += speed if down: level.position[2] -= speed level.time_checkpoint = current_time # update view matrix (according to position and orientation) level.view = look_at(level.position[:3], add(level.position, level.orientation)[:3]) glUniformMatrix4fv(level.view_pos, 1, GL_FALSE, level.view) # update rotating model level.angle = -(level.time_start - time()) / 3 level.rotating_model = array([cos(level.angle), -sin(level.angle), 0, 0, sin(level.angle), cos(level.angle), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], dtype='float32').reshape(4, 4) glUniformMatrix4fv(level.rotating_model_pos, 1, GL_FALSE, level.rotating_model)
def turn(self, ang): self.curAng += ang if self.dir == 'Z': self.nodes.append( (translate(self.curPoint.tolist()[:-1]) ) # remove fourth coordinate ( rotate(a=[-90, 0, self.curAng]) # rotation order: x, y and z #(sphere(self.r)) (cylinder(self.r, self.h)))) else: self.nodes.append((translate(self.curPoint.tolist()[:-1]) ) # remove fourth coordinate ( rotate(a=self.curAng, v=self.axis) # entering the screen #(sphere(self.r)) (cylinder(self.r, self.h)))) if True: if self.dir == 'Z': ang = -ang self.curVector = self.rotFunc(self.curVector, ang) else: if not self.dir == 'Z': ang = -ang mat = matrix.rotate(ang, self.axis[0], self.axis[1], self.axis[2]) mat = mat.tolist() self.curVector = np.dot(self.curVector, mat) # update current position self.curPoint = np.add(self.curPoint, self.curVector)
def forward(self,distance): if distance <= 0: return self.h = distance if self.down: if self.rotVector is not None: t = self.position() m = self.rotMatrix if self.__mode == "standard": # move initial cylinder to x axis. m = matrix.dot(m, matrix.rotate(90,0,1,0)) m = matrix.dot(matrix.translate(t[0],t[1],t[2]), m).tolist() self.addNode(m) if self.showAxes: self.__drawAxes() else: if self.dir == 'Z': self.addNode2(ang = [-90, 0, self.curAng]) else: self.addNode2() # update current position self.curPoint = np.add(self.curPoint, self.h * self.heading()) if turtle.__fullDebug__: print("curPoint = %s" % self.position()) if turtle.__toDebug__: print(" forward = %d -> heading = %s" % (self.h, self.heading().tolist()[:-1]))
def apply_nut(self, pos): """ Nutation(章動) 適用 :param list pos: 適用前直角座標 :return list : 適用後直角座標 """ try: pos_np = np.matrix([pos]).transpose() return lmtx.rotate(self.r_mtx_n, pos_np).A1.tolist() except Exception as e: raise
def apply_prec(self, pos): """ Precession(歳差) 適用 :param list pos: 適用前直角座標 :return list : 適用後直角座標 """ try: pos_np = np.matrix([pos]).transpose() return lmtx.rotate(self.r_mtx_p, pos_np).A1.tolist() except Exception as e: raise
def rect_ec2eq(rect, eps): """ 直交座標:黄道座標 -> 赤道座標. :param list rect: 黄道直交座標 :param float eps: 黄道傾斜角 (Unit: rad) :return list : 赤道直交座標 """ try: mtx_rect = np.matrix([rect]).transpose() r_mtx = lmtx.r_x(-eps) return lmtx.rotate(r_mtx, mtx_rect).A1.tolist() except Exception as e: raise
def __drawAxes(self): r = self.r/8 if self.__mode == "standard": hx = self.h*0.8 hy = self.r*3 hz = self.r*3 else: hx = self.r*3 hy = self.r*3 hz = self.h*0.8 # draw the Z axis. c = np.add(self.curPoint, self.h*self.rotVector/2) m = matrix.dot(matrix.translate(c[0],c[1],c[2]), self.rotMatrix).tolist() self.addNode(m, [0,0,1], r, hz, False) # draw the Y axis. m = matrix.dot(self.rotMatrix, matrix.rotate(90,-1,0,0)) m = matrix.dot(matrix.translate(c[0],c[1],c[2]), m).tolist() self.addNode(m, [0,1,0], r, hy, False) # draw the X axis. m = matrix.dot(self.rotMatrix, matrix.rotate(90,0,1,0)) m = matrix.dot(matrix.translate(c[0],c[1],c[2]), m).tolist() self.addNode(m, [1,0,0], r, hx, False)
def pol2rect(pol, r): """ 極座標 -> 直交座標 :param list pol: 極座標 :return list : 直交座標 """ try: lmd, phi = pol r_mtx = lmtx.r_y(phi) r_mtx = lmtx.r_z(-lmd, r_mtx) return lmtx.rotate( r_mtx, np.matrix([[r], [0.0], [0.0]]) ).A1.tolist() except Exception as e: raise
def __turn(self,ang): self.rotVector = None self.curAng += ang if True: if self.dir == 'Z': ang = -ang self.curVector = self.rotFunc(self.curVector, ang ) else: if self.dir != 'Z': ang = -ang mat = matrix.rotate(ang, self.axis[0], self.axis[1], self.axis[2]) mat = mat.tolist() self.curVector = np.dot (self.curVector, mat) if turtle.__fullDebug__: print("curVector = %s" % self.curVector) print("curAng = %f\n" % self.curAng)
def main(argv=None): #vList = [Point(1.0/3,1.0/3,1.0/3), Point(2,3,-4), Point(-1,9,-7), Point(-5,-2,8)] #vList = [Point(-1,-1,1), Point(-1,-1,-1), Point(1,-1,-1), Point(1,-1,1)] size = 4 vList = [ Point(0, 0, 0), Point(size, 0, 0), Point(size, size, 0), Point(0, size, 0), Point(size, 0, 2 * size), Point(size, size, 2 * size) ] #edge = set([1,4]) vIndexes = [0, 1, 2, 3] vIndexes2 = [1, 4, 5, 2] poly = SelectablePoly(vList, vIndexes, 0) poly2 = SelectablePoly(vList, vIndexes2, 0) vtx = poly2.getAdjacentVertices(poly) print("Vertices adjacent to %s: %s, %s" % (vtx[1], vtx[0], vtx[2])) poly.flipNormal() print("Poly:\n%s" % poly) print("Poly2:\n%s" % poly2) print("Inward normal poly: %s" % poly.checkInwardNormal(poly2)) print("Inward normal poly2: %s" % poly2.checkInwardNormal(poly)) print("Poly.V:\n%s" % poly.V) for v in vList: x = v.np().reshape(4, 1) print(type(x)) print(poly.V * x) print("\nPoly = %s" % poly) print("Poly area = %s" % poly.area()) print("Poly normal = %s" % poly.normal) transf = matrix.rotate(30, 0, 0, 1) vtx = poly.transformPoints(transf) vList = poly.toPoints(vtx) poly2 = SelectablePoly(vList, vIndexes, 0) poly2.flipNormal() print("\nPoly2 = %s" % poly2) print("Poly2 area = %s" % poly2.area()) print("Poly2 normal = %s" % poly2.normal)
def onMouseDragged(self, event): self.updatePosition(event.x, event.y) if self.start is None or self.center is None or self.depth is None: return human = gui3d.app.selectedHuman dist = (event.x - self.start[0]) / 100.0 if self.norm.selected: coord = self.original + dist * self.weights[:,None] * self.normals elif self.scalex.selected: coord = self.scale([1, 0, 0], dist) elif self.scaley.selected: coord = self.scale([0, 1, 0], dist) elif self.scalez.selected: coord = self.scale([0, 0, 1], dist) elif self.rotate.selected: mat = matrix.rotate(-dist * 90, self.axis) mat = np.asarray(mat)[:3,:3] coor = self.original - self.center coor = np.dot(mat, coor.T).T coor += self.center delta = coor - self.original coord = self.original + self.weights[:,None] * delta elif self.smooth.selected: if self.smoothed is None: self.smoothed = self.makeSmoothed() dist = min(1.0, max(0.0, dist)) coord = self.original + self.weights[:,None] * dist * (self.smoothed - self.original) else: x, y, z = gui3d.app.modelCamera.convertToWorld3D(event.x, event.y, self.depth, human.mesh) pos = np.array([x, y, z]) delta = pos - self.center coord = self.original + delta[None,:] * self.weights[:,None] human.meshData.changeCoords(coord, self.verts) human.meshData.calcNormals(True, True, self.verts, self.faces) human.meshData.update() mh.redraw()
def set_add_rotation(self, dx, dy): sens = self.sens self.add_rotation = rotate(sens * dy, -1, 0, 0) @ rotate( sens * dx, 0, -1, 0)
def set_add_rotation_roll(self, dx, dy): roll = -5 * self.sens * (dx - dy) roll_mat = rotate(roll, 0, 0, 1) self.add_roll = roll_mat
def set_add_rotation(self, dx, dy): yaw = self.sens * dx pitch = self.sens * dy yaw_mat = rotate(yaw, 0, 1, 0) pitch_mat = rotate(pitch, 1, 0, 0) self.add_yawpitch = pitch_mat @ yaw_mat
def unit_test_ArcBall_module(): """ Unit testing of the ArcBall class and the real math behind it. Simulates a click and drag followed by another click and drag. """ print("unit testing ArcBall") Transform = Matrix4fT() LastRot = Matrix3fT() ThisRot = Matrix3fT() ArcBall = ArcBallT(640, 480) # print "The ArcBall with NO click" # print ArcBall # First click LastRot = copy.copy(ThisRot) mouse_pt = Point2fT(500, 250) ArcBall.click(mouse_pt) # print "The ArcBall with first click" # print ArcBall # First drag mouse_pt = Point2fT(475, 275) ThisQuat = ArcBall.drag(mouse_pt) # print "The ArcBall after first drag" # print ArcBall # print # print print("Quat for first drag") print(ThisQuat) ThisRot = Matrix3fSetRotationFromQuat4f(ThisQuat) print("Quat4fFromMatrix3") ThisQuat = Quat4fFromMatrix(ThisRot) print(ThisQuat) # Linear Algebra matrix multiplication A = old, B = New : C = A * B ThisRot = Matrix3fMulMatrix3f(LastRot, ThisRot) Transform = Matrix4fSetRotationFromMatrix3f(Transform, ThisRot) print("First transform") print(Transform) # Done with first drag print("slerp qt, t = 0.5") qt = slerp(ThisQuat, Quat4fT(), 0.5) print(qt) # second click LastRot = copy.copy(ThisRot) print("LastRot at end of first drag") print(LastRot) mouse_pt = Point2fT(350, 260) ArcBall.click(mouse_pt) # second drag mouse_pt = Point2fT(450, 260) ThisQuat = ArcBall.drag(mouse_pt) # print "The ArcBall" # print ArcBall print("Quat for second drag") print(ThisQuat) ThisRot = Matrix3fSetRotationFromQuat4f(ThisQuat) ThisRot = Matrix3fMulMatrix3f(LastRot, ThisRot) # print ThisRot Transform = Matrix4fSetRotationFromMatrix3f(Transform, ThisRot) print("Second transform") print(Transform) # Done with second drag LastRot = copy.copy(ThisRot) ang = 32 e0 = 1 e1 = -2 e2 = 33 m = matrix.rotate(ang, e0, e1, e2) len = sqrt(e0 * e0 + e1 * e1 + e2 * e2) print("\nang = %f, x = %f, y =%f, z= %s" % (ang, e0, e1, e2)) print("m = %s" % m) theta, x, y, z = matrixToEulerAxisAngle(Numeric.asarray(m)) print("t = %f, x = %f, y = %f, z = %f\n" % (theta, x * len, y * len, z * len)) ind = 3 aList = [[-34, 56, 120], [45, 90, 45], [10, 20, 30], [-33, -84, 57]] m = Numeric.asarray(matrix.rotateZYX(aList[ind])) x, y, z = rotationMatrixToEulerAngles(m.T) # XYZ q = EulerAnglesToQuaternion(aList[ind]) print("Quat from Euler %s" % q) print("m = \n%s" % m) print(quatToMat(q)) print(quatToEulerAngles(q)) print(aList[ind]) print("x = %f, y = %f, z = %f" % (x, y, z)) print("m = %s" % m) theta, x, y, z = matrixToEulerAxisAngle(m) print("q = %s" % matToQuat(m)) print("W = %s" % Quat4fFromMatrix(m)) print("x = %f, y = %f, z = %f, ang = %f" % (x, y, z, theta))
def rotate_cropped_data(self): if self.has_crop_data: self.data_points = rotate(self.cropped_data, self.cx, self.cy, 0, 360, DELTA_ANGLE, True, self.name) self.has_data_point = True
def rotate_area_data(self): if self.has_area_data: self.area_data_points = rotate(self.area_data, self.cx, self.cy, 0, 360, DELTA_ANGLE, True, self.name)
def runCommands(commands, knobs): """ Runs the given commands and returns the resulting screen """ stack = [matrix.ident()] view = screen.Screen() for command in commands: if command[0] == "ignore": pass if command[0] == "pop": stack.pop() if not stack: stack = [matrix.ident()] if command[0] == "push": stack.append(stack[-1].clone()) if command[0] == "screen": view = screen.Screen(command[1], command[2]) if command[0] == "save": view.save(command[1]) if command[0] == "display": if len(command) == 2: screen.display(command[1]) else: screen.display(view) if command[0] == "set": knobs[command[1]] = float(command[2]) if command[0] == "set_knobs": for name in knobs.keys(): knobs[name] = float(command[1]) if command[0] == "sphere": m = matrix.FaceMatrix() m.add_sphere(*command[1:]) m.apply(stack[-1]) view.draw_FaceMatrix(m, [255, 255, 255]) if command[0] == "torus": m = matrix.FaceMatrix() m.add_torus(*command[1:]) m.apply(stack[-1]) view.draw_FaceMatrix(m, [255, 255, 255]) if command[0] == "box": m = matrix.FaceMatrix() m.add_box(*command[1:]) m.apply(stack[-1]) view.draw_FaceMatrix(m, [255, 255, 255]) if command[0] == "line": m = matrix.EdgeMatrix() m.add_edge(*command[1:]) m.apply(stack[-1]) view.draw_EdgeMatrix(m, [255, 255, 255]) if command[0] == "bezier": m = matrix.EdgeMatrix() m.add_bezier_curve(*command[1:]) m.apply(stack[-1]) view.draw_EdgeMatrix(m, [255, 255, 255]) if command[0] == "hermite": m = matrix.EdgeMatrix() m.add_hermite_curve(*command[1:]) m.apply(stack[-1]) view.draw_EdgeMatrix(m, [255, 255, 255]) if command[0] == "circle": m = matrix.EdgeMatrix() m.add_circle(command[1], command[2], command[3], command[4]) stack.append(stack[-1].clone()) # # # # # m.apply(stack[-1]) stack.pop() view.draw_EdgeMatrix(m, [255, 255, 255]) if command[0] == "move": if command[4]: val = float(knobs[command[4]]) else: val = 1.0 stack[-1] *= matrix.move(command[1] * val, command[2] * val, command[3] * val) if command[0] == "scale": if command[4]: val = float(knobs[command[4]]) else: val = 1.0 stack[-1] *= matrix.scale(command[1] * val, command[2] * val, command[3] * val) if command[0] == "rotate": if command[3]: val = float(knobs[command[3]]) else: val = 1.0 stack[-1] *= matrix.rotate(command[1], command[2] * val) return view
def run(filename): """ This function runs an mdl script """ p = mdl.parseFile(filename) if p: (commands, symbols) = p else: print "Parsing failed." return knobs = {} for s in symbols: if s[0] == "knob": knobs[s[1]] = 0.0 knobs = getKnobValues(knobs) while 1: stack = [matrix.ident()] view = screen.Screen() for command in commands: if command[0] == "pop": stack.pop() if not stack: stack = [matrix.ident()] if command[0] == "push": stack.append(stack[-1].clone()) if command[0] == "screen": view = screen.Screen(command[1], command[2]) if command[0] == "save": view.save(command[1]) if command[0] == "display": if len(command) == 2: screen.display(command[1]) else: screen.display(view) if command[0] == "set": knobs[command[1]] = float(command[2]) if command[0] == "set_knobs": for name in knobs.keys(): knobs[name] = float(command[1]) if command[0] == "sphere": m = matrix.FaceMatrix() m.add_sphere(*command[1:]) m.apply(stack[-1]) view.draw_FaceMatrix(m, [255, 255, 255]) if command[0] == "torus": m = matrix.FaceMatrix() m.add_torus(*command[1:]) m.apply(stack[-1]) view.draw_FaceMatrix(m, [255, 255, 255]) if command[0] == "box": m = matrix.FaceMatrix() m.add_box(*command[1:]) m.apply(stack[-1]) view.draw_FaceMatrix(m, [255, 255, 255]) if command[0] == "line": m = matrix.EdgeMatrix() m.add_edge(*command[1:]) m.apply(stack[-1]) view.draw_EdgeMatrix(m, [255, 255, 255]) if command[0] == "bezier": m = matrix.EdgeMatrix() m.add_bezier_curve(*command[1:]) m.apply(stack[-1]) view.draw_EdgeMatrix(m, [255, 255, 255]) if command[0] == "hermite": m = matrix.EdgeMatrix() m.add_hermite_curve(*command[1:]) m.apply(stack[-1]) view.draw_EdgeMatrix(m, [255, 255, 255]) if command[0] == "circle": m = matrix.EdgeMatrix() m.add_circle(command[1], command[2], command[3], command[4]) stack.append(stack[-1].clone()) # # # # # m.apply(stack[-1]) stack.pop() view.draw_EdgeMatrix(m, [255, 255, 255]) if command[0] == "move": if command[4]: val = float(knobs[command[4]]) else: val = 1.0 stack[-1] *= matrix.move(command[1] * val, command[2] * val, command[3] * val) if command[0] == "scale": if command[4]: val = float(knobs[command[4]]) else: val = 1.0 stack[-1] *= matrix.scale(command[1] * val, command[2] * val, command[3] * val) if command[0] == "rotate": if command[3]: val = float(knobs[command[3]]) else: val = 1.0 stack[-1] *= matrix.rotate(command[1], command[2] * val) while 1: text = raw_input("Continue?\n> ") if not text in ["yes", "no", "n", "y"]: print "I don't understand." elif text in ["yes", "y"]: print break else: return knobs = getKnobValues(knobs)
def run(filename): """ This function runs an mdl script """ p = mdl.parseFile(filename) if p: (commands, symbols) = p else: print "Parsing failed." return arc = {} arc["display"] = [] arc["save"] = [] arc["screen"] = [] arc["vary"] = [] arc["basename"] = [] arc["frames"] = [] arc["tween"] = [] arc["save_knobs"] = [] for command in commands: if arc.has_key(command[0]): arc[command[0]].append(command) if not arc["basename"] and not arc["vary"] and not arc["frames"] and not arc["tween"]: knobs = {} constants = {} coord_systems = {} meshesE = {} meshesF = {} for s in symbols: if s[0] == "knob": knobs[s[1]] = 1.0 if s[0] == "constants": constants[s[1]] = [255, 255, 255, 200, 200, 200, 100, 100, 100, 0, 0, 0] if s[0] == "coord_system": coord_systems[s[1]] = matrix.ident() if s[0] == "mesh": try: meshFile = open(s[1]) line1 = meshFile.readline().strip() if line1 not in ["edges", "faces"]: meshFile.close() continue if line1 == "edges" and not meshesE.has_key(s[1]): m = matrix.EdgeMatrix() for line in meshFile.readlines(): line = line.strip() vals = [float(x) for x in line.split(" ")] m.add_edge(*vals) meshesE[s[1]] = m elif line1 == "faces" and not meshesF.has_key(s[1]): m = matrix.FaceMatrix() for line in meshFile.readlines(): line = line.strip() vals = [float(x) for x in line.split(" ")] m.add_face(*vals) meshesF[s[1]] = m meshFile.close() except: pass for command in arc["save_knobs"]: command[0] = "ignore" while 1: knobs = getKnobValues(knobs) runCommands(commands, knobs, constants, coord_systems, meshesE, meshesF, matrix.ident(), 0) while 1: text = raw_input("Continue?\n> ") if not text in ["yes", "no", "n", "y"]: print "I don't understand." elif text in ["yes", "y"]: print break else: return for command in arc["display"]: command[0] = "ignore" for command in arc["save"]: command[0] = "ignore" for command in arc["screen"]: command[0] = "ignore" knobs = {} constants = {} coord_systems = {} knoblists = {} meshesE = {} meshesF = {} for s in symbols: if s[0] == "knob" and not knobs.has_key(s[1]): knobs[s[1]] = [] if s[0] == "constants" and not constants.has_key(s[1]): constants[s[1]] = [255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0] if s[0] == "coord_system" and not coord_systems.has_key(s[1]): coord_systems[s[1]] = matrix.ident() if s[0] == "mesh": try: meshFile = open(s[1]) line1 = meshFile.readline().strip() if line1 not in ["edges", "faces"]: meshFile.close() continue if line1 == "edges" and not meshesE.has_key(s[1]): m = matrix.EdgeMatrix() for line in meshFile.readlines(): line = line.strip() vals = [float(x) for x in line.split(" ")] m.add_edge(*vals) meshesE[s[1]] = m elif line1 == "faces" and not meshesF.has_key(s[1]): m = matrix.FaceMatrix() for line in meshFile.readlines(): line = line.strip() vals = [float(x) for x in line.split(" ")] m.add_face(*vals) meshesF[s[1]] = m meshFile.close() except: pass for s in symbols: if s[0] == "knoblist" and not knoblists.has_key(s[1]): knoblists[s[1]] = {} for k in knobs.keys(): knoblists[s[1]][k] = 1.0 frames = 1 for command in arc["frames"]: if command[1] > frames: frames = command[1] command[0] = "ignore" for command in arc["vary"]: if command[3] + 1 > frames: frames = command[3] + 1 for command in arc["tween"]: if command[2] + 1 > frames: frames = command[2] + 1 tmpknobs = {} for k in knobs.keys(): tmpknobs[k] = 1.0 image_requests = [] base_matrix = matrix.ident() focalLength = 0 for command in commands: if command[0] == "set": tmpknobs[command[1]] = float(command[2]) command[0] = "ignore" if command[0] == "set_knobs": for k in tmpknobs.keys(): tmpknobs[k] = command[1] command[0] = "ignore" if command[0] == "save_knobs": knoblists[command[1]] = tmpknobs.copy() command[0] = "ignore" if command[0] == "tween": (tweenliteral, start, end, knoblist0, knoblist1, f) = command i = start if start <= end: for k in knobs.keys(): if not knobs[k]: knobs[k] = [None] * frames while i <= end: slider = float(f(float(i - start))) for k in knobs.keys(): knobs[k][i] = slider * knoblists[knoblist1][k] + (1 - slider) * knoblists[knoblist0][k] i = i + 1 command[0] = "ignore" if command[0] == "vary": (varyliteral, knobname, start, end, f) = command i = start if start <= end: if not knobs[knobname]: knobs[knobname] = [None] * frames while i <= end: knobs[knobname][i] = float(f(float(i - start))) i = i + 1 command[0] = "ignore" if command[0] == "basename": image_requests.append([command[1], base_matrix, focalLength]) command[0] = "ignore" if command[0] == "camera": base_matrix = matrix.ident() base_matrix *= matrix.move(0 - command[1], 0 - command[2], 0 - command[3]) xaim = command[4] - command[1] yaim = command[5] - command[2] zaim = command[6] - command[3] if xaim == 0 and zaim == 0: if yaim >= 0: base_matrix *= matrix.rotate("x", -90) else: base_matrix *= matrix.rotate("x", 90) else: theta = (math.atan2(yaim, math.sqrt(math.pow(xaim, 2) + math.pow(zaim, 2)))) * -180.0 / 3.14159265358979323 base_matrix *= matrix.rotate("x", theta) theta = ((math.atan2(zaim, xaim) - math.atan2(1, 0)) * 180.0 / 3.14159265358979323) base_matrix *= matrix.rotate("y", theta) command[0] = "ignore" if command[0] == "focal": focalLength = command[1] command[0] = "ignore" for knobname in knobs.keys(): if not knobs[knobname]: knobs[knobname] = [1.0] * frames values = knobs[knobname] for i in range(frames): if values[i] != None: val = values[i] break for i in range(frames): if values[i] == None: values[i] = val else: val = values[i] for i in range(frames): print "starting frame %d ..." % i, sys.stdout.flush() K = {} for k in knobs: K[k] = knobs[k][i] for basename, base_matrix, focalLength in image_requests: view = runCommands(commands, K, constants, coord_systems, meshesE, meshesF, base_matrix, focalLength) name = (basename + "%0" + str(len(str(frames - 1))) + "d.ppm") % i view.save(name) print "DONE" print "converting to gif format ...", sys.stdout.flush() for name, base_matrix, focalLength in image_requests: os.system("mogrify -format gif %s*.ppm" % name) os.system("convert -delay 2.5 -loop 0 %s[0-9]*.gif %s.gif" % (name, name)) os.system("rm %s*.ppm" % name) print "DONE"
def reset(self): self.rotation = rotate(-90, -1, 0, 0) @ rotate(240, 0, -1, 0) self.add_rotation = np.eye(4)
def runCommands(commands, knobs, constants, coord_systems, meshesE, meshesF, base_matrix, focalLength): """ Runs the given commands and returns the resulting screen """ stack = [base_matrix.clone()] view = screen.Screen() constants[None] = [255, 255, 255, 200, 200, 200, 100, 100, 100, 0, 0, 0] lights = [] ambient = [0, 0, 0] shading_type = "wireframe" for command in commands: if command[0] == "ignore": pass elif command[0] == "pop": stack.pop() if not stack: stack = [base_matrix.clone()] elif command[0] == "push": stack.append(stack[-1].clone()) elif command[0] == "screen": view = screen.Screen(command[1], command[2]) stack = [base_matrix.clone()] elif command[0] == "save": view.save(command[1]) elif command[0] == "display": if len(command) == 2: screen.display(command[1]) else: screen.display(view) elif command[0] == "camera": base_matrix = matrix.ident() base_matrix *= matrix.move(0 - command[1], 0 - command[2], 0 - command[3]) xaim = command[4] - command[1] yaim = command[5] - command[2] zaim = command[6] - command[3] if xaim == 0 and zaim == 0: if yaim >= 0: base_matrix *= matrix.rotate("x", -90) else: base_matrix *= matrix.rotate("x", 90) else: theta = (math.atan2(yaim, math.sqrt(math.pow(xaim, 2) + math.pow(zaim, 2)))) * -180.0 / 3.14159265358979323 base_matrix *= matrix.rotate("x", theta) theta = ((math.atan2(zaim, xaim) - math.atan2(1, 0)) * 180.0 / 3.14159265358979323) base_matrix *= matrix.rotate("y", theta) stack = [base_matrix.clone()] elif command[0] == "focal": focalLength = command[1] view.focalLength = focalLength elif command[0] == "set": knobs[command[1]] = float(command[2]) elif command[0] == "set_knobs": for name in knobs.keys(): knobs[name] = float(command[1]) elif command[0] == "ambient": ambient = command[1:] elif command[0] == "light": lights.append(command[1:]) elif command[0] == "sphere": m = matrix.FaceMatrix() m.add_sphere(*[command[i] for i in range(2, 8) if i != 5]) if command[5]: m.apply(coord_systems[command[5]]) else: m.apply(stack[-1]) view.draw_FaceMatrix(m, [shading_type, constants[command[1]], ambient, lights]) elif command[0] == "torus": m = matrix.FaceMatrix() m.add_torus(*[command[i] for i in range(2, 9) if i != 5]) if command[5]: m.apply(coord_systems[command[5]]) else: m.apply(stack[-1]) view.draw_FaceMatrix(m, [shading_type, constants[command[1]], ambient, lights]) elif command[0] == "box": m = matrix.FaceMatrix() m.add_box(*(command[2:8])) if command[8]: m.apply(coord_systems[command[8]]) else: m.apply(stack[-1]) view.draw_FaceMatrix(m, [shading_type, constants[command[1]], ambient, lights]) elif command[0] == "line": m = matrix.PointMatrix() n = matrix.PointMatrix() m.add_point(*command[2:5]) n.add_point(*command[6:9]) if command[5]: m.apply(coord_systems[command[5]]) else: m.apply(stack[-1]) if command[9]: n.apply(coord_systems[command[9]]) else: n.apply(stack[-1]) [x0, y0, z0] = [m.get(i, 0) for i in range(3)] [x1, y1, z1] = [n.get(i, 0) for i in range(3)] m = matrix.EdgeMatrix() m.add_edge(x0, y0, z0, x1, y1, z1) view.draw_EdgeMatrix(m, [shading_type, constants[command[1]], ambient, lights]) elif command[0] == "bezier": xs = [] ys = [] zs = [] for i in range(4): m = matrix.PointMatrix() m.add_point(*command[2 + 4 * i:5 + 4 * i]) if command[5 + 4 * i]: m.apply(coord_systems[command[5 + 4 * i]]) else: m.apply(stack[-1]) xs.append(m.get(0, 0)) ys.append(m.get(1, 0)) zs.append(m.get(2, 0)) m = matrix.EdgeMatrix() m.add_bezier_curve(xs[0], ys[0], zs[0], xs[1], ys[1], zs[1], xs[2], ys[2], zs[2], xs[3], ys[3], zs[3], command[18]) view.draw_EdgeMatrix(m, [shading_type, constants[command[1]], ambient, lights]) elif command[0] == "hermite": xs = [] ys = [] zs = [] for i in range(4): m = matrix.PointMatrix() m.add_point(*command[2 + 4 * i:5 + 4 * i]) if command[5 + 4 * i]: m.apply(coord_systems[command[5 + 4 * i]]) else: m.apply(stack[-1]) xs.append(m.get(0, 0)) ys.append(m.get(1, 0)) zs.append(m.get(2, 0)) m = matrix.EdgeMatrix() m.add_hermite_curve(xs[0], ys[0], zs[0], xs[1], ys[1], zs[1], xs[2], ys[2], zs[2], xs[3], ys[3], zs[3], command[18]) view.draw_EdgeMatrix(m, [shading_type, constants[command[1]], ambient, lights]) elif command[0] == "mesh": if meshesE.has_key(command[2]): m = meshesE[command[2]].clone() if command[3]: m.apply(coord_systems[command[3]]) else: m.apply(stack[-1]) view.draw_EdgeMatrix(m, [shading_type, constants[command[1]], ambient, lights]) elif meshesF.has_key(command[2]): m = meshesF[command[2]].clone() if command[3]: m.apply(coord_systems[command[3]]) else: m.apply(stack[-1]) view.draw_FaceMatrix(m, [shading_type, constants[command[1]], ambient, lights]) elif command[0] == "save_coord_system": coord_systems[command[1]] = stack[-1].clone() elif command[0] == "constants": constants[command[1]] = command[2:] elif command[0] == "shading": shading_type = command[1] elif command[0] == "move": if command[4]: val = float(knobs[command[4]]) else: val = 1.0 stack[-1] *= matrix.move(command[1] * val, command[2] * val, command[3] * val) elif command[0] == "scale": if command[4]: val = float(knobs[command[4]]) else: val = 1.0 stack[-1] *= matrix.scale(command[1] * val, command[2] * val, command[3] * val) elif command[0] == "scaleXYZ": if command[3]: val = float(knobs[command[3]]) else: val = 1.0 if command[1] == "x": stack[-1] *= matrix.scale(command[2] * val, 1, 1) elif command[1] == "y": stack[-1] *= matrix.scale(1, command[2] * val, 1) else: stack[-1] *= matrix.scale(command[2] * val, 1, 1) elif command[0] == "rotate": if command[3]: val = float(knobs[command[3]]) else: val = 1.0 stack[-1] *= matrix.rotate(command[1], command[2] * val) return view
def rote(self): matrix.rotate(model[self.qlistwidget.currentIndex().row()]['data'], 45, 45, 45) self.opengl_widget.update()
def rotatePolygon(self, x, y): global grabbedPoint global grabbedPolygon global rotationPoint # Returns the angle between three points, in degrees. # Useful for checking how much the polygon should rotate. # Points a, b and c must be in the form np.array([x, y, z]). def angleBetweenPoints(a, b, c): ba = a - b bc = c - b # Avoids a division by zero if (np.linalg.norm(ba) * np.linalg.norm(bc)) == 0: return 0 cosine_angle = np.dot( ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) # Avoids getting the arccos of a nonsensical cosine if cosine_angle > 1: cosine_angle = 1 elif cosine_angle < -1: cosine_angle = -1 angle = np.arccos(cosine_angle) if np.cross(ba, bc)[2] > 0: return np.degrees(angle) else: return np.degrees(-angle) if self == grabbedPolygon: rotationPoint = self.fatherNail # Matrix that rotates the polygon around the father nail. rotationMatrix = matrix.rotate(angleBetweenPoints( \ np.array([grabbedPoint.x, grabbedPoint.y, 0]), \ np.array([rotationPoint.x, rotationPoint.y, 0]), \ np.array([x, y, 0])\ ), \ 0, 0, 1) # The defacto matrix that rotates the polygon. It shifts the polygon so that the father nail # is in the origin, then it rotates around the father nail and finally shifts # back to the original position. nailRotationMatrix = matrix.translate(rotationPoint.x, rotationPoint.y, 0) * \ rotationMatrix * \ matrix.translate(-rotationPoint.x, -rotationPoint.y, 0) # The polygon also moves the nail that attached it to a father. Useful for the recursion. nailVector = [[self.fatherNail.x], [self.fatherNail.y], [0], [1]] rotatedNail = np.array(nailRotationMatrix * nailVector) if np.isnan(rotatedNail[0][0]) or np.isnan(rotatedNail[1][0]): return # nail position isn't updated if there is a NaN value self.fatherNail.x = rotatedNail[0][0] self.fatherNail.y = rotatedNail[1][0] # Each vertex of the polygon is rotated. for vertex in self.vertexes: vertexVector = [[vertex.x], [vertex.y], [vertex.z], [1]] rotatedVector = np.array(nailRotationMatrix * vertexVector) vertex.x = rotatedVector[0][0] vertex.y = rotatedVector[1][0] self.triangulate() # the polygon's respective triangles are updated # Recursively, each descendant of the polygon is translated as well for child in self.children: child.rotatePolygon(x, y) # The root updates the mouse position that is grabbing the polygon, after all # polygons in the tree have moved. if self == grabbedPolygon: grabbedPoint = Vertex(x, y)
def roll(self, ang): self.setDirection('X') self.rotMatrix = matrix.dot(self.rotMatrix, matrix.rotate(ang,1,0,0)) self.rotVector = np.dot (self.initialVector, self.rotMatrix.T.tolist()) if turtle.__toDebug__: print ("roll(%d)" % ang)