我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用mathutils.Matrix()。
def test_bge(): import traceback sys.path.append(build_path) try: import mathutils, bge v=mathutils.Vector() m=mathutils.Matrix() scn = bge.logic.getCurrentScene() o = scn.objects["some"] a=o.isPlayingAction() b=o.parent.addDebugProperty("LOL") o.endObject() print("Test BGE: OK") except Exception: traceback.print_exc()
def __init__(self): self.SPOT = int() self.SUN = int() self.NORMAL = int() self.HEMI = int() self.type = None self.energy = float() self.shadowClipStart = float() self.shadowClipEnd = float() self.shadowFrustumSize = float() self.shadowBindId = int() self.shadowMapType = int() self.shadowBias = float() self.shadowBleedBias = float() self.useShadow = bool() self.shadowColor = mathutils.Color() self.shadowMatrix = mathutils.Matrix() self.distance = float() self.color = [0,0,0] self.lin_attenuation = float() self.quad_attenuation = float() self.spotsize = float() self.spotblend = float() self.staticShadow = bool()
def __init__(self): self.INSIDE = int() self.INTERSECT = int() self.OUTSIDE = int() self.lens = float() self.lodDistanceFactor = float() self.fov = float() self.ortho_scale = float() self.near = float() self.far = float() self.shift_x = float() self.shift_y = float() self.perspective = bool() self.frustum_culling = bool() self.projection_matrix = mathutils.Matrix() self.modelview_matrix = mathutils.Matrix() self.camera_to_world = mathutils.Matrix() self.world_to_camera = mathutils.Matrix() self.useViewport = bool()
def mouse_hover_wall(self, context, event): """ convert mouse pos to matrix at bottom of surrounded wall, y oriented outside wall """ res, pt, y, i, o, tM = self.mouse_to_scene_raycast(context, event) if res and o.data is not None and 'archipack_wall2' in o.data: z = Vector((0, 0, 1)) d = o.data.archipack_wall2[0] y = -y pt += (0.5 * d.width) * y.normalized() x = y.cross(z) return True, Matrix([ [x.x, y.x, z.x, pt.x], [x.y, y.y, z.y, pt.y], [x.z, y.z, z.z, o.matrix_world.translation.z], [0, 0, 0, 1] ]), o, y return False, Matrix(), None, Vector()
def rotate(self, idx_from, a): """ apply rotation to all following segs """ self.segs[idx_from].rotate(a) ca = cos(a) sa = sin(a) rM = Matrix([ [ca, -sa], [sa, ca] ]) # rotation center p0 = self.segs[idx_from].p0 for i in range(idx_from + 1, len(self.segs)): seg = self.segs[i] # rotate seg seg.rotate(a) # rotate delta from rotation center to segment start dp = rM * (seg.p0 - p0) seg.translate(dp)
def create(self, context): curve = context.active_object bpy.ops.archipack.slab(auto_manipulate=self.auto_manipulate) o = context.scene.objects.active d = archipack_slab.datablock(o) spline = curve.data.splines[0] d.from_spline(curve.matrix_world, 12, spline) if spline.type == 'POLY': pt = spline.points[0].co elif spline.type == 'BEZIER': pt = spline.bezier_points[0].co else: pt = Vector((0, 0, 0)) # pretranslate o.matrix_world = curve.matrix_world * Matrix([ [1, 0, 0, pt.x], [0, 1, 0, pt.y], [0, 0, 1, pt.z], [0, 0, 0, 1] ]) return o # ----------------------------------------------------- # Execute # -----------------------------------------------------
def rotate(self, idx_from, a): """ apply rotation to all following segs """ self.segs[idx_from].rotate(a) ca = cos(a) sa = sin(a) rM = Matrix([ [ca, -sa], [sa, ca] ]) # rotation center p0 = self.segs[idx_from].p0 for i in range(idx_from + 1, len(self.segs)): seg = self.segs[i] seg.rotate(a) dp = rM * (seg.p0 - p0) seg.translate(dp)
def create(self, context): curve = context.active_object for spline in curve.data.splines: bpy.ops.archipack.wall2(auto_manipulate=self.auto_manipulate) o = context.scene.objects.active d = archipack_wall2.datablock(o) d.from_spline(curve.matrix_world, 12, spline) if spline.type == 'POLY': pt = spline.points[0].co elif spline.type == 'BEZIER': pt = spline.bezier_points[0].co else: pt = Vector((0, 0, 0)) # pretranslate o.matrix_world = curve.matrix_world * Matrix([ [1, 0, 0, pt.x], [0, 1, 0, pt.y], [0, 0, 1, pt.z], [0, 0, 0, 1] ]) return o # ----------------------------------------------------- # Execute # -----------------------------------------------------
def get_proj_matrix(self, part, t, nose_y): # a matrix to project verts # into uv space for horizontal parts of this step # so uv = (rM * vertex).to_2d() tl = t - nose_y / self.get_length("LEFT") tr = t - nose_y / self.get_length("RIGHT") t2, part, dz, shape = self.get_part(tl, "LEFT") p0 = part.lerp(t2) t2, part, dz, shape = self.get_part(tr, "RIGHT") p1 = part.lerp(t2) v = (p1 - p0).normalized() return Matrix([ [-v.y, v.x, 0, p0.x], [v.x, v.y, 0, p0.y], [0, 0, 1, 0], [0, 0, 0, 1] ]).inverted()
def rotate(self, a): """ Rotate center so we rotate ccw arround p0 """ ca = cos(a) sa = sin(a) rM = Matrix([ [ca, -sa], [sa, ca] ]) p0 = self.p0 self.c = p0 + rM * (self.c - p0) dp = p0 - self.c self.a0 = atan2(dp.y, dp.x) return self # make offset for line / arc, arc / arc
def getmat(bone, active, context, ignoreparent): """Helper function for visual transform copy, gets the active transform in bone space """ obj_act = context.active_object data_bone = obj_act.data.bones[bone.name] #all matrices are in armature space unless commented otherwise otherloc = active.matrix # final 4x4 mat of target, location. bonemat_local = data_bone.matrix_local.copy() # self rest matrix if data_bone.parent: parentposemat = obj_act.pose.bones[data_bone.parent.name].matrix.copy() parentbonemat = data_bone.parent.matrix_local.copy() else: parentposemat = parentbonemat = Matrix() if parentbonemat == parentposemat or ignoreparent: newmat = bonemat_local.inverted() * otherloc else: bonemat = parentbonemat.inverted() * bonemat_local newmat = bonemat.inverted() * parentposemat.inverted() * otherloc return newmat
def to_matrix(self): """ mat = M(to original transform)^-1 * Mt(to origin) * Ms * Mt(to origin)^-1 * M(to original transform) """ m = self.__mat mi = self.__mat.inverted() mtoi = mathutils.Matrix.Translation((-self.__iox, -self.__ioy, 0.0)) mto = mathutils.Matrix.Translation((self.__iox, self.__ioy, 0.0)) # every point must be transformed to origin t = m * mathutils.Vector((self.__ix, self.__iy, 0.0)) tix, tiy = t.x, t.y t = m * mathutils.Vector((self.__ox, self.__oy, 0.0)) tox, toy = t.x, t.y t = m * mathutils.Vector((self.__x, self.__y, 0.0)) tx, ty = t.x, t.y ms = mathutils.Matrix() ms.identity() if self.__dir_x == 1: ms[0][0] = (tx - tox) * self.__dir_x / (tix - tox) if self.__dir_y == 1: ms[1][1] = (ty - toy) * self.__dir_y / (tiy - toy) return mi * mto * ms * mtoi * m
def get_view_projection_matrix(context, settings): """ Returns view projection matrix. Projection matrix is either identity if 3d export is selected or camera projection if a camera or view is selected. Currently only orthographic projection is used. (Subject to discussion). """ cam = settings['projectionThrough'] if cam is None: mw = mathutils.Matrix() mw.identity() elif cam in projectionMapping.keys(): projection = mathutils.Matrix.OrthoProjection(projectionMapping[cam], 4) mw = projection else: # get camera with given name c = context.scene.objects[cam] mw = getCameraMatrix(c) return mw
def z_up_matrix(n): """Get a rotation matrix that aligns given vector upwards.""" b = n.xy.length l = n.length if b > 0: return M.Matrix(( (n.x*n.z/(b*l), n.y*n.z/(b*l), -b/l), (-n.y/b, n.x/b, 0), (0, 0, 0) )) else: # no need for rotation return M.Matrix(( (1, 0, 0), (0, (-1 if n.z < 0 else 1), 0), (0, 0, 0) ))
def finalize_islands(self, is_landscape=False, title_height=0): for island in self.islands: if title_height: island.title = "[{}] {}".format(island.abbreviation, island.label) points = list(vertex.co for vertex in island.verts) + island.fake_verts angle = M.geometry.box_fit_2d(points) rot = M.Matrix.Rotation(angle, 2) # ensure that the island matches page orientation (portrait/landscape) dimensions = M.Vector(max(r * v for v in points) - min(r * v for v in points) for r in rot) if dimensions.x > dimensions.y != is_landscape: rot = M.Matrix.Rotation(angle + pi / 2, 2) for point in points: # note: we need an in-place operation, and Vector.rotate() seems to work for 3d vectors only point[:] = rot * point for marker in island.markers: marker.rot = rot * marker.rot bottom_left = M.Vector((min(v.x for v in points), min(v.y for v in points) - title_height)) for point in points: point -= bottom_left island.bounding_box = M.Vector((max(v.x for v in points), max(v.y for v in points)))
def execute(self, context): bpy.ops.object.parent_set(type='BONE') if bpy.context.active_bone.parent: to_parent_matrix = bpy.context.active_bone.parent.matrix_local else: to_parent_matrix = Matrix() from_parent_matrix, bone_matrix = bpy.context.active_bone.RobotEditor.getTransform() armature_matrix = bpy.context.active_object.matrix_basis # find selected physics frame for ob in bpy.data.objects: if ob.select and ob.RobotEditor.tag == 'PHYSICS_FRAME': frame = ob print(frame.name) # frame.matrix_basis = armature_matrix*to_parent_matrix*from_parent_matrix*bone_matrix # frame.matrix_basis = parent_matrix*armature_matrix*bone_matrix return {'FINISHED'}
def setup(): global init if init: return init = True view_matrix = workplane.data.get_view_matrix() zero = Matrix() zero.zero() #print(view_matrix) if view_matrix != zero: #print("found matrix display") global matrix matrix = view_matrix enable() #print ("setup done")
def set_transform_orientation(self, context, transform_orientation): #print("catching space: " + transform_orientation) #op.create_orientation doesn't work if nothing is selected, so I missuse the view orientation a bit to cicumvent use_view = transform_orientation == "VIEW" or transform_orientation.endswith("_EMPTY") bpy.ops.transform.create_orientation(name=work_plane, use=True, use_view=use_view, overwrite=True) current = context.space_data.current_orientation if transform_orientation.startswith("GLOBAL"): current.matrix = Matrix().to_3x3() if transform_orientation.startswith("LOCAL"): active_object = context.active_object current.matrix = active_object.matrix_world.to_3x3() return current.matrix
def compute_rest( self ): # called after rebuild_tree, recursive roots to leaves if self.parent: inverseParentMatrix = self.parent.inverse_total_trans elif self.fixUpAxis: inverseParentMatrix = self.flipMat else: inverseParentMatrix = mathutils.Matrix(((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1))) #self.ogre_rest_matrix = self.skeleton.object_space_transformation * self.matrix # ALLOW ROTATION? self.ogre_rest_matrix = self.matrix.copy() # store total inverse transformation self.inverse_total_trans = self.ogre_rest_matrix.inverted() # relative to OGRE parent bone origin self.ogre_rest_matrix = inverseParentMatrix * self.ogre_rest_matrix self.inverse_ogre_rest_matrix = self.ogre_rest_matrix.inverted() # recursion for child in self.children: child.compute_rest()
def apply(self, bone, json_obj, MhNoLocation): # the dots in collada exported bone names are replaced with '_', check for data with that changed back name = bone.name.replace("_", ".") if not self.haveDots else bone.name if name in json_obj.data: bone.matrix = Matrix(json_obj.data[name]) if MhNoLocation: bone.location[0] = 0 bone.location[1] = 0 bone.location[2] = 0 # this operation every bone causes all matrices to be applied in one run bpy.ops.pose.select_all(action='SELECT') else: print(name + ' bone not found coming from MH')
def get_vertical_mode_matrix(is_vertical, camera_rotation): if is_vertical: # Get the up direction of the camera up_vec = mathutils.Vector((0.0, 1.0, 0.0)) up_vec.rotate(camera_rotation) # Decide around which axis to rotate vert_mode_rotate_x = abs(up_vec[0]) < abs(up_vec[1]) # Create rotation matrix if vert_mode_rotate_x: vert_angle = pi / 2 if up_vec[1] > 0 else -pi / 2 return mathutils.Matrix().Rotation(vert_angle, 3, "X") else: vert_angle = pi / 2 if up_vec[0] < 0 else -pi / 2 return mathutils.Matrix().Rotation(vert_angle, 3, "Y") else: return mathutils.Matrix().Identity(3)
def change_coordsys(self, fromTM, toTM): """ move shape fromTM into toTM coordsys """ dp = (toTM.inverted() * fromTM.translation).to_2d() da = toTM.row[1].to_2d().angle_signed(fromTM.row[1].to_2d()) ca = cos(da) sa = sin(da) rM = Matrix([ [ca, -sa], [sa, ca] ]) for s in self.segs: tp = (rM * s.p0) - s.p0 + dp s.rotate(da) s.translate(tp)
def relocate_child(self, context, o, g, child): d = archipack_roof.datablock(child) if d is not None and d.t_part - 1 < len(g.segs): # print("relocate_child(%s)" % (child.name)) seg = g.segs[d.t_part] # adjust T part matrix_world from parent # T part origin located on parent axis # with y in parent direction t = (d.t_dist_x / seg.length) x, y, z = seg.lerp(t).to_3d() dy = -seg.v.normalized() child.matrix_world = o.matrix_world * Matrix([ [dy.x, -dy.y, 0, x], [dy.y, dy.x, 0, y], [0, 0, 1, z], [0, 0, 0, 1] ])
def scale_rot_matrix(self, u, v): """ given vector u and v (from and to p0 p1) apply scale factor to radius and return a matrix to rotate and scale the center around u origin so arc fit v """ # signed angle old new vectors (rotation) a = self.signed_angle(u, v) # scale factor scale = v.length / u.length ca = scale * cos(a) sa = scale * sin(a) return scale, Matrix([ [ca, -sa], [sa, ca] ])
def extrusion_to_matrix(entity): """ Converts an extrusion vector to a rotation matrix that denotes the transformation between world coordinate system and the entity's own coordinate system (described by the extrusion vector). """ def arbitrary_x_axis(extrusion_normal): world_y = Vector((0, 1, 0)) world_z = Vector((0, 0, 1)) if abs(extrusion_normal[0]) < 1 / 64 and abs(extrusion_normal[1]) < 1 / 64: a_x = world_y.cross(extrusion_normal) else: a_x = world_z.cross(extrusion_normal) a_x.normalize() return a_x, extrusion_normal.cross(a_x) az = Vector(entity.extrusion) ax, ay = arbitrary_x_axis(az) return Matrix((ax, ay, az)).inverted()
def get_view_projection_matrix(context, settings): """ Returns view projection matrix. Projection matrix is either identity if 3d export is selected or camera projection if a camera or view is selected. Currently only orthographic projection is used. (Subject to discussion). """ cam = settings['projectionThrough'] if cam == None: mw = mathutils.Matrix() mw.identity() elif cam in projectionMapping.keys(): projection = mathutils.Matrix.OrthoProjection(projectionMapping[cam], 4) mw = projection else: # get camera with given name c = context.scene.objects[cam] mw = getCameraMatrix(c) return mw
def finalize_islands(self, title_height=0): for island in self.islands: if title_height: island.title = "[{}] {}".format(island.abbreviation, island.label) points = list(vertex.co for vertex in island.verts) + island.fake_verts angle = M.geometry.box_fit_2d(points) rot = M.Matrix.Rotation(angle, 2) for point in points: # note: we need an in-place operation, and Vector.rotate() seems to work for 3d vectors only point[:] = rot * point for marker in island.markers: marker.rot = rot * marker.rot bottom_left = M.Vector((min(v.x for v in points), min(v.y for v in points) - title_height)) for point in points: point -= bottom_left island.bounding_box = M.Vector((max(v.x for v in points), max(v.y for v in points)))
def _areDifferent_Mat44(self, mat1, mat2, thresholdLoc = 1.0, thresholdRot = 1.0): """ Check if 2 input matrices are different above a certain threshold. :param mat1: input Matrix :param mat2: input Matrix :param thresholdLoc: threshold above which delta translation between the 2 matrix has to be for them to be qualified as different :param thresholdRot: threshold above which delta rotation between the 2 matrix has to be for them to be qualified as different :type mat1: mathutils.Matrix :type mat2: mathutils.Matrix :type thresholdLoc: Float :type thresholdRot: Float :return: a boolean stating wheter the two matrices are different :rtype: Boolean """ areDifferent = False jnd_vect = mathutils.Vector((thresholdLoc,thresholdLoc,thresholdRot)) t1, t2 = mat1.to_translation(), mat2.to_translation() r1, r2 = mat1.to_euler(), mat2.to_euler() for n in range(3): if (abs(t1[n]-t2[n]) > thresholdLoc) or (abs(math.degrees(r1[n]-r2[n])) > thresholdRot): areDifferent = True return areDifferent
def transform_bone_matrix(bone): if not bone.parent: return Matrix() i1 = Vector((1.0, 0.0, 0.0)) i2 = Vector((0.0, 1.0, 0.0)) i3 = Vector((0.0, 0.0, 1.0)) x_axis = bone.y_axis y_axis = bone.x_axis z_axis = -bone.z_axis row_x = Vector((x_axis * i1, x_axis * i2, x_axis * i3)) row_y = Vector((y_axis * i1, y_axis * i2, y_axis * i3)) row_z = Vector((z_axis * i1, z_axis * i2, z_axis * i3)) trans_matrix = Matrix((row_x, row_y, row_z)) location = trans_matrix * bone.matrix.translation bone_matrix = trans_matrix.to_4x4() bone_matrix.translation = -location return bone_matrix
def _create_mesh_object(self, bm, name): # Transform the coordinate system so that Y is up. matrix_y_to_z = Matrix(((1, 0, 0), (0, 0, -1), (0, 1, 0))) bmesh.ops.transform(bm, matrix=matrix_y_to_z, verts=bm.verts) # Create the mesh into which each bmesh will be written. mesh = bpy.data.meshes.new(name) bm.to_mesh(mesh) bm.free() # Create, group and link an object representing that mesh. ob = bpy.data.objects.new(name, mesh) self._add_to_group(ob, "KCL") bpy.context.scene.objects.link(ob)
def read_matrix4x3(self): matrix = mathutils.Matrix() matrix[0][0] = self.read_single() matrix[0][1] = self.read_single() matrix[0][2] = self.read_single() matrix[1][0] = self.read_single() matrix[1][1] = self.read_single() matrix[1][2] = self.read_single() matrix[2][0] = self.read_single() matrix[2][1] = self.read_single() matrix[2][2] = self.read_single() matrix[3][0] = self.read_single() matrix[3][1] = self.read_single() matrix[3][2] = self.read_single() return matrix
def getWheelOrientationQuaternion(self, wheelIndex): """Returns the wheel orientation as a quaternion.""" return mathutils.Matrix()
def getWorldToCamera(self): """Returns the world-to-camera transform.""" return mathutils.Matrix()
def __call__(self, bm: BMesh = Required, mat: Matrix = None): color = self.node.face_color[:] if mat is not None: if self.node.use_ops_trans: bm = bm.copy() matrix = mu.Matrix(mat) bmesh.ops.transform(bm, matrix=matrix, verts=bm.verts) verts = [v.co[:] for v in bm.verts] bm.normal_update() normals = [f.normal[:] for f in bm.faces] else: matrix = mu.Matrix(mat) verts = [matrix * v.co for v in bm.verts] bm.normal_update() mat33 = matrix.to_3x3() normals = [(mat33 * f.normal)[:] for f in bm.faces] else: verts = [v.co[:] for v in bm.verts] bm.normal_update() normals = [f.normal[:] for f in bm.faces] tess_faces = bm.calc_tessface() vert_index = [l.vert.index for l in itertools.chain(*bm.calc_tessface())] face_index = [t_f[0].face.index for t_f in tess_faces] edges_index = [(e.verts[0].index, e.verts[1].index) for e in bm.edges] colors = [] for idx in face_index: normal = mu.Vector(normals[idx]) normal_nu = normal.angle((0, 0, 1), 0) / np.pi r = (normal_nu * color[0]) + 0.1 g = (normal_nu * color[1]) + 0.1 b = (normal_nu * color[2]) + 0.1 colors.append((r, g, b)) self.vertices.append(verts) self.faces.append(vert_index if self.node.display_face else []) self.colors.append(colors) self.edges.append(edges_index)
def __call__(self, verts: Vertices = Required, edges: Edges = None, faces: Faces = None, mat: Matrix = None): bm = bmesh_from_pydata(verts[:, :3].tolist(), edges, faces) super().__call__(bm, mat)
def get_object_rotational_matrix(): return mathutils.Matrix(bpy.context.active_object.matrix_world).to_quaternion().to_matrix()